blob: 9e96a6d9a87474fe5b8343fcedb10ae0e7d25830 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00002from unittest import mock
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
6import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04007import io
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03008import itertools
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Gregory P. Smith580d2782019-09-11 04:23:05 -050013import traceback
Charles-François Natali3a4586a2013-11-08 19:56:59 +010014import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000015import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000016import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040017import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020018import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050019import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030020import textwrap
Patrick McLean2b2ead72019-09-12 10:15:44 -070021import json
Serhiy Storchakab21d1552018-03-02 11:53:51 +020022from test.support import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050023
24try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020025 import _testcapi
26except ImportError:
27 _testcapi = None
28
Patrick McLean2b2ead72019-09-12 10:15:44 -070029try:
30 import pwd
31except ImportError:
32 pwd = None
33try:
34 import grp
35except ImportError:
36 grp = None
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020037
Steve Dower22d06982016-09-06 19:38:15 -070038if support.PGO:
39 raise unittest.SkipTest("test is not helpful for PGO")
40
Victor Stinner937ee9e2018-06-26 02:11:06 +020041mswindows = (sys.platform == "win32")
42
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000043#
44# Depends on the following external programs: Python
45#
46
Victor Stinner937ee9e2018-06-26 02:11:06 +020047if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000048 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
49 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000050else:
51 SETBINARY = ''
52
Victor Stinner9a83f652017-08-21 23:51:31 +020053NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010054# Ignore errors that indicate the command was not found
55NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020056
Gregory P. Smith67b93f82019-10-12 16:35:53 -070057ZERO_RETURN_CMD = (sys.executable, '-c', 'pass')
58
59
60def setUpModule():
61 shell_true = shutil.which('true')
Pablo Galindo46113e02019-10-13 02:40:24 +010062 if shell_true is None:
63 return
Gregory P. Smith67b93f82019-10-12 16:35:53 -070064 if (os.access(shell_true, os.X_OK) and
65 subprocess.run([shell_true]).returncode == 0):
66 global ZERO_RETURN_CMD
67 ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup.
68
Florent Xiclunab1e94e82010-02-27 22:12:37 +000069
Florent Xiclunac049d872010-03-27 22:47:23 +000070class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000071 def setUp(self):
72 # Try to minimize the number of children we have so this test
73 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000074 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000076 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030077 if not mswindows:
78 # subprocess._active is not used on Windows and is set to None.
79 for inst in subprocess._active:
80 inst.wait()
81 subprocess._cleanup()
82 self.assertFalse(
83 subprocess._active, "subprocess._active not empty"
84 )
Victor Stinnercc42c122017-07-28 18:00:22 +020085 self.doCleanups()
86 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000087
Florent Xiclunab1e94e82010-02-27 22:12:37 +000088 def assertStderrEqual(self, stderr, expected, msg=None):
89 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
90 # shutdown time. That frustrates tests trying to check stderr produced
91 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000092 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040093 # strip_python_stderr also strips whitespace, so we do too.
94 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000095 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000096
Florent Xiclunac049d872010-03-27 22:47:23 +000097
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080098class PopenTestException(Exception):
99 pass
100
101
102class PopenExecuteChildRaises(subprocess.Popen):
103 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
104 _execute_child fails.
105 """
106 def _execute_child(self, *args, **kwargs):
107 raise PopenTestException("Forced Exception for Test")
108
109
Florent Xiclunac049d872010-03-27 22:47:23 +0000110class ProcessTestCase(BaseTestCase):
111
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700112 def test_io_buffered_by_default(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700113 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700114 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
115 stderr=subprocess.PIPE)
116 try:
117 self.assertIsInstance(p.stdin, io.BufferedIOBase)
118 self.assertIsInstance(p.stdout, io.BufferedIOBase)
119 self.assertIsInstance(p.stderr, io.BufferedIOBase)
120 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700121 p.stdin.close()
122 p.stdout.close()
123 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700124 p.wait()
125
126 def test_io_unbuffered_works(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700127 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700128 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
129 stderr=subprocess.PIPE, bufsize=0)
130 try:
131 self.assertIsInstance(p.stdin, io.RawIOBase)
132 self.assertIsInstance(p.stdout, io.RawIOBase)
133 self.assertIsInstance(p.stderr, io.RawIOBase)
134 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700135 p.stdin.close()
136 p.stdout.close()
137 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700138 p.wait()
139
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000141 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000142 rc = subprocess.call([sys.executable, "-c",
143 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000144 self.assertEqual(rc, 47)
145
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400146 def test_call_timeout(self):
147 # call() function with timeout argument; we want to test that the child
148 # process gets killed when the timeout expires. If the child isn't
149 # killed, this call will deadlock since subprocess.call waits for the
150 # child.
151 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
152 [sys.executable, "-c", "while True: pass"],
153 timeout=0.1)
154
Peter Astrand454f7672005-01-01 09:36:35 +0000155 def test_check_call_zero(self):
156 # check_call() function with zero return code
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700157 rc = subprocess.check_call(ZERO_RETURN_CMD)
Peter Astrand454f7672005-01-01 09:36:35 +0000158 self.assertEqual(rc, 0)
159
160 def test_check_call_nonzero(self):
161 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000162 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000163 subprocess.check_call([sys.executable, "-c",
164 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000165 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000166
Georg Brandlf9734072008-12-07 15:30:06 +0000167 def test_check_output(self):
168 # check_output() function with zero return code
169 output = subprocess.check_output(
170 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000171 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000172
173 def test_check_output_nonzero(self):
174 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000175 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000176 subprocess.check_output(
177 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000178 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000179
180 def test_check_output_stderr(self):
181 # check_output() function stderr redirected to stdout
182 output = subprocess.check_output(
183 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
184 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000185 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000186
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300187 def test_check_output_stdin_arg(self):
188 # check_output() can be called with stdin set to a file
189 tf = tempfile.TemporaryFile()
190 self.addCleanup(tf.close)
191 tf.write(b'pear')
192 tf.seek(0)
193 output = subprocess.check_output(
194 [sys.executable, "-c",
195 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
196 stdin=tf)
197 self.assertIn(b'PEAR', output)
198
199 def test_check_output_input_arg(self):
200 # check_output() can be called with input set to a string
201 output = subprocess.check_output(
202 [sys.executable, "-c",
203 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
204 input=b'pear')
205 self.assertIn(b'PEAR', output)
206
Georg Brandlf9734072008-12-07 15:30:06 +0000207 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300208 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000209 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000210 output = subprocess.check_output(
211 [sys.executable, "-c", "print('will not be run')"],
212 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000213 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000214 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000215
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300216 def test_check_output_stdin_with_input_arg(self):
217 # check_output() refuses to accept 'stdin' with 'input'
218 tf = tempfile.TemporaryFile()
219 self.addCleanup(tf.close)
220 tf.write(b'pear')
221 tf.seek(0)
222 with self.assertRaises(ValueError) as c:
223 output = subprocess.check_output(
224 [sys.executable, "-c", "print('will not be run')"],
225 stdin=tf, input=b'hare')
226 self.fail("Expected ValueError when stdin and input args supplied.")
227 self.assertIn('stdin', c.exception.args[0])
228 self.assertIn('input', c.exception.args[0])
229
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400230 def test_check_output_timeout(self):
231 # check_output() function with timeout arg
232 with self.assertRaises(subprocess.TimeoutExpired) as c:
233 output = subprocess.check_output(
234 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200235 "import sys, time\n"
236 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400237 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200238 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400239 # Some heavily loaded buildbots (sparc Debian 3.x) require
240 # this much time to start and print.
241 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400242 self.fail("Expected TimeoutExpired.")
243 self.assertEqual(c.exception.output, b'BDFL')
244
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000246 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 newenv = os.environ.copy()
248 newenv["FRUIT"] = "banana"
249 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000250 'import sys, os;'
251 'sys.exit(os.getenv("FRUIT")=="banana")'],
252 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000253 self.assertEqual(rc, 1)
254
Victor Stinner87b9bc32011-06-01 00:57:47 +0200255 def test_invalid_args(self):
256 # Popen() called with invalid arguments should raise TypeError
257 # but Popen.__del__ should not complain (issue #12085)
258 with support.captured_stderr() as s:
259 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
260 argcount = subprocess.Popen.__init__.__code__.co_argcount
261 too_many_args = [0] * (argcount + 1)
262 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
263 self.assertEqual(s.getvalue(), '')
264
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000266 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000267 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000269 self.addCleanup(p.stdout.close)
270 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271 p.wait()
272 self.assertEqual(p.stdin, None)
273
274 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200275 # .stdout is None when not redirected, and the child's stdout will
276 # be inherited from the parent. In order to test this we run a
277 # subprocess in a subprocess:
278 # this_test
279 # \-- subprocess created by this test (parent)
280 # \-- subprocess created by the parent subprocess (child)
281 # The parent doesn't specify stdout, so the child will use the
282 # parent's stdout. This test checks that the message printed by the
283 # child goes to the parent stdout. The parent also checks that the
284 # child's stdout is None. See #11963.
285 code = ('import sys; from subprocess import Popen, PIPE;'
286 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
287 ' stdin=PIPE, stderr=PIPE);'
288 'p.wait(); assert p.stdout is None;')
289 p = subprocess.Popen([sys.executable, "-c", code],
290 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
291 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000292 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200293 out, err = p.communicate()
294 self.assertEqual(p.returncode, 0, err)
295 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296
297 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000298 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000299 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000300 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000301 self.addCleanup(p.stdout.close)
302 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000303 p.wait()
304 self.assertEqual(p.stderr, None)
305
Chris Jerdonek776cb192012-10-08 15:56:43 -0700306 def _assert_python(self, pre_args, **kwargs):
307 # We include sys.exit() to prevent the test runner from hanging
308 # whenever python is found.
309 args = pre_args + ["import sys; sys.exit(47)"]
310 p = subprocess.Popen(args, **kwargs)
311 p.wait()
312 self.assertEqual(47, p.returncode)
313
314 def test_executable(self):
315 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700316 #
317 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
318 # determine where its standard library is, so we need the directory
319 # of args[0] to be valid for the Popen() call to Python to succeed.
320 # See also issue #16170 and issue #7774.
321 doesnotexist = os.path.join(os.path.dirname(sys.executable),
322 "doesnotexist")
323 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700324
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300325 def test_bytes_executable(self):
326 doesnotexist = os.path.join(os.path.dirname(sys.executable),
327 "doesnotexist")
328 self._assert_python([doesnotexist, "-c"],
329 executable=os.fsencode(sys.executable))
330
331 def test_pathlike_executable(self):
332 doesnotexist = os.path.join(os.path.dirname(sys.executable),
333 "doesnotexist")
334 self._assert_python([doesnotexist, "-c"],
335 executable=FakePath(sys.executable))
336
Chris Jerdonek776cb192012-10-08 15:56:43 -0700337 def test_executable_takes_precedence(self):
338 # Check that the executable argument takes precedence over args[0].
339 #
340 # Verify first that the call succeeds without the executable arg.
341 pre_args = [sys.executable, "-c"]
342 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100343 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100344 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100345 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700346
Victor Stinner937ee9e2018-06-26 02:11:06 +0200347 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700348 def test_executable_replaces_shell(self):
349 # Check that the executable argument replaces the default shell
350 # when shell=True.
351 self._assert_python([], executable=sys.executable, shell=True)
352
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300353 @unittest.skipIf(mswindows, "executable argument replaces shell")
354 def test_bytes_executable_replaces_shell(self):
355 self._assert_python([], executable=os.fsencode(sys.executable),
356 shell=True)
357
358 @unittest.skipIf(mswindows, "executable argument replaces shell")
359 def test_pathlike_executable_replaces_shell(self):
360 self._assert_python([], executable=FakePath(sys.executable),
361 shell=True)
362
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700363 # For use in the test_cwd* tests below.
364 def _normalize_cwd(self, cwd):
365 # Normalize an expected cwd (for Tru64 support).
366 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
367 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300368 with support.change_cwd(cwd):
369 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700370
371 # For use in the test_cwd* tests below.
372 def _split_python_path(self):
373 # Return normalized (python_dir, python_base).
374 python_path = os.path.realpath(sys.executable)
375 return os.path.split(python_path)
376
377 # For use in the test_cwd* tests below.
378 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
379 # Invoke Python via Popen, and assert that (1) the call succeeds,
380 # and that (2) the current working directory of the child process
381 # matches *expected_cwd*.
382 p = subprocess.Popen([python_arg, "-c",
383 "import os, sys; "
384 "sys.stdout.write(os.getcwd()); "
385 "sys.exit(47)"],
386 stdout=subprocess.PIPE,
387 **kwargs)
388 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000389 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700390 self.assertEqual(47, p.returncode)
391 normcase = os.path.normcase
392 self.assertEqual(normcase(expected_cwd),
393 normcase(p.stdout.read().decode("utf-8")))
394
395 def test_cwd(self):
396 # Check that cwd changes the cwd for the child process.
397 temp_dir = tempfile.gettempdir()
398 temp_dir = self._normalize_cwd(temp_dir)
399 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
400
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300401 def test_cwd_with_bytes(self):
402 temp_dir = tempfile.gettempdir()
403 temp_dir = self._normalize_cwd(temp_dir)
404 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
405
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530406 def test_cwd_with_pathlike(self):
407 temp_dir = tempfile.gettempdir()
408 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200409 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530410
Victor Stinner937ee9e2018-06-26 02:11:06 +0200411 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700412 def test_cwd_with_relative_arg(self):
413 # Check that Popen looks for args[0] relative to cwd if args[0]
414 # is relative.
415 python_dir, python_base = self._split_python_path()
416 rel_python = os.path.join(os.curdir, python_base)
417 with support.temp_cwd() as wrong_dir:
418 # Before calling with the correct cwd, confirm that the call fails
419 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700420 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700421 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700422 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700423 [rel_python], cwd=wrong_dir)
424 python_dir = self._normalize_cwd(python_dir)
425 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
426
Victor Stinner937ee9e2018-06-26 02:11:06 +0200427 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700428 def test_cwd_with_relative_executable(self):
429 # Check that Popen looks for executable relative to cwd if executable
430 # is relative (and that executable takes precedence over args[0]).
431 python_dir, python_base = self._split_python_path()
432 rel_python = os.path.join(os.curdir, python_base)
433 doesntexist = "somethingyoudonthave"
434 with support.temp_cwd() as wrong_dir:
435 # Before calling with the correct cwd, confirm that the call fails
436 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700437 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700438 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700439 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700440 [doesntexist], executable=rel_python,
441 cwd=wrong_dir)
442 python_dir = self._normalize_cwd(python_dir)
443 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
444 cwd=python_dir)
445
446 def test_cwd_with_absolute_arg(self):
447 # Check that Popen can find the executable when the cwd is wrong
448 # if args[0] is an absolute path.
449 python_dir, python_base = self._split_python_path()
450 abs_python = os.path.join(python_dir, python_base)
451 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300452 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700453 # Before calling with an absolute path, confirm that using a
454 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700455 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700456 [rel_python], cwd=wrong_dir)
457 wrong_dir = self._normalize_cwd(wrong_dir)
458 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
459
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100460 @unittest.skipIf(sys.base_prefix != sys.prefix,
461 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000462 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700463 python_dir, python_base = self._split_python_path()
464 python_dir = self._normalize_cwd(python_dir)
465 self._assert_cwd(python_dir, "somethingyoudonthave",
466 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000467
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100468 @unittest.skipIf(sys.base_prefix != sys.prefix,
469 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000470 @unittest.skipIf(sysconfig.is_python_build(),
471 "need an installed Python. See #7774")
472 def test_executable_without_cwd(self):
473 # For a normal installation, it should work without 'cwd'
474 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700475 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
476 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000477
478 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000479 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000480 p = subprocess.Popen([sys.executable, "-c",
481 'import sys; sys.exit(sys.stdin.read() == "pear")'],
482 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000483 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484 p.stdin.close()
485 p.wait()
486 self.assertEqual(p.returncode, 1)
487
488 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000489 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000490 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000491 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000493 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 os.lseek(d, 0, 0)
495 p = subprocess.Popen([sys.executable, "-c",
496 'import sys; sys.exit(sys.stdin.read() == "pear")'],
497 stdin=d)
498 p.wait()
499 self.assertEqual(p.returncode, 1)
500
501 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000502 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000503 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000504 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000505 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000506 tf.seek(0)
507 p = subprocess.Popen([sys.executable, "-c",
508 'import sys; sys.exit(sys.stdin.read() == "pear")'],
509 stdin=tf)
510 p.wait()
511 self.assertEqual(p.returncode, 1)
512
513 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000514 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000515 p = subprocess.Popen([sys.executable, "-c",
516 'import sys; sys.stdout.write("orange")'],
517 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200518 with p:
519 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520
521 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000522 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000523 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000524 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525 d = tf.fileno()
526 p = subprocess.Popen([sys.executable, "-c",
527 'import sys; sys.stdout.write("orange")'],
528 stdout=d)
529 p.wait()
530 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000531 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532
533 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000534 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000535 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000536 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537 p = subprocess.Popen([sys.executable, "-c",
538 'import sys; sys.stdout.write("orange")'],
539 stdout=tf)
540 p.wait()
541 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000542 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543
544 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000545 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546 p = subprocess.Popen([sys.executable, "-c",
547 'import sys; sys.stderr.write("strawberry")'],
548 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200549 with p:
550 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551
552 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000553 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000554 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000555 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556 d = tf.fileno()
557 p = subprocess.Popen([sys.executable, "-c",
558 'import sys; sys.stderr.write("strawberry")'],
559 stderr=d)
560 p.wait()
561 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000562 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563
564 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000565 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000566 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000567 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568 p = subprocess.Popen([sys.executable, "-c",
569 'import sys; sys.stderr.write("strawberry")'],
570 stderr=tf)
571 p.wait()
572 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000573 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000574
Martin Panterc7635892016-05-13 01:54:44 +0000575 def test_stderr_redirect_with_no_stdout_redirect(self):
576 # test stderr=STDOUT while stdout=None (not set)
577
578 # - grandchild prints to stderr
579 # - child redirects grandchild's stderr to its stdout
580 # - the parent should get grandchild's stderr in child's stdout
581 p = subprocess.Popen([sys.executable, "-c",
582 'import sys, subprocess;'
583 'rc = subprocess.call([sys.executable, "-c",'
584 ' "import sys;"'
585 ' "sys.stderr.write(\'42\')"],'
586 ' stderr=subprocess.STDOUT);'
587 'sys.exit(rc)'],
588 stdout=subprocess.PIPE,
589 stderr=subprocess.PIPE)
590 stdout, stderr = p.communicate()
591 #NOTE: stdout should get stderr from grandchild
592 self.assertStderrEqual(stdout, b'42')
593 self.assertStderrEqual(stderr, b'') # should be empty
594 self.assertEqual(p.returncode, 0)
595
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000597 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000599 'import sys;'
600 'sys.stdout.write("apple");'
601 'sys.stdout.flush();'
602 'sys.stderr.write("orange")'],
603 stdout=subprocess.PIPE,
604 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200605 with p:
606 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000607
608 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000609 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000610 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000611 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000612 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000613 'import sys;'
614 'sys.stdout.write("apple");'
615 'sys.stdout.flush();'
616 'sys.stderr.write("orange")'],
617 stdout=tf,
618 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619 p.wait()
620 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000621 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000622
Thomas Wouters89f507f2006-12-13 04:49:30 +0000623 def test_stdout_filedes_of_stdout(self):
624 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200625 # To avoid printing the text on stdout, we do something similar to
626 # test_stdout_none (see above). The parent subprocess calls the child
627 # subprocess passing stdout=1, and this test uses stdout=PIPE in
628 # order to capture and check the output of the parent. See #11963.
629 code = ('import sys, subprocess; '
630 'rc = subprocess.call([sys.executable, "-c", '
631 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
632 'b\'test with stdout=1\'))"], stdout=1); '
633 'assert rc == 18')
634 p = subprocess.Popen([sys.executable, "-c", code],
635 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
636 self.addCleanup(p.stdout.close)
637 self.addCleanup(p.stderr.close)
638 out, err = p.communicate()
639 self.assertEqual(p.returncode, 0, err)
640 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000641
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200642 def test_stdout_devnull(self):
643 p = subprocess.Popen([sys.executable, "-c",
644 'for i in range(10240):'
645 'print("x" * 1024)'],
646 stdout=subprocess.DEVNULL)
647 p.wait()
648 self.assertEqual(p.stdout, None)
649
650 def test_stderr_devnull(self):
651 p = subprocess.Popen([sys.executable, "-c",
652 'import sys\n'
653 'for i in range(10240):'
654 'sys.stderr.write("x" * 1024)'],
655 stderr=subprocess.DEVNULL)
656 p.wait()
657 self.assertEqual(p.stderr, None)
658
659 def test_stdin_devnull(self):
660 p = subprocess.Popen([sys.executable, "-c",
661 'import sys;'
662 'sys.stdin.read(1)'],
663 stdin=subprocess.DEVNULL)
664 p.wait()
665 self.assertEqual(p.stdin, None)
666
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000667 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000668 newenv = os.environ.copy()
669 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200670 with subprocess.Popen([sys.executable, "-c",
671 'import sys,os;'
672 'sys.stdout.write(os.getenv("FRUIT"))'],
673 stdout=subprocess.PIPE,
674 env=newenv) as p:
675 stdout, stderr = p.communicate()
676 self.assertEqual(stdout, b"orange")
677
Victor Stinner62d51182011-06-23 01:02:25 +0200678 # Windows requires at least the SYSTEMROOT environment variable to start
679 # Python
680 @unittest.skipIf(sys.platform == 'win32',
681 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700682 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
683 'The Python shared library cannot be loaded '
684 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200685 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700686 """Verify that env={} is as empty as possible."""
687
Gregory P. Smith85aba232017-05-30 16:21:47 -0700688 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700689 """Determine if an environment variable is under our control."""
690 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
691 # on adding even when the environment in exec is empty.
692 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700693 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400694 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000695 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
696 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700697
Victor Stinnerf1512a22011-06-21 17:18:38 +0200698 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700699 'import os; print(list(os.environ.keys()))'],
700 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200701 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700702 child_env_names = eval(stdout.strip())
703 self.assertIsInstance(child_env_names, list)
704 child_env_names = [k for k in child_env_names
705 if not is_env_var_to_ignore(k)]
706 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000707
Serhiy Storchakad174d242017-06-23 19:39:27 +0300708 def test_invalid_cmd(self):
709 # null character in the command name
710 cmd = sys.executable + '\0'
711 with self.assertRaises(ValueError):
712 subprocess.Popen([cmd, "-c", "pass"])
713
714 # null character in the command argument
715 with self.assertRaises(ValueError):
716 subprocess.Popen([sys.executable, "-c", "pass#\0"])
717
718 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300719 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300720 newenv = os.environ.copy()
721 newenv["FRUIT\0VEGETABLE"] = "cabbage"
722 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700723 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300724
Ville Skyttä49b27342017-08-03 09:00:59 +0300725 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300726 newenv = os.environ.copy()
727 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
728 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700729 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300730
Ville Skyttä49b27342017-08-03 09:00:59 +0300731 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300732 newenv = os.environ.copy()
733 newenv["FRUIT=ORANGE"] = "lemon"
734 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700735 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300736
Ville Skyttä49b27342017-08-03 09:00:59 +0300737 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300738 newenv = os.environ.copy()
739 newenv["FRUIT"] = "orange=lemon"
740 with subprocess.Popen([sys.executable, "-c",
741 'import sys, os;'
742 'sys.stdout.write(os.getenv("FRUIT"))'],
743 stdout=subprocess.PIPE,
744 env=newenv) as p:
745 stdout, stderr = p.communicate()
746 self.assertEqual(stdout, b"orange=lemon")
747
Peter Astrandcbac93c2005-03-03 20:24:28 +0000748 def test_communicate_stdin(self):
749 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000750 'import sys;'
751 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000752 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000753 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000754 self.assertEqual(p.returncode, 1)
755
756 def test_communicate_stdout(self):
757 p = subprocess.Popen([sys.executable, "-c",
758 'import sys; sys.stdout.write("pineapple")'],
759 stdout=subprocess.PIPE)
760 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000761 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000762 self.assertEqual(stderr, None)
763
764 def test_communicate_stderr(self):
765 p = subprocess.Popen([sys.executable, "-c",
766 'import sys; sys.stderr.write("pineapple")'],
767 stderr=subprocess.PIPE)
768 (stdout, stderr) = p.communicate()
769 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000770 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000771
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000773 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000774 'import sys,os;'
775 'sys.stderr.write("pineapple");'
776 'sys.stdout.write(sys.stdin.read())'],
777 stdin=subprocess.PIPE,
778 stdout=subprocess.PIPE,
779 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000780 self.addCleanup(p.stdout.close)
781 self.addCleanup(p.stderr.close)
782 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000783 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000784 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000785 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000786
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400787 def test_communicate_timeout(self):
788 p = subprocess.Popen([sys.executable, "-c",
789 'import sys,os,time;'
790 'sys.stderr.write("pineapple\\n");'
791 'time.sleep(1);'
792 'sys.stderr.write("pear\\n");'
793 'sys.stdout.write(sys.stdin.read())'],
794 universal_newlines=True,
795 stdin=subprocess.PIPE,
796 stdout=subprocess.PIPE,
797 stderr=subprocess.PIPE)
798 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
799 timeout=0.3)
800 # Make sure we can keep waiting for it, and that we get the whole output
801 # after it completes.
802 (stdout, stderr) = p.communicate()
803 self.assertEqual(stdout, "banana")
804 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
805
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700806 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200807 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400808 p = subprocess.Popen([sys.executable, "-c",
809 'import sys,os,time;'
810 'sys.stdout.write("a" * (64 * 1024));'
811 'time.sleep(0.2);'
812 'sys.stdout.write("a" * (64 * 1024));'
813 'time.sleep(0.2);'
814 'sys.stdout.write("a" * (64 * 1024));'
815 'time.sleep(0.2);'
816 'sys.stdout.write("a" * (64 * 1024));'],
817 stdout=subprocess.PIPE)
818 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
819 (stdout, _) = p.communicate()
820 self.assertEqual(len(stdout), 4 * 64 * 1024)
821
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000822 # Test for the fd leak reported in http://bugs.python.org/issue2791.
823 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000824 for stdin_pipe in (False, True):
825 for stdout_pipe in (False, True):
826 for stderr_pipe in (False, True):
827 options = {}
828 if stdin_pipe:
829 options['stdin'] = subprocess.PIPE
830 if stdout_pipe:
831 options['stdout'] = subprocess.PIPE
832 if stderr_pipe:
833 options['stderr'] = subprocess.PIPE
834 if not options:
835 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700836 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000837 p.communicate()
838 if p.stdin is not None:
839 self.assertTrue(p.stdin.closed)
840 if p.stdout is not None:
841 self.assertTrue(p.stdout.closed)
842 if p.stderr is not None:
843 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000844
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000845 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000846 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000847 p = subprocess.Popen([sys.executable, "-c",
848 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 (stdout, stderr) = p.communicate()
850 self.assertEqual(stdout, None)
851 self.assertEqual(stderr, None)
852
853 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000854 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000856 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000857 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858 os.close(x)
859 os.close(y)
860 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000861 'import sys,os;'
862 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200863 'sys.stderr.write("x" * %d);'
864 'sys.stdout.write(sys.stdin.read())' %
865 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000866 stdin=subprocess.PIPE,
867 stdout=subprocess.PIPE,
868 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000869 self.addCleanup(p.stdout.close)
870 self.addCleanup(p.stderr.close)
871 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200872 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000873 (stdout, stderr) = p.communicate(string_to_write)
874 self.assertEqual(stdout, string_to_write)
875
876 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000877 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000878 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000879 'import sys,os;'
880 'sys.stdout.write(sys.stdin.read())'],
881 stdin=subprocess.PIPE,
882 stdout=subprocess.PIPE,
883 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000884 self.addCleanup(p.stdout.close)
885 self.addCleanup(p.stderr.close)
886 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000887 p.stdin.write(b"banana")
888 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000889 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000890 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000891
andyclegg7fed7bd2017-10-23 03:01:19 +0100892 def test_universal_newlines_and_text(self):
893 args = [
894 sys.executable, "-c",
895 'import sys,os;' + SETBINARY +
896 'buf = sys.stdout.buffer;'
897 'buf.write(sys.stdin.readline().encode());'
898 'buf.flush();'
899 'buf.write(b"line2\\n");'
900 'buf.flush();'
901 'buf.write(sys.stdin.read().encode());'
902 'buf.flush();'
903 'buf.write(b"line4\\n");'
904 'buf.flush();'
905 'buf.write(b"line5\\r\\n");'
906 'buf.flush();'
907 'buf.write(b"line6\\r");'
908 'buf.flush();'
909 'buf.write(b"\\nline7");'
910 'buf.flush();'
911 'buf.write(b"\\nline8");']
912
913 for extra_kwarg in ('universal_newlines', 'text'):
914 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
915 'stdout': subprocess.PIPE,
916 extra_kwarg: True})
917 with p:
918 p.stdin.write("line1\n")
919 p.stdin.flush()
920 self.assertEqual(p.stdout.readline(), "line1\n")
921 p.stdin.write("line3\n")
922 p.stdin.close()
923 self.addCleanup(p.stdout.close)
924 self.assertEqual(p.stdout.readline(),
925 "line2\n")
926 self.assertEqual(p.stdout.read(6),
927 "line3\n")
928 self.assertEqual(p.stdout.read(),
929 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000930
931 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000932 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000933 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000934 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200935 'buf = sys.stdout.buffer;'
936 'buf.write(b"line2\\n");'
937 'buf.flush();'
938 'buf.write(b"line4\\n");'
939 'buf.flush();'
940 'buf.write(b"line5\\r\\n");'
941 'buf.flush();'
942 'buf.write(b"line6\\r");'
943 'buf.flush();'
944 'buf.write(b"\\nline7");'
945 'buf.flush();'
946 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200947 stderr=subprocess.PIPE,
948 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000949 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000950 self.addCleanup(p.stdout.close)
951 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000952 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200953 self.assertEqual(stdout,
954 "line2\nline4\nline5\nline6\nline7\nline8")
955
956 def test_universal_newlines_communicate_stdin(self):
957 # universal newlines through communicate(), with only stdin
958 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300959 'import sys,os;' + SETBINARY + textwrap.dedent('''
960 s = sys.stdin.readline()
961 assert s == "line1\\n", repr(s)
962 s = sys.stdin.read()
963 assert s == "line3\\n", repr(s)
964 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200965 stdin=subprocess.PIPE,
966 universal_newlines=1)
967 (stdout, stderr) = p.communicate("line1\nline3\n")
968 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000969
Andrew Svetlovf3765072012-08-14 18:35:17 +0300970 def test_universal_newlines_communicate_input_none(self):
971 # Test communicate(input=None) with universal newlines.
972 #
973 # We set stdout to PIPE because, as of this writing, a different
974 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700975 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +0300976 stdin=subprocess.PIPE,
977 stdout=subprocess.PIPE,
978 universal_newlines=True)
979 p.communicate()
980 self.assertEqual(p.returncode, 0)
981
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300982 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300983 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300984 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300985 'import sys,os;' + SETBINARY + textwrap.dedent('''
986 s = sys.stdin.buffer.readline()
987 sys.stdout.buffer.write(s)
988 sys.stdout.buffer.write(b"line2\\r")
989 sys.stderr.buffer.write(b"eline2\\n")
990 s = sys.stdin.buffer.read()
991 sys.stdout.buffer.write(s)
992 sys.stdout.buffer.write(b"line4\\n")
993 sys.stdout.buffer.write(b"line5\\r\\n")
994 sys.stderr.buffer.write(b"eline6\\r")
995 sys.stderr.buffer.write(b"eline7\\r\\nz")
996 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300997 stdin=subprocess.PIPE,
998 stderr=subprocess.PIPE,
999 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001000 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001001 self.addCleanup(p.stdout.close)
1002 self.addCleanup(p.stderr.close)
1003 (stdout, stderr) = p.communicate("line1\nline3\n")
1004 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001005 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001006 # Python debug build push something like "[42442 refs]\n"
1007 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001008 # Don't use assertStderrEqual because it strips CR and LF from output.
1009 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001010
Andrew Svetlov82860712012-08-19 22:13:41 +03001011 def test_universal_newlines_communicate_encodings(self):
1012 # Check that universal newlines mode works for various encodings,
1013 # in particular for encodings in the UTF-16 and UTF-32 families.
1014 # See issue #15595.
1015 #
1016 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1017 # without, and UTF-16 and UTF-32.
1018 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001019 code = ("import sys; "
1020 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1021 encoding)
1022 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001023 # We set stdin to be non-None because, as of this writing,
1024 # a different code path is used when the number of pipes is
1025 # zero or one.
1026 popen = subprocess.Popen(args,
1027 stdin=subprocess.PIPE,
1028 stdout=subprocess.PIPE,
1029 encoding=encoding)
1030 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001031 self.assertEqual(stdout, '1\n2\n3\n4')
1032
Steve Dower050acae2016-09-06 20:16:17 -07001033 def test_communicate_errors(self):
1034 for errors, expected in [
1035 ('ignore', ''),
1036 ('replace', '\ufffd\ufffd'),
1037 ('surrogateescape', '\udc80\udc80'),
1038 ('backslashreplace', '\\x80\\x80'),
1039 ]:
1040 code = ("import sys; "
1041 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1042 args = [sys.executable, '-c', code]
1043 # We set stdin to be non-None because, as of this writing,
1044 # a different code path is used when the number of pipes is
1045 # zero or one.
1046 popen = subprocess.Popen(args,
1047 stdin=subprocess.PIPE,
1048 stdout=subprocess.PIPE,
1049 encoding='utf-8',
1050 errors=errors)
1051 stdout, stderr = popen.communicate(input='')
1052 self.assertEqual(stdout, '[{}]'.format(expected))
1053
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001054 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001055 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001056 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001057 max_handles = 1026 # too much for most UNIX systems
1058 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001059 max_handles = 2050 # too much for (at least some) Windows setups
1060 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001061 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001062 try:
1063 for i in range(max_handles):
1064 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001065 tmpfile = os.path.join(tmpdir, support.TESTFN)
1066 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001067 except OSError as e:
1068 if e.errno != errno.EMFILE:
1069 raise
1070 break
1071 else:
1072 self.skipTest("failed to reach the file descriptor limit "
1073 "(tried %d)" % max_handles)
1074 # Close a couple of them (should be enough for a subprocess)
1075 for i in range(10):
1076 os.close(handles.pop())
1077 # Loop creating some subprocesses. If one of them leaks some fds,
1078 # the next loop iteration will fail by reaching the max fd limit.
1079 for i in range(15):
1080 p = subprocess.Popen([sys.executable, "-c",
1081 "import sys;"
1082 "sys.stdout.write(sys.stdin.read())"],
1083 stdin=subprocess.PIPE,
1084 stdout=subprocess.PIPE,
1085 stderr=subprocess.PIPE)
1086 data = p.communicate(b"lime")[0]
1087 self.assertEqual(data, b"lime")
1088 finally:
1089 for h in handles:
1090 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001091 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001092
1093 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001094 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1095 '"a b c" d e')
1096 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1097 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001098 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1099 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001100 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1101 'a\\\\\\b "de fg" h')
1102 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1103 'a\\\\\\"b c d')
1104 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1105 '"a\\\\b c" d e')
1106 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1107 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001108 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1109 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001110
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001111 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001112 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001113 "import os; os.read(0, 1)"],
1114 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001115 self.addCleanup(p.stdin.close)
1116 self.assertIsNone(p.poll())
1117 os.write(p.stdin.fileno(), b'A')
1118 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001119 # Subsequent invocations should just return the returncode
1120 self.assertEqual(p.poll(), 0)
1121
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001122 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001123 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001124 self.assertEqual(p.wait(), 0)
1125 # Subsequent invocations should just return the returncode
1126 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001127
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001128 def test_wait_timeout(self):
1129 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001130 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001131 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001132 p.wait(timeout=0.0001)
1133 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001134 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1135 # time to start.
1136 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001137
Peter Astrand738131d2004-11-30 21:04:45 +00001138 def test_invalid_bufsize(self):
1139 # an invalid type of the bufsize argument should raise
1140 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001141 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001142 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001143
Guido van Rossum46a05a72007-06-07 21:56:45 +00001144 def test_bufsize_is_none(self):
1145 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001146 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001147 self.assertEqual(p.wait(), 0)
1148 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001149 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001150 self.assertEqual(p.wait(), 0)
1151
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001152 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1153 # subprocess may deadlock with bufsize=1, see issue #21332
1154 with subprocess.Popen([sys.executable, "-c", "import sys;"
1155 "sys.stdout.write(sys.stdin.readline());"
1156 "sys.stdout.flush()"],
1157 stdin=subprocess.PIPE,
1158 stdout=subprocess.PIPE,
1159 stderr=subprocess.DEVNULL,
1160 bufsize=1,
1161 universal_newlines=universal_newlines) as p:
1162 p.stdin.write(line) # expect that it flushes the line in text mode
1163 os.close(p.stdin.fileno()) # close it without flushing the buffer
1164 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001165 with support.SuppressCrashReport():
1166 try:
1167 p.stdin.close()
1168 except OSError:
1169 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001170 p.stdin = None
1171 self.assertEqual(p.returncode, 0)
1172 self.assertEqual(read_line, expected)
1173
1174 def test_bufsize_equal_one_text_mode(self):
1175 # line is flushed in text mode with bufsize=1.
1176 # we should get the full line in return
1177 line = "line\n"
1178 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1179
1180 def test_bufsize_equal_one_binary_mode(self):
1181 # line is not flushed in binary mode with bufsize=1.
1182 # we should get empty response
1183 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001184 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1185 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001186
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001187 def test_leaking_fds_on_error(self):
1188 # see bug #5179: Popen leaks file descriptors to PIPEs if
1189 # the child fails to execute; this will eventually exhaust
1190 # the maximum number of open fds. 1024 seems a very common
1191 # value for that limit, but Windows has 2048, so we loop
1192 # 1024 times (each call leaked two fds).
1193 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001194 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001195 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001196 stdout=subprocess.PIPE,
1197 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001198
Victor Stinner9a83f652017-08-21 23:51:31 +02001199 def test_nonexisting_with_pipes(self):
1200 # bpo-30121: Popen with pipes must close properly pipes on error.
1201 # Previously, os.close() was called with a Windows handle which is not
1202 # a valid file descriptor.
1203 #
1204 # Run the test in a subprocess to control how the CRT reports errors
1205 # and to get stderr content.
1206 try:
1207 import msvcrt
1208 msvcrt.CrtSetReportMode
1209 except (AttributeError, ImportError):
1210 self.skipTest("need msvcrt.CrtSetReportMode")
1211
1212 code = textwrap.dedent(f"""
1213 import msvcrt
1214 import subprocess
1215
1216 cmd = {NONEXISTING_CMD!r}
1217
1218 for report_type in [msvcrt.CRT_WARN,
1219 msvcrt.CRT_ERROR,
1220 msvcrt.CRT_ASSERT]:
1221 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1222 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1223
1224 try:
Zachary Ware55376462018-02-19 14:02:38 -06001225 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001226 stdout=subprocess.PIPE,
1227 stderr=subprocess.PIPE)
1228 except OSError:
1229 pass
1230 """)
1231 cmd = [sys.executable, "-c", code]
1232 proc = subprocess.Popen(cmd,
1233 stderr=subprocess.PIPE,
1234 universal_newlines=True)
1235 with proc:
1236 stderr = proc.communicate()[1]
1237 self.assertEqual(stderr, "")
1238 self.assertEqual(proc.returncode, 0)
1239
Antoine Pitroua8392712013-08-30 23:38:13 +02001240 def test_double_close_on_error(self):
1241 # Issue #18851
1242 fds = []
1243 def open_fds():
1244 for i in range(20):
1245 fds.extend(os.pipe())
1246 time.sleep(0.001)
1247 t = threading.Thread(target=open_fds)
1248 t.start()
1249 try:
1250 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001251 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001252 stdin=subprocess.PIPE,
1253 stdout=subprocess.PIPE,
1254 stderr=subprocess.PIPE)
1255 finally:
1256 t.join()
1257 exc = None
1258 for fd in fds:
1259 # If a double close occurred, some of those fds will
1260 # already have been closed by mistake, and os.close()
1261 # here will raise.
1262 try:
1263 os.close(fd)
1264 except OSError as e:
1265 exc = e
1266 if exc is not None:
1267 raise exc
1268
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001269 def test_threadsafe_wait(self):
1270 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1271 proc = subprocess.Popen([sys.executable, '-c',
1272 'import time; time.sleep(12)'])
1273 self.assertEqual(proc.returncode, None)
1274 results = []
1275
1276 def kill_proc_timer_thread():
1277 results.append(('thread-start-poll-result', proc.poll()))
1278 # terminate it from the thread and wait for the result.
1279 proc.kill()
1280 proc.wait()
1281 results.append(('thread-after-kill-and-wait', proc.returncode))
1282 # this wait should be a no-op given the above.
1283 proc.wait()
1284 results.append(('thread-after-second-wait', proc.returncode))
1285
1286 # This is a timing sensitive test, the failure mode is
1287 # triggered when both the main thread and this thread are in
1288 # the wait() call at once. The delay here is to allow the
1289 # main thread to most likely be blocked in its wait() call.
1290 t = threading.Timer(0.2, kill_proc_timer_thread)
1291 t.start()
1292
Victor Stinner937ee9e2018-06-26 02:11:06 +02001293 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001294 expected_errorcode = 1
1295 else:
1296 # Should be -9 because of the proc.kill() from the thread.
1297 expected_errorcode = -9
1298
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001299 # Wait for the process to finish; the thread should kill it
1300 # long before it finishes on its own. Supplying a timeout
1301 # triggers a different code path for better coverage.
1302 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001303 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001304 msg="unexpected result in wait from main thread")
1305
1306 # This should be a no-op with no change in returncode.
1307 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001308 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001309 msg="unexpected result in second main wait.")
1310
1311 t.join()
1312 # Ensure that all of the thread results are as expected.
1313 # When a race condition occurs in wait(), the returncode could
1314 # be set by the wrong thread that doesn't actually have it
1315 # leading to an incorrect value.
1316 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001317 ('thread-after-kill-and-wait', expected_errorcode),
1318 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001319 results)
1320
Victor Stinnerb3693582010-05-21 20:13:12 +00001321 def test_issue8780(self):
1322 # Ensure that stdout is inherited from the parent
1323 # if stdout=PIPE is not used
1324 code = ';'.join((
1325 'import subprocess, sys',
1326 'retcode = subprocess.call('
1327 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1328 'assert retcode == 0'))
1329 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001330 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001331
Tim Goldenaf5ac392010-08-06 13:03:56 +00001332 def test_handles_closed_on_exception(self):
1333 # If CreateProcess exits with an error, ensure the
1334 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001335 ifhandle, ifname = tempfile.mkstemp()
1336 ofhandle, ofname = tempfile.mkstemp()
1337 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001338 try:
1339 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1340 stderr=efhandle)
1341 except OSError:
1342 os.close(ifhandle)
1343 os.remove(ifname)
1344 os.close(ofhandle)
1345 os.remove(ofname)
1346 os.close(efhandle)
1347 os.remove(efname)
1348 self.assertFalse(os.path.exists(ifname))
1349 self.assertFalse(os.path.exists(ofname))
1350 self.assertFalse(os.path.exists(efname))
1351
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001352 def test_communicate_epipe(self):
1353 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001354 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001355 stdin=subprocess.PIPE,
1356 stdout=subprocess.PIPE,
1357 stderr=subprocess.PIPE)
1358 self.addCleanup(p.stdout.close)
1359 self.addCleanup(p.stderr.close)
1360 self.addCleanup(p.stdin.close)
1361 p.communicate(b"x" * 2**20)
1362
1363 def test_communicate_epipe_only_stdin(self):
1364 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001365 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001366 stdin=subprocess.PIPE)
1367 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001368 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001369 p.communicate(b"x" * 2**20)
1370
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001371 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1372 "Requires signal.SIGUSR1")
1373 @unittest.skipUnless(hasattr(os, 'kill'),
1374 "Requires os.kill")
1375 @unittest.skipUnless(hasattr(os, 'getppid'),
1376 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001377 def test_communicate_eintr(self):
1378 # Issue #12493: communicate() should handle EINTR
1379 def handler(signum, frame):
1380 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001381 old_handler = signal.signal(signal.SIGUSR1, handler)
1382 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001383
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001384 args = [sys.executable, "-c",
1385 'import os, signal;'
1386 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001387 for stream in ('stdout', 'stderr'):
1388 kw = {stream: subprocess.PIPE}
1389 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001390 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001391 process.communicate()
1392
Tim Peterse718f612004-10-12 21:51:32 +00001393
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001394 # This test is Linux-ish specific for simplicity to at least have
1395 # some coverage. It is not a platform specific bug.
1396 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1397 "Linux specific")
1398 def test_failed_child_execute_fd_leak(self):
1399 """Test for the fork() failure fd leak reported in issue16327."""
1400 fd_directory = '/proc/%d/fd' % os.getpid()
1401 fds_before_popen = os.listdir(fd_directory)
1402 with self.assertRaises(PopenTestException):
1403 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001404 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001405 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1406
1407 # NOTE: This test doesn't verify that the real _execute_child
1408 # does not close the file descriptors itself on the way out
1409 # during an exception. Code inspection has confirmed that.
1410
1411 fds_after_exception = os.listdir(fd_directory)
1412 self.assertEqual(fds_before_popen, fds_after_exception)
1413
Victor Stinner937ee9e2018-06-26 02:11:06 +02001414 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001415 def test_file_not_found_includes_filename(self):
1416 with self.assertRaises(FileNotFoundError) as c:
1417 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1418 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1419
Victor Stinner937ee9e2018-06-26 02:11:06 +02001420 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001421 def test_file_not_found_with_bad_cwd(self):
1422 with self.assertRaises(FileNotFoundError) as c:
1423 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1424 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1425
Gregory P. Smith6e730002015-04-14 16:14:25 -07001426
1427class RunFuncTestCase(BaseTestCase):
1428 def run_python(self, code, **kwargs):
1429 """Run Python code in a subprocess using subprocess.run"""
1430 argv = [sys.executable, "-c", code]
1431 return subprocess.run(argv, **kwargs)
1432
1433 def test_returncode(self):
1434 # call() function with sequence argument
1435 cp = self.run_python("import sys; sys.exit(47)")
1436 self.assertEqual(cp.returncode, 47)
1437 with self.assertRaises(subprocess.CalledProcessError):
1438 cp.check_returncode()
1439
1440 def test_check(self):
1441 with self.assertRaises(subprocess.CalledProcessError) as c:
1442 self.run_python("import sys; sys.exit(47)", check=True)
1443 self.assertEqual(c.exception.returncode, 47)
1444
1445 def test_check_zero(self):
1446 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001447 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001448 self.assertEqual(cp.returncode, 0)
1449
1450 def test_timeout(self):
1451 # run() function with timeout argument; we want to test that the child
1452 # process gets killed when the timeout expires. If the child isn't
1453 # killed, this call will deadlock since subprocess.run waits for the
1454 # child.
1455 with self.assertRaises(subprocess.TimeoutExpired):
1456 self.run_python("while True: pass", timeout=0.0001)
1457
1458 def test_capture_stdout(self):
1459 # capture stdout with zero return code
1460 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1461 self.assertIn(b'BDFL', cp.stdout)
1462
1463 def test_capture_stderr(self):
1464 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1465 stderr=subprocess.PIPE)
1466 self.assertIn(b'BDFL', cp.stderr)
1467
1468 def test_check_output_stdin_arg(self):
1469 # run() can be called with stdin set to a file
1470 tf = tempfile.TemporaryFile()
1471 self.addCleanup(tf.close)
1472 tf.write(b'pear')
1473 tf.seek(0)
1474 cp = self.run_python(
1475 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1476 stdin=tf, stdout=subprocess.PIPE)
1477 self.assertIn(b'PEAR', cp.stdout)
1478
1479 def test_check_output_input_arg(self):
1480 # check_output() can be called with input set to a string
1481 cp = self.run_python(
1482 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1483 input=b'pear', stdout=subprocess.PIPE)
1484 self.assertIn(b'PEAR', cp.stdout)
1485
1486 def test_check_output_stdin_with_input_arg(self):
1487 # run() refuses to accept 'stdin' with 'input'
1488 tf = tempfile.TemporaryFile()
1489 self.addCleanup(tf.close)
1490 tf.write(b'pear')
1491 tf.seek(0)
1492 with self.assertRaises(ValueError,
1493 msg="Expected ValueError when stdin and input args supplied.") as c:
1494 output = self.run_python("print('will not be run')",
1495 stdin=tf, input=b'hare')
1496 self.assertIn('stdin', c.exception.args[0])
1497 self.assertIn('input', c.exception.args[0])
1498
1499 def test_check_output_timeout(self):
1500 with self.assertRaises(subprocess.TimeoutExpired) as c:
1501 cp = self.run_python((
1502 "import sys, time\n"
1503 "sys.stdout.write('BDFL')\n"
1504 "sys.stdout.flush()\n"
1505 "time.sleep(3600)"),
1506 # Some heavily loaded buildbots (sparc Debian 3.x) require
1507 # this much time to start and print.
1508 timeout=3, stdout=subprocess.PIPE)
1509 self.assertEqual(c.exception.output, b'BDFL')
1510 # output is aliased to stdout
1511 self.assertEqual(c.exception.stdout, b'BDFL')
1512
1513 def test_run_kwargs(self):
1514 newenv = os.environ.copy()
1515 newenv["FRUIT"] = "banana"
1516 cp = self.run_python(('import sys, os;'
1517 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1518 env=newenv)
1519 self.assertEqual(cp.returncode, 33)
1520
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001521 def test_run_with_pathlike_path(self):
1522 # bpo-31961: test run(pathlike_object)
1523 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001524 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001525 prog = 'tree.com' if mswindows else 'ls'
1526 path = shutil.which(prog)
1527 if path is None:
1528 self.skipTest(f'{prog} required for this test')
1529 path = FakePath(path)
1530 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1531 self.assertEqual(res.returncode, 0)
1532 with self.assertRaises(TypeError):
1533 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1534
1535 def test_run_with_bytes_path_and_arguments(self):
1536 # bpo-31961: test run([bytes_object, b'additional arguments'])
1537 path = os.fsencode(sys.executable)
1538 args = [path, '-c', b'import sys; sys.exit(57)']
1539 res = subprocess.run(args)
1540 self.assertEqual(res.returncode, 57)
1541
1542 def test_run_with_pathlike_path_and_arguments(self):
1543 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1544 path = FakePath(sys.executable)
1545 args = [path, '-c', 'import sys; sys.exit(57)']
1546 res = subprocess.run(args)
1547 self.assertEqual(res.returncode, 57)
1548
Bo Baylesce0f33d2018-01-30 00:40:39 -06001549 def test_capture_output(self):
1550 cp = self.run_python(("import sys;"
1551 "sys.stdout.write('BDFL'); "
1552 "sys.stderr.write('FLUFL')"),
1553 capture_output=True)
1554 self.assertIn(b'BDFL', cp.stdout)
1555 self.assertIn(b'FLUFL', cp.stderr)
1556
1557 def test_stdout_with_capture_output_arg(self):
1558 # run() refuses to accept 'stdout' with 'capture_output'
1559 tf = tempfile.TemporaryFile()
1560 self.addCleanup(tf.close)
1561 with self.assertRaises(ValueError,
1562 msg=("Expected ValueError when stdout and capture_output "
1563 "args supplied.")) as c:
1564 output = self.run_python("print('will not be run')",
1565 capture_output=True, stdout=tf)
1566 self.assertIn('stdout', c.exception.args[0])
1567 self.assertIn('capture_output', c.exception.args[0])
1568
1569 def test_stderr_with_capture_output_arg(self):
1570 # run() refuses to accept 'stderr' with 'capture_output'
1571 tf = tempfile.TemporaryFile()
1572 self.addCleanup(tf.close)
1573 with self.assertRaises(ValueError,
1574 msg=("Expected ValueError when stderr and capture_output "
1575 "args supplied.")) as c:
1576 output = self.run_python("print('will not be run')",
1577 capture_output=True, stderr=tf)
1578 self.assertIn('stderr', c.exception.args[0])
1579 self.assertIn('capture_output', c.exception.args[0])
1580
Gregory P. Smith580d2782019-09-11 04:23:05 -05001581 # This test _might_ wind up a bit fragile on loaded build+test machines
1582 # as it depends on the timing with wide enough margins for normal situations
1583 # but does assert that it happened "soon enough" to believe the right thing
1584 # happened.
1585 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1586 def test_run_with_shell_timeout_and_capture_output(self):
1587 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1588 before_secs = time.monotonic()
1589 try:
1590 subprocess.run('sleep 3', shell=True, timeout=0.1,
1591 capture_output=True) # New session unspecified.
1592 except subprocess.TimeoutExpired as exc:
1593 after_secs = time.monotonic()
1594 stacks = traceback.format_exc() # assertRaises doesn't give this.
1595 else:
1596 self.fail("TimeoutExpired not raised.")
1597 self.assertLess(after_secs - before_secs, 1.5,
1598 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1599 f"{stacks}```")
1600
Gregory P. Smith6e730002015-04-14 16:14:25 -07001601
Gregory P. Smith693aa802019-09-13 14:43:35 +01001602def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001603 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001604 if grp:
1605 try:
1606 grp.getgrnam(name_group)
1607 except KeyError:
1608 continue
1609 return name_group
1610 else:
1611 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1612
1613
Victor Stinner937ee9e2018-06-26 02:11:06 +02001614@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001615class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001616
Gregory P. Smith5591b022012-10-10 03:34:47 -07001617 def setUp(self):
1618 super().setUp()
1619 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1620
1621 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001622 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001623 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001624 except OSError as e:
1625 # This avoids hard coding the errno value or the OS perror()
1626 # string and instead capture the exception that we want to see
1627 # below for comparison.
1628 desired_exception = e
1629 else:
Martin Pantereb995702016-07-28 01:11:04 +00001630 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001631 self._nonexistent_dir)
1632 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001633
Gregory P. Smith5591b022012-10-10 03:34:47 -07001634 def test_exception_cwd(self):
1635 """Test error in the child raised in the parent for a bad cwd."""
1636 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001637 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001638 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001639 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001640 except OSError as e:
1641 # Test that the child process chdir failure actually makes
1642 # it up to the parent process as the correct exception.
1643 self.assertEqual(desired_exception.errno, e.errno)
1644 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001645 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001646 else:
1647 self.fail("Expected OSError: %s" % desired_exception)
1648
Gregory P. Smith5591b022012-10-10 03:34:47 -07001649 def test_exception_bad_executable(self):
1650 """Test error in the child raised in the parent for a bad executable."""
1651 desired_exception = self._get_chdir_exception()
1652 try:
1653 p = subprocess.Popen([sys.executable, "-c", ""],
1654 executable=self._nonexistent_dir)
1655 except OSError as e:
1656 # Test that the child process exec failure actually makes
1657 # it up to the parent process as the correct exception.
1658 self.assertEqual(desired_exception.errno, e.errno)
1659 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001660 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001661 else:
1662 self.fail("Expected OSError: %s" % desired_exception)
1663
1664 def test_exception_bad_args_0(self):
1665 """Test error in the child raised in the parent for a bad args[0]."""
1666 desired_exception = self._get_chdir_exception()
1667 try:
1668 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1669 except OSError as e:
1670 # Test that the child process exec failure actually makes
1671 # it up to the parent process as the correct exception.
1672 self.assertEqual(desired_exception.errno, e.errno)
1673 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001674 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001675 else:
1676 self.fail("Expected OSError: %s" % desired_exception)
1677
Ammar Askar3fc499b2017-09-06 02:41:30 -04001678 # We mock the __del__ method for Popen in the next two tests
1679 # because it does cleanup based on the pid returned by fork_exec
1680 # along with issuing a resource warning if it still exists. Since
1681 # we don't actually spawn a process in these tests we can forego
1682 # the destructor. An alternative would be to set _child_created to
1683 # False before the destructor is called but there is no easy way
1684 # to do that
1685 class PopenNoDestructor(subprocess.Popen):
1686 def __del__(self):
1687 pass
1688
1689 @mock.patch("subprocess._posixsubprocess.fork_exec")
1690 def test_exception_errpipe_normal(self, fork_exec):
1691 """Test error passing done through errpipe_write in the good case"""
1692 def proper_error(*args):
1693 errpipe_write = args[13]
1694 # Write the hex for the error code EISDIR: 'is a directory'
1695 err_code = '{:x}'.format(errno.EISDIR).encode()
1696 os.write(errpipe_write, b"OSError:" + err_code + b":")
1697 return 0
1698
1699 fork_exec.side_effect = proper_error
1700
Victor Stinner11045c92017-10-05 06:32:53 -07001701 with mock.patch("subprocess.os.waitpid",
1702 side_effect=ChildProcessError):
1703 with self.assertRaises(IsADirectoryError):
1704 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001705
1706 @mock.patch("subprocess._posixsubprocess.fork_exec")
1707 def test_exception_errpipe_bad_data(self, fork_exec):
1708 """Test error passing done through errpipe_write where its not
1709 in the expected format"""
1710 error_data = b"\xFF\x00\xDE\xAD"
1711 def bad_error(*args):
1712 errpipe_write = args[13]
1713 # Anything can be in the pipe, no assumptions should
1714 # be made about its encoding, so we'll write some
1715 # arbitrary hex bytes to test it out
1716 os.write(errpipe_write, error_data)
1717 return 0
1718
1719 fork_exec.side_effect = bad_error
1720
Victor Stinner11045c92017-10-05 06:32:53 -07001721 with mock.patch("subprocess.os.waitpid",
1722 side_effect=ChildProcessError):
1723 with self.assertRaises(subprocess.SubprocessError) as e:
1724 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001725
1726 self.assertIn(repr(error_data), str(e.exception))
1727
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001728 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1729 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001730 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001731 # Blindly assume that cat exists on systems with /proc/self/status...
1732 default_proc_status = subprocess.check_output(
1733 ['cat', '/proc/self/status'],
1734 restore_signals=False)
1735 for line in default_proc_status.splitlines():
1736 if line.startswith(b'SigIgn'):
1737 default_sig_ign_mask = line
1738 break
1739 else:
1740 self.skipTest("SigIgn not found in /proc/self/status.")
1741 restored_proc_status = subprocess.check_output(
1742 ['cat', '/proc/self/status'],
1743 restore_signals=True)
1744 for line in restored_proc_status.splitlines():
1745 if line.startswith(b'SigIgn'):
1746 restored_sig_ign_mask = line
1747 break
1748 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1749 msg="restore_signals=True should've unblocked "
1750 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001751
1752 def test_start_new_session(self):
1753 # For code coverage of calling setsid(). We don't care if we get an
1754 # EPERM error from it depending on the test execution environment, that
1755 # still indicates that it was called.
1756 try:
1757 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001758 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001759 start_new_session=True)
1760 except OSError as e:
1761 if e.errno != errno.EPERM:
1762 raise
1763 else:
Victor Stinner58840432019-06-14 19:31:43 +02001764 parent_sid = os.getsid(0)
1765 child_sid = int(output)
1766 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001767
Patrick McLean2b2ead72019-09-12 10:15:44 -07001768 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1769 def test_user(self):
1770 # For code coverage of the user parameter. 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
1774 uid = os.geteuid()
1775 test_users = [65534 if uid != 65534 else 65533, uid]
1776 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1777
1778 if pwd is not None:
1779 test_users.append(name_uid)
1780
1781 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001782 # posix_spawn() may be used with close_fds=False
1783 for close_fds in (False, True):
1784 with self.subTest(user=user, close_fds=close_fds):
1785 try:
1786 output = subprocess.check_output(
1787 [sys.executable, "-c",
1788 "import os; print(os.getuid())"],
1789 user=user,
1790 close_fds=close_fds)
1791 except PermissionError: # (EACCES, EPERM)
1792 pass
1793 except OSError as e:
1794 if e.errno not in (errno.EACCES, errno.EPERM):
1795 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001796 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001797 if isinstance(user, str):
1798 user_uid = pwd.getpwnam(user).pw_uid
1799 else:
1800 user_uid = user
1801 child_user = int(output)
1802 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001803
1804 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001805 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001806
1807 if pwd is None:
1808 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001809 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001810
1811 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1812 def test_user_error(self):
1813 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001814 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001815
1816 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1817 def test_group(self):
1818 gid = os.getegid()
1819 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001820 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001821
1822 if grp is not None:
1823 group_list.append(name_group)
1824
1825 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001826 # posix_spawn() may be used with close_fds=False
1827 for close_fds in (False, True):
1828 with self.subTest(group=group, close_fds=close_fds):
1829 try:
1830 output = subprocess.check_output(
1831 [sys.executable, "-c",
1832 "import os; print(os.getgid())"],
1833 group=group,
1834 close_fds=close_fds)
1835 except PermissionError: # (EACCES, EPERM)
1836 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001837 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001838 if isinstance(group, str):
1839 group_gid = grp.getgrnam(group).gr_gid
1840 else:
1841 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001842
Victor Stinnerfaca8552019-09-25 15:52:49 +02001843 child_group = int(output)
1844 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001845
1846 # make sure we bomb on negative values
1847 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001848 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001849
1850 if grp is None:
1851 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001852 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001853
1854 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1855 def test_group_error(self):
1856 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001857 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001858
1859 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1860 def test_extra_groups(self):
1861 gid = os.getegid()
1862 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001863 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001864 perm_error = False
1865
1866 if grp is not None:
1867 group_list.append(name_group)
1868
1869 try:
1870 output = subprocess.check_output(
1871 [sys.executable, "-c",
1872 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1873 extra_groups=group_list)
1874 except OSError as ex:
1875 if ex.errno != errno.EPERM:
1876 raise
1877 perm_error = True
1878
1879 else:
1880 parent_groups = os.getgroups()
1881 child_groups = json.loads(output)
1882
1883 if grp is not None:
1884 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
1885 for g in group_list]
1886 else:
1887 desired_gids = group_list
1888
1889 if perm_error:
1890 self.assertEqual(set(child_groups), set(parent_groups))
1891 else:
1892 self.assertEqual(set(desired_gids), set(child_groups))
1893
1894 # make sure we bomb on negative values
1895 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001896 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001897
1898 if grp is None:
1899 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001900 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07001901 extra_groups=[name_group])
1902
1903 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
1904 def test_extra_groups_error(self):
1905 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001906 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001907
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001908 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
1909 'POSIX umask() is not available.')
1910 def test_umask(self):
1911 tmpdir = None
1912 try:
1913 tmpdir = tempfile.mkdtemp()
1914 name = os.path.join(tmpdir, "beans")
1915 # We set an unusual umask in the child so as a unique mode
1916 # for us to test the child's touched file for.
1917 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001918 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001919 umask=0o053)
1920 # Ignore execute permissions entirely in our test,
1921 # filesystems could be mounted to ignore or force that.
1922 st_mode = os.stat(name).st_mode & 0o666
1923 expected_mode = 0o624
1924 self.assertEqual(expected_mode, st_mode,
1925 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
1926 finally:
1927 if tmpdir is not None:
1928 shutil.rmtree(tmpdir)
1929
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001930 def test_run_abort(self):
1931 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001932 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001933 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001934 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001935 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001936 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001937
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001938 def test_CalledProcessError_str_signal(self):
1939 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1940 error_string = str(err)
1941 # We're relying on the repr() of the signal.Signals intenum to provide
1942 # the word signal, the signal name and the numeric value.
1943 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001944 # We're not being specific about the signal name as some signals have
1945 # multiple names and which name is revealed can vary.
1946 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001947 self.assertIn(str(signal.SIGABRT), error_string)
1948
1949 def test_CalledProcessError_str_unknown_signal(self):
1950 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1951 error_string = str(err)
1952 self.assertIn("unknown signal 9876543.", error_string)
1953
1954 def test_CalledProcessError_str_non_zero(self):
1955 err = subprocess.CalledProcessError(2, "fake cmd")
1956 error_string = str(err)
1957 self.assertIn("non-zero exit status 2.", error_string)
1958
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001959 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001960 # DISCLAIMER: Setting environment variables is *not* a good use
1961 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001962 p = subprocess.Popen([sys.executable, "-c",
1963 'import sys,os;'
1964 'sys.stdout.write(os.getenv("FRUIT"))'],
1965 stdout=subprocess.PIPE,
1966 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001967 with p:
1968 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001969
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001970 def test_preexec_exception(self):
1971 def raise_it():
1972 raise ValueError("What if two swallows carried a coconut?")
1973 try:
1974 p = subprocess.Popen([sys.executable, "-c", ""],
1975 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001976 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001977 self.assertTrue(
1978 subprocess._posixsubprocess,
1979 "Expected a ValueError from the preexec_fn")
1980 except ValueError as e:
1981 self.assertIn("coconut", e.args[0])
1982 else:
1983 self.fail("Exception raised by preexec_fn did not make it "
1984 "to the parent process.")
1985
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001986 class _TestExecuteChildPopen(subprocess.Popen):
1987 """Used to test behavior at the end of _execute_child."""
1988 def __init__(self, testcase, *args, **kwargs):
1989 self._testcase = testcase
1990 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001991
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001992 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001993 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001994 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001995 finally:
1996 # Open a bunch of file descriptors and verify that
1997 # none of them are the same as the ones the Popen
1998 # instance is using for stdin/stdout/stderr.
1999 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2000 for _ in range(8)]
2001 try:
2002 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002003 self._testcase.assertNotIn(
2004 fd, (self.stdin.fileno(), self.stdout.fileno(),
2005 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002006 msg="At least one fd was closed early.")
2007 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002008 for fd in devzero_fds:
2009 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002010
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002011 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2012 def test_preexec_errpipe_does_not_double_close_pipes(self):
2013 """Issue16140: Don't double close pipes on preexec error."""
2014
2015 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002016 raise subprocess.SubprocessError(
2017 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002018
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002019 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002020 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002021 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002022 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2023 stderr=subprocess.PIPE, preexec_fn=raise_it)
2024
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002025 def test_preexec_gc_module_failure(self):
2026 # This tests the code that disables garbage collection if the child
2027 # process will execute any Python.
2028 def raise_runtime_error():
2029 raise RuntimeError("this shouldn't escape")
2030 enabled = gc.isenabled()
2031 orig_gc_disable = gc.disable
2032 orig_gc_isenabled = gc.isenabled
2033 try:
2034 gc.disable()
2035 self.assertFalse(gc.isenabled())
2036 subprocess.call([sys.executable, '-c', ''],
2037 preexec_fn=lambda: None)
2038 self.assertFalse(gc.isenabled(),
2039 "Popen enabled gc when it shouldn't.")
2040
2041 gc.enable()
2042 self.assertTrue(gc.isenabled())
2043 subprocess.call([sys.executable, '-c', ''],
2044 preexec_fn=lambda: None)
2045 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2046
2047 gc.disable = raise_runtime_error
2048 self.assertRaises(RuntimeError, subprocess.Popen,
2049 [sys.executable, '-c', ''],
2050 preexec_fn=lambda: None)
2051
2052 del gc.isenabled # force an AttributeError
2053 self.assertRaises(AttributeError, subprocess.Popen,
2054 [sys.executable, '-c', ''],
2055 preexec_fn=lambda: None)
2056 finally:
2057 gc.disable = orig_gc_disable
2058 gc.isenabled = orig_gc_isenabled
2059 if not enabled:
2060 gc.disable()
2061
Martin Panterf7fdbda2015-12-05 09:51:52 +00002062 @unittest.skipIf(
2063 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002064 def test_preexec_fork_failure(self):
2065 # The internal code did not preserve the previous exception when
2066 # re-enabling garbage collection
2067 try:
2068 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2069 except ImportError as err:
2070 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2071 limits = getrlimit(RLIMIT_NPROC)
2072 [_, hard] = limits
2073 setrlimit(RLIMIT_NPROC, (0, hard))
2074 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002075 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002076 subprocess.call([sys.executable, '-c', ''],
2077 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002078 except BlockingIOError:
2079 # Forking should raise EAGAIN, translated to BlockingIOError
2080 pass
2081 else:
2082 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002083
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002084 def test_args_string(self):
2085 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002086 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002087 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002088 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002089 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002090 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2091 sys.executable)
2092 os.chmod(fname, 0o700)
2093 p = subprocess.Popen(fname)
2094 p.wait()
2095 os.remove(fname)
2096 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002097
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002098 def test_invalid_args(self):
2099 # invalid arguments should raise ValueError
2100 self.assertRaises(ValueError, subprocess.call,
2101 [sys.executable, "-c",
2102 "import sys; sys.exit(47)"],
2103 startupinfo=47)
2104 self.assertRaises(ValueError, subprocess.call,
2105 [sys.executable, "-c",
2106 "import sys; sys.exit(47)"],
2107 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002108
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002109 def test_shell_sequence(self):
2110 # Run command through the shell (sequence)
2111 newenv = os.environ.copy()
2112 newenv["FRUIT"] = "apple"
2113 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2114 stdout=subprocess.PIPE,
2115 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002116 with p:
2117 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002118
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002119 def test_shell_string(self):
2120 # Run command through the shell (string)
2121 newenv = os.environ.copy()
2122 newenv["FRUIT"] = "apple"
2123 p = subprocess.Popen("echo $FRUIT", shell=1,
2124 stdout=subprocess.PIPE,
2125 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002126 with p:
2127 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002128
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002129 def test_call_string(self):
2130 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002131 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002132 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002133 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002134 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002135 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2136 sys.executable)
2137 os.chmod(fname, 0o700)
2138 rc = subprocess.call(fname)
2139 os.remove(fname)
2140 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002141
Stefan Krah9542cc62010-07-19 14:20:53 +00002142 def test_specific_shell(self):
2143 # Issue #9265: Incorrect name passed as arg[0].
2144 shells = []
2145 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2146 for name in ['bash', 'ksh']:
2147 sh = os.path.join(prefix, name)
2148 if os.path.isfile(sh):
2149 shells.append(sh)
2150 if not shells: # Will probably work for any shell but csh.
2151 self.skipTest("bash or ksh required for this test")
2152 sh = '/bin/sh'
2153 if os.path.isfile(sh) and not os.path.islink(sh):
2154 # Test will fail if /bin/sh is a symlink to csh.
2155 shells.append(sh)
2156 for sh in shells:
2157 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2158 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002159 with p:
2160 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002161
Florent Xicluna4886d242010-03-08 13:27:26 +00002162 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002163 # Do not inherit file handles from the parent.
2164 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002165 # Also set the SIGINT handler to the default to make sure it's not
2166 # being ignored (some tests rely on that.)
2167 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2168 try:
2169 p = subprocess.Popen([sys.executable, "-c", """if 1:
2170 import sys, time
2171 sys.stdout.write('x\\n')
2172 sys.stdout.flush()
2173 time.sleep(30)
2174 """],
2175 close_fds=True,
2176 stdin=subprocess.PIPE,
2177 stdout=subprocess.PIPE,
2178 stderr=subprocess.PIPE)
2179 finally:
2180 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002181 # Wait for the interpreter to be completely initialized before
2182 # sending any signal.
2183 p.stdout.read(1)
2184 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002185 return p
2186
Charles-François Natali53221e32013-01-12 16:52:20 +01002187 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2188 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002189 def _kill_dead_process(self, method, *args):
2190 # Do not inherit file handles from the parent.
2191 # It should fix failures on some platforms.
2192 p = subprocess.Popen([sys.executable, "-c", """if 1:
2193 import sys, time
2194 sys.stdout.write('x\\n')
2195 sys.stdout.flush()
2196 """],
2197 close_fds=True,
2198 stdin=subprocess.PIPE,
2199 stdout=subprocess.PIPE,
2200 stderr=subprocess.PIPE)
2201 # Wait for the interpreter to be completely initialized before
2202 # sending any signal.
2203 p.stdout.read(1)
2204 # The process should end after this
2205 time.sleep(1)
2206 # This shouldn't raise even though the child is now dead
2207 getattr(p, method)(*args)
2208 p.communicate()
2209
Florent Xicluna4886d242010-03-08 13:27:26 +00002210 def test_send_signal(self):
2211 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002212 _, stderr = p.communicate()
2213 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002214 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002215
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002216 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002217 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002218 _, stderr = p.communicate()
2219 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002220 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002221
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002222 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002223 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002224 _, stderr = p.communicate()
2225 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002226 self.assertEqual(p.wait(), -signal.SIGTERM)
2227
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002228 def test_send_signal_dead(self):
2229 # Sending a signal to a dead process
2230 self._kill_dead_process('send_signal', signal.SIGINT)
2231
2232 def test_kill_dead(self):
2233 # Killing a dead process
2234 self._kill_dead_process('kill')
2235
2236 def test_terminate_dead(self):
2237 # Terminating a dead process
2238 self._kill_dead_process('terminate')
2239
Victor Stinnerdaf45552013-08-28 00:53:59 +02002240 def _save_fds(self, save_fds):
2241 fds = []
2242 for fd in save_fds:
2243 inheritable = os.get_inheritable(fd)
2244 saved = os.dup(fd)
2245 fds.append((fd, saved, inheritable))
2246 return fds
2247
2248 def _restore_fds(self, fds):
2249 for fd, saved, inheritable in fds:
2250 os.dup2(saved, fd, inheritable=inheritable)
2251 os.close(saved)
2252
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002253 def check_close_std_fds(self, fds):
2254 # Issue #9905: test that subprocess pipes still work properly with
2255 # some standard fds closed
2256 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002257 saved_fds = self._save_fds(fds)
2258 for fd, saved, inheritable in saved_fds:
2259 if fd == 0:
2260 stdin = saved
2261 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002262 try:
2263 for fd in fds:
2264 os.close(fd)
2265 out, err = subprocess.Popen([sys.executable, "-c",
2266 'import sys;'
2267 'sys.stdout.write("apple");'
2268 'sys.stdout.flush();'
2269 'sys.stderr.write("orange")'],
2270 stdin=stdin,
2271 stdout=subprocess.PIPE,
2272 stderr=subprocess.PIPE).communicate()
2273 err = support.strip_python_stderr(err)
2274 self.assertEqual((out, err), (b'apple', b'orange'))
2275 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002276 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002277
2278 def test_close_fd_0(self):
2279 self.check_close_std_fds([0])
2280
2281 def test_close_fd_1(self):
2282 self.check_close_std_fds([1])
2283
2284 def test_close_fd_2(self):
2285 self.check_close_std_fds([2])
2286
2287 def test_close_fds_0_1(self):
2288 self.check_close_std_fds([0, 1])
2289
2290 def test_close_fds_0_2(self):
2291 self.check_close_std_fds([0, 2])
2292
2293 def test_close_fds_1_2(self):
2294 self.check_close_std_fds([1, 2])
2295
2296 def test_close_fds_0_1_2(self):
2297 # Issue #10806: test that subprocess pipes still work properly with
2298 # all standard fds closed.
2299 self.check_close_std_fds([0, 1, 2])
2300
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002301 def test_small_errpipe_write_fd(self):
2302 """Issue #15798: Popen should work when stdio fds are available."""
2303 new_stdin = os.dup(0)
2304 new_stdout = os.dup(1)
2305 try:
2306 os.close(0)
2307 os.close(1)
2308
2309 # Side test: if errpipe_write fails to have its CLOEXEC
2310 # flag set this should cause the parent to think the exec
2311 # failed. Extremely unlikely: everyone supports CLOEXEC.
2312 subprocess.Popen([
2313 sys.executable, "-c",
2314 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2315 finally:
2316 # Restore original stdin and stdout
2317 os.dup2(new_stdin, 0)
2318 os.dup2(new_stdout, 1)
2319 os.close(new_stdin)
2320 os.close(new_stdout)
2321
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002322 def test_remapping_std_fds(self):
2323 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002324 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002325 try:
2326 temp_fds = [fd for fd, fname in temps]
2327
2328 # unlink the files -- we won't need to reopen them
2329 for fd, fname in temps:
2330 os.unlink(fname)
2331
2332 # write some data to what will become stdin, and rewind
2333 os.write(temp_fds[1], b"STDIN")
2334 os.lseek(temp_fds[1], 0, 0)
2335
2336 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002337 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002338 try:
2339 # duplicate the file objects over the standard fd's
2340 for fd, temp_fd in enumerate(temp_fds):
2341 os.dup2(temp_fd, fd)
2342
2343 # now use those files in the "wrong" order, so that subprocess
2344 # has to rearrange them in the child
2345 p = subprocess.Popen([sys.executable, "-c",
2346 'import sys; got = sys.stdin.read();'
2347 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2348 stdin=temp_fds[1],
2349 stdout=temp_fds[2],
2350 stderr=temp_fds[0])
2351 p.wait()
2352 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002353 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002354
2355 for fd in temp_fds:
2356 os.lseek(fd, 0, 0)
2357
2358 out = os.read(temp_fds[2], 1024)
2359 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2360 self.assertEqual(out, b"got STDIN")
2361 self.assertEqual(err, b"err")
2362
2363 finally:
2364 for fd in temp_fds:
2365 os.close(fd)
2366
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002367 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2368 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002369 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002370 temp_fds = [fd for fd, fname in temps]
2371 try:
2372 # unlink the files -- we won't need to reopen them
2373 for fd, fname in temps:
2374 os.unlink(fname)
2375
2376 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002377 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002378 try:
2379 # duplicate the temp files over the standard fd's 0, 1, 2
2380 for fd, temp_fd in enumerate(temp_fds):
2381 os.dup2(temp_fd, fd)
2382
2383 # write some data to what will become stdin, and rewind
2384 os.write(stdin_no, b"STDIN")
2385 os.lseek(stdin_no, 0, 0)
2386
2387 # now use those files in the given order, so that subprocess
2388 # has to rearrange them in the child
2389 p = subprocess.Popen([sys.executable, "-c",
2390 'import sys; got = sys.stdin.read();'
2391 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2392 stdin=stdin_no,
2393 stdout=stdout_no,
2394 stderr=stderr_no)
2395 p.wait()
2396
2397 for fd in temp_fds:
2398 os.lseek(fd, 0, 0)
2399
2400 out = os.read(stdout_no, 1024)
2401 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2402 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002403 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002404
2405 self.assertEqual(out, b"got STDIN")
2406 self.assertEqual(err, b"err")
2407
2408 finally:
2409 for fd in temp_fds:
2410 os.close(fd)
2411
2412 # When duping fds, if there arises a situation where one of the fds is
2413 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2414 # This tests all combinations of this.
2415 def test_swap_fds(self):
2416 self.check_swap_fds(0, 1, 2)
2417 self.check_swap_fds(0, 2, 1)
2418 self.check_swap_fds(1, 0, 2)
2419 self.check_swap_fds(1, 2, 0)
2420 self.check_swap_fds(2, 0, 1)
2421 self.check_swap_fds(2, 1, 0)
2422
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002423 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2424 saved_fds = self._save_fds(range(3))
2425 try:
2426 for from_fd in from_fds:
2427 with tempfile.TemporaryFile() as f:
2428 os.dup2(f.fileno(), from_fd)
2429
2430 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2431 os.close(fd_to_close)
2432
2433 arg_names = ['stdin', 'stdout', 'stderr']
2434 kwargs = {}
2435 for from_fd, to_fd in zip(from_fds, to_fds):
2436 kwargs[arg_names[to_fd]] = from_fd
2437
2438 code = textwrap.dedent(r'''
2439 import os, sys
2440 skipped_fd = int(sys.argv[1])
2441 for fd in range(3):
2442 if fd != skipped_fd:
2443 os.write(fd, str(fd).encode('ascii'))
2444 ''')
2445
2446 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2447
2448 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2449 **kwargs)
2450 self.assertEqual(rc, 0)
2451
2452 for from_fd, to_fd in zip(from_fds, to_fds):
2453 os.lseek(from_fd, 0, os.SEEK_SET)
2454 read_bytes = os.read(from_fd, 1024)
2455 read_fds = list(map(int, read_bytes.decode('ascii')))
2456 msg = textwrap.dedent(f"""
2457 When testing {from_fds} to {to_fds} redirection,
2458 parent descriptor {from_fd} got redirected
2459 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2460 """)
2461 self.assertEqual([to_fd], read_fds, msg)
2462 finally:
2463 self._restore_fds(saved_fds)
2464
2465 # Check that subprocess can remap std fds correctly even
2466 # if one of them is closed (#32844).
2467 def test_swap_std_fds_with_one_closed(self):
2468 for from_fds in itertools.combinations(range(3), 2):
2469 for to_fds in itertools.permutations(range(3), 2):
2470 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2471
Victor Stinner13bb71c2010-04-23 21:41:56 +00002472 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002473 def prepare():
2474 raise ValueError("surrogate:\uDCff")
2475
2476 try:
2477 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002478 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002479 preexec_fn=prepare)
2480 except ValueError as err:
2481 # Pure Python implementations keeps the message
2482 self.assertIsNone(subprocess._posixsubprocess)
2483 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002484 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002485 # _posixsubprocess uses a default message
2486 self.assertIsNotNone(subprocess._posixsubprocess)
2487 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2488 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002489 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002490
Victor Stinner13bb71c2010-04-23 21:41:56 +00002491 def test_undecodable_env(self):
2492 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002493 encoded_value = value.encode("ascii", "surrogateescape")
2494
Victor Stinner13bb71c2010-04-23 21:41:56 +00002495 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002496 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002497 env = os.environ.copy()
2498 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002499 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002500 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002501 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002502 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002503 stdout = subprocess.check_output(
2504 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002505 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002506 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002507 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002508
2509 # test bytes
2510 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002511 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002512 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002513 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002514 stdout = subprocess.check_output(
2515 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002516 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002517 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002518 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002519
Victor Stinnerb745a742010-05-18 17:17:23 +00002520 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002521 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2522 args = list(ZERO_RETURN_CMD[1:])
2523 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002524 program = os.fsencode(program)
2525
2526 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002527 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002528 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002529
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002530 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002531 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002532 exitcode = subprocess.call(cmd, shell=True)
2533 self.assertEqual(exitcode, 0)
2534
Victor Stinnerb745a742010-05-18 17:17:23 +00002535 # bytes program, unicode PATH
2536 env = os.environ.copy()
2537 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002538 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002539 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002540
2541 # bytes program, bytes PATH
2542 envb = os.environb.copy()
2543 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002544 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002545 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002546
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002547 def test_pipe_cloexec(self):
2548 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2549 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2550
2551 p1 = subprocess.Popen([sys.executable, sleeper],
2552 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2553 stderr=subprocess.PIPE, close_fds=False)
2554
2555 self.addCleanup(p1.communicate, b'')
2556
2557 p2 = subprocess.Popen([sys.executable, fd_status],
2558 stdout=subprocess.PIPE, close_fds=False)
2559
2560 output, error = p2.communicate()
2561 result_fds = set(map(int, output.split(b',')))
2562 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2563 p1.stderr.fileno()])
2564
2565 self.assertFalse(result_fds & unwanted_fds,
2566 "Expected no fds from %r to be open in child, "
2567 "found %r" %
2568 (unwanted_fds, result_fds & unwanted_fds))
2569
2570 def test_pipe_cloexec_real_tools(self):
2571 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2572 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2573
2574 subdata = b'zxcvbn'
2575 data = subdata * 4 + b'\n'
2576
2577 p1 = subprocess.Popen([sys.executable, qcat],
2578 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2579 close_fds=False)
2580
2581 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2582 stdin=p1.stdout, stdout=subprocess.PIPE,
2583 close_fds=False)
2584
2585 self.addCleanup(p1.wait)
2586 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002587 def kill_p1():
2588 try:
2589 p1.terminate()
2590 except ProcessLookupError:
2591 pass
2592 def kill_p2():
2593 try:
2594 p2.terminate()
2595 except ProcessLookupError:
2596 pass
2597 self.addCleanup(kill_p1)
2598 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002599
2600 p1.stdin.write(data)
2601 p1.stdin.close()
2602
2603 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2604
2605 self.assertTrue(readfiles, "The child hung")
2606 self.assertEqual(p2.stdout.read(), data)
2607
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002608 p1.stdout.close()
2609 p2.stdout.close()
2610
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002611 def test_close_fds(self):
2612 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2613
2614 fds = os.pipe()
2615 self.addCleanup(os.close, fds[0])
2616 self.addCleanup(os.close, fds[1])
2617
2618 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002619 # add a bunch more fds
2620 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002621 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002622 self.addCleanup(os.close, fd)
2623 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002624
Victor Stinnerdaf45552013-08-28 00:53:59 +02002625 for fd in open_fds:
2626 os.set_inheritable(fd, True)
2627
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002628 p = subprocess.Popen([sys.executable, fd_status],
2629 stdout=subprocess.PIPE, close_fds=False)
2630 output, ignored = p.communicate()
2631 remaining_fds = set(map(int, output.split(b',')))
2632
2633 self.assertEqual(remaining_fds & open_fds, open_fds,
2634 "Some fds were closed")
2635
2636 p = subprocess.Popen([sys.executable, fd_status],
2637 stdout=subprocess.PIPE, close_fds=True)
2638 output, ignored = p.communicate()
2639 remaining_fds = set(map(int, output.split(b',')))
2640
2641 self.assertFalse(remaining_fds & open_fds,
2642 "Some fds were left open")
2643 self.assertIn(1, remaining_fds, "Subprocess failed")
2644
Gregory P. Smith8facece2012-01-21 14:01:08 -08002645 # Keep some of the fd's we opened open in the subprocess.
2646 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2647 fds_to_keep = set(open_fds.pop() for _ in range(8))
2648 p = subprocess.Popen([sys.executable, fd_status],
2649 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002650 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002651 output, ignored = p.communicate()
2652 remaining_fds = set(map(int, output.split(b',')))
2653
izbyshev2d8f0632017-12-19 03:26:49 +07002654 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002655 "Some fds not in pass_fds were left open")
2656 self.assertIn(1, remaining_fds, "Subprocess failed")
2657
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002658
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002659 @unittest.skipIf(sys.platform.startswith("freebsd") and
2660 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2661 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002662 def test_close_fds_when_max_fd_is_lowered(self):
2663 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2664 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2665
Gregory P. Smith634aa682014-06-15 17:51:04 -07002666 # This launches the meat of the test in a child process to
2667 # avoid messing with the larger unittest processes maximum
2668 # number of file descriptors.
2669 # This process launches:
2670 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2671 # a bunch of high open fds above the new lower rlimit.
2672 # Those are reported via stdout before launching a new
2673 # process with close_fds=False to run the actual test:
2674 # +--> The TEST: This one launches a fd_status.py
2675 # subprocess with close_fds=True so we can find out if
2676 # any of the fds above the lowered rlimit are still open.
2677 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2678 '''
2679 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002680 open_fds = set()
2681 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002682 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002683 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002684 open_fds.add(fd)
2685
2686 # Leave a two pairs of low ones available for use by the
2687 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002688 # We also leave 10 more open as some Python buildbots run into
2689 # "too many open files" errors during the test if we do not.
2690 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002691 os.close(fd)
2692 open_fds.remove(fd)
2693
2694 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002695 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002696 os.set_inheritable(fd, True)
2697
2698 max_fd_open = max(open_fds)
2699
Gregory P. Smith634aa682014-06-15 17:51:04 -07002700 # Communicate the open_fds to the parent unittest.TestCase process.
2701 print(','.join(map(str, sorted(open_fds))))
2702 sys.stdout.flush()
2703
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002704 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2705 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002706 # 29 is lower than the highest fds we are leaving open.
2707 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002708 # Launch a new Python interpreter with our low fd rlim_cur that
2709 # inherits open fds above that limit. It then uses subprocess
2710 # with close_fds=True to get a report of open fds in the child.
2711 # An explicit list of fds to check is passed to fd_status.py as
2712 # letting fd_status rely on its default logic would miss the
2713 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002714 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002715 [sys.executable, '-c',
2716 textwrap.dedent("""
2717 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002718 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002719 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002720 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002721 """.format(max_fd=max_fd_open+1))],
2722 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002723 finally:
2724 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002725 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002726
2727 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002728 output_lines = output.splitlines()
2729 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002730 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002731 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2732 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002733
Gregory P. Smith634aa682014-06-15 17:51:04 -07002734 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002735 msg="Some fds were left open.")
2736
2737
Victor Stinner88701e22011-06-01 13:13:04 +02002738 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2739 # descriptor of a pipe closed in the parent process is valid in the
2740 # child process according to fstat(), but the mode of the file
2741 # descriptor is invalid, and read or write raise an error.
2742 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002743 def test_pass_fds(self):
2744 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2745
2746 open_fds = set()
2747
2748 for x in range(5):
2749 fds = os.pipe()
2750 self.addCleanup(os.close, fds[0])
2751 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002752 os.set_inheritable(fds[0], True)
2753 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002754 open_fds.update(fds)
2755
2756 for fd in open_fds:
2757 p = subprocess.Popen([sys.executable, fd_status],
2758 stdout=subprocess.PIPE, close_fds=True,
2759 pass_fds=(fd, ))
2760 output, ignored = p.communicate()
2761
2762 remaining_fds = set(map(int, output.split(b',')))
2763 to_be_closed = open_fds - {fd}
2764
2765 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2766 self.assertFalse(remaining_fds & to_be_closed,
2767 "fd to be closed passed")
2768
2769 # pass_fds overrides close_fds with a warning.
2770 with self.assertWarns(RuntimeWarning) as context:
2771 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002772 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002773 close_fds=False, pass_fds=(fd, )))
2774 self.assertIn('overriding close_fds', str(context.warning))
2775
Victor Stinnerdaf45552013-08-28 00:53:59 +02002776 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002777 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002778
2779 inheritable, non_inheritable = os.pipe()
2780 self.addCleanup(os.close, inheritable)
2781 self.addCleanup(os.close, non_inheritable)
2782 os.set_inheritable(inheritable, True)
2783 os.set_inheritable(non_inheritable, False)
2784 pass_fds = (inheritable, non_inheritable)
2785 args = [sys.executable, script]
2786 args += list(map(str, pass_fds))
2787
2788 p = subprocess.Popen(args,
2789 stdout=subprocess.PIPE, close_fds=True,
2790 pass_fds=pass_fds)
2791 output, ignored = p.communicate()
2792 fds = set(map(int, output.split(b',')))
2793
2794 # the inheritable file descriptor must be inherited, so its inheritable
2795 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002796 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002797
2798 # inheritable flag must not be changed in the parent process
2799 self.assertEqual(os.get_inheritable(inheritable), True)
2800 self.assertEqual(os.get_inheritable(non_inheritable), False)
2801
Gregory P. Smithce344102018-09-10 17:46:22 -07002802
2803 # bpo-32270: Ensure that descriptors specified in pass_fds
2804 # are inherited even if they are used in redirections.
2805 # Contributed by @izbyshev.
2806 def test_pass_fds_redirected(self):
2807 """Regression test for https://bugs.python.org/issue32270."""
2808 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2809 pass_fds = []
2810 for _ in range(2):
2811 fd = os.open(os.devnull, os.O_RDWR)
2812 self.addCleanup(os.close, fd)
2813 pass_fds.append(fd)
2814
2815 stdout_r, stdout_w = os.pipe()
2816 self.addCleanup(os.close, stdout_r)
2817 self.addCleanup(os.close, stdout_w)
2818 pass_fds.insert(1, stdout_w)
2819
2820 with subprocess.Popen([sys.executable, fd_status],
2821 stdin=pass_fds[0],
2822 stdout=pass_fds[1],
2823 stderr=pass_fds[2],
2824 close_fds=True,
2825 pass_fds=pass_fds):
2826 output = os.read(stdout_r, 1024)
2827 fds = {int(num) for num in output.split(b',')}
2828
2829 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2830
2831
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002832 def test_stdout_stdin_are_single_inout_fd(self):
2833 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002834 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002835 stdout=inout, stdin=inout)
2836 p.wait()
2837
2838 def test_stdout_stderr_are_single_inout_fd(self):
2839 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002840 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002841 stdout=inout, stderr=inout)
2842 p.wait()
2843
2844 def test_stderr_stdin_are_single_inout_fd(self):
2845 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002846 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002847 stderr=inout, stdin=inout)
2848 p.wait()
2849
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002850 def test_wait_when_sigchild_ignored(self):
2851 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2852 sigchild_ignore = support.findfile("sigchild_ignore.py",
2853 subdir="subprocessdata")
2854 p = subprocess.Popen([sys.executable, sigchild_ignore],
2855 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2856 stdout, stderr = p.communicate()
2857 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002858 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002859 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002860
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002861 def test_select_unbuffered(self):
2862 # Issue #11459: bufsize=0 should really set the pipes as
2863 # unbuffered (and therefore let select() work properly).
2864 select = support.import_module("select")
2865 p = subprocess.Popen([sys.executable, "-c",
2866 'import sys;'
2867 'sys.stdout.write("apple")'],
2868 stdout=subprocess.PIPE,
2869 bufsize=0)
2870 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002871 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002872 try:
2873 self.assertEqual(f.read(4), b"appl")
2874 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2875 finally:
2876 p.wait()
2877
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002878 def test_zombie_fast_process_del(self):
2879 # Issue #12650: on Unix, if Popen.__del__() was called before the
2880 # process exited, it wouldn't be added to subprocess._active, and would
2881 # remain a zombie.
2882 # spawn a Popen, and delete its reference before it exits
2883 p = subprocess.Popen([sys.executable, "-c",
2884 'import sys, time;'
2885 'time.sleep(0.2)'],
2886 stdout=subprocess.PIPE,
2887 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002888 self.addCleanup(p.stdout.close)
2889 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002890 ident = id(p)
2891 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002892 with support.check_warnings(('', ResourceWarning)):
2893 p = None
2894
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002895 if mswindows:
2896 # subprocess._active is not used on Windows and is set to None.
2897 self.assertIsNone(subprocess._active)
2898 else:
2899 # check that p is in the active processes list
2900 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002901
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002902 def test_leak_fast_process_del_killed(self):
2903 # Issue #12650: on Unix, if Popen.__del__() was called before the
2904 # process exited, and the process got killed by a signal, it would never
2905 # be removed from subprocess._active, which triggered a FD and memory
2906 # leak.
2907 # spawn a Popen, delete its reference and kill it
2908 p = subprocess.Popen([sys.executable, "-c",
2909 'import time;'
2910 'time.sleep(3)'],
2911 stdout=subprocess.PIPE,
2912 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002913 self.addCleanup(p.stdout.close)
2914 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002915 ident = id(p)
2916 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002917 with support.check_warnings(('', ResourceWarning)):
2918 p = None
2919
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002920 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002921 if mswindows:
2922 # subprocess._active is not used on Windows and is set to None.
2923 self.assertIsNone(subprocess._active)
2924 else:
2925 # check that p is in the active processes list
2926 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002927
2928 # let some time for the process to exit, and create a new Popen: this
2929 # should trigger the wait() of p
2930 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002931 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002932 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002933 stdout=subprocess.PIPE,
2934 stderr=subprocess.PIPE) as proc:
2935 pass
2936 # p should have been wait()ed on, and removed from the _active list
2937 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002938 if mswindows:
2939 # subprocess._active is not used on Windows and is set to None.
2940 self.assertIsNone(subprocess._active)
2941 else:
2942 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002943
Charles-François Natali249cdc32013-08-25 18:24:45 +02002944 def test_close_fds_after_preexec(self):
2945 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2946
2947 # this FD is used as dup2() target by preexec_fn, and should be closed
2948 # in the child process
2949 fd = os.dup(1)
2950 self.addCleanup(os.close, fd)
2951
2952 p = subprocess.Popen([sys.executable, fd_status],
2953 stdout=subprocess.PIPE, close_fds=True,
2954 preexec_fn=lambda: os.dup2(1, fd))
2955 output, ignored = p.communicate()
2956
2957 remaining_fds = set(map(int, output.split(b',')))
2958
2959 self.assertNotIn(fd, remaining_fds)
2960
Victor Stinner8f437aa2014-10-05 17:25:19 +02002961 @support.cpython_only
2962 def test_fork_exec(self):
2963 # Issue #22290: fork_exec() must not crash on memory allocation failure
2964 # or other errors
2965 import _posixsubprocess
2966 gc_enabled = gc.isenabled()
2967 try:
2968 # Use a preexec function and enable the garbage collector
2969 # to force fork_exec() to re-enable the garbage collector
2970 # on error.
2971 func = lambda: None
2972 gc.enable()
2973
Victor Stinner8f437aa2014-10-05 17:25:19 +02002974 for args, exe_list, cwd, env_list in (
2975 (123, [b"exe"], None, [b"env"]),
2976 ([b"arg"], 123, None, [b"env"]),
2977 ([b"arg"], [b"exe"], 123, [b"env"]),
2978 ([b"arg"], [b"exe"], None, 123),
2979 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07002980 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02002981 _posixsubprocess.fork_exec(
2982 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002983 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002984 -1, -1, -1, -1,
2985 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07002986 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07002987 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07002988 func)
2989 # Attempt to prevent
2990 # "TypeError: fork_exec() takes exactly N arguments (M given)"
2991 # from passing the test. More refactoring to have us start
2992 # with a valid *args list, confirm a good call with that works
2993 # before mutating it in various ways to ensure that bad calls
2994 # with individual arg type errors raise a typeerror would be
2995 # ideal. Saving that for a future PR...
2996 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02002997 finally:
2998 if not gc_enabled:
2999 gc.disable()
3000
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003001 @support.cpython_only
3002 def test_fork_exec_sorted_fd_sanity_check(self):
3003 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3004 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003005 class BadInt:
3006 first = True
3007 def __init__(self, value):
3008 self.value = value
3009 def __int__(self):
3010 if self.first:
3011 self.first = False
3012 return self.value
3013 raise ValueError
3014
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003015 gc_enabled = gc.isenabled()
3016 try:
3017 gc.enable()
3018
3019 for fds_to_keep in (
3020 (-1, 2, 3, 4, 5), # Negative number.
3021 ('str', 4), # Not an int.
3022 (18, 23, 42, 2**63), # Out of range.
3023 (5, 4), # Not sorted.
3024 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003025 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003026 ):
3027 with self.assertRaises(
3028 ValueError,
3029 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3030 _posixsubprocess.fork_exec(
3031 [b"false"], [b"false"],
3032 True, fds_to_keep, None, [b"env"],
3033 -1, -1, -1, -1,
3034 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003035 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003036 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003037 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003038 self.assertIn('fds_to_keep', str(c.exception))
3039 finally:
3040 if not gc_enabled:
3041 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003042
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003043 def test_communicate_BrokenPipeError_stdin_close(self):
3044 # By not setting stdout or stderr or a timeout we force the fast path
3045 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003046 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003047 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3048 mock_proc_stdin.close.side_effect = BrokenPipeError
3049 proc.communicate() # Should swallow BrokenPipeError from close.
3050 mock_proc_stdin.close.assert_called_with()
3051
3052 def test_communicate_BrokenPipeError_stdin_write(self):
3053 # By not setting stdout or stderr or a timeout we force the fast path
3054 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003055 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003056 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3057 mock_proc_stdin.write.side_effect = BrokenPipeError
3058 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3059 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3060 mock_proc_stdin.close.assert_called_once_with()
3061
3062 def test_communicate_BrokenPipeError_stdin_flush(self):
3063 # Setting stdin and stdout forces the ._communicate() code path.
3064 # python -h exits faster than python -c pass (but spams stdout).
3065 proc = subprocess.Popen([sys.executable, '-h'],
3066 stdin=subprocess.PIPE,
3067 stdout=subprocess.PIPE)
3068 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3069 open(os.devnull, 'wb') as dev_null:
3070 mock_proc_stdin.flush.side_effect = BrokenPipeError
3071 # because _communicate registers a selector using proc.stdin...
3072 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3073 # _communicate() should swallow BrokenPipeError from flush.
3074 proc.communicate(b'stuff')
3075 mock_proc_stdin.flush.assert_called_once_with()
3076
3077 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3078 # Setting stdin and stdout forces the ._communicate() code path.
3079 # python -h exits faster than python -c pass (but spams stdout).
3080 proc = subprocess.Popen([sys.executable, '-h'],
3081 stdin=subprocess.PIPE,
3082 stdout=subprocess.PIPE)
3083 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3084 mock_proc_stdin.close.side_effect = BrokenPipeError
3085 # _communicate() should swallow BrokenPipeError from close.
3086 proc.communicate(timeout=999)
3087 mock_proc_stdin.close.assert_called_once_with()
3088
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003089 @unittest.skipUnless(_testcapi is not None
3090 and hasattr(_testcapi, 'W_STOPCODE'),
3091 'need _testcapi.W_STOPCODE')
3092 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003093 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003094 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003095 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003096
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003097 # Wait until the real process completes to avoid zombie process
3098 pid = proc.pid
3099 pid, status = os.waitpid(pid, 0)
3100 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003101
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003102 status = _testcapi.W_STOPCODE(3)
3103 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
3104 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003105
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003106 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003107
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003108
Victor Stinner937ee9e2018-06-26 02:11:06 +02003109@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003110class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003111
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003112 def test_startupinfo(self):
3113 # startupinfo argument
3114 # We uses hardcoded constants, because we do not want to
3115 # depend on win32all.
3116 STARTF_USESHOWWINDOW = 1
3117 SW_MAXIMIZE = 3
3118 startupinfo = subprocess.STARTUPINFO()
3119 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3120 startupinfo.wShowWindow = SW_MAXIMIZE
3121 # Since Python is a console process, it won't be affected
3122 # by wShowWindow, but the argument should be silently
3123 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003124 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003125 startupinfo=startupinfo)
3126
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303127 def test_startupinfo_keywords(self):
3128 # startupinfo argument
3129 # We use hardcoded constants, because we do not want to
3130 # depend on win32all.
3131 STARTF_USERSHOWWINDOW = 1
3132 SW_MAXIMIZE = 3
3133 startupinfo = subprocess.STARTUPINFO(
3134 dwFlags=STARTF_USERSHOWWINDOW,
3135 wShowWindow=SW_MAXIMIZE
3136 )
3137 # Since Python is a console process, it won't be affected
3138 # by wShowWindow, but the argument should be silently
3139 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003140 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303141 startupinfo=startupinfo)
3142
Victor Stinner483422f2018-07-05 22:54:17 +02003143 def test_startupinfo_copy(self):
3144 # bpo-34044: Popen must not modify input STARTUPINFO structure
3145 startupinfo = subprocess.STARTUPINFO()
3146 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3147 startupinfo.wShowWindow = subprocess.SW_HIDE
3148
3149 # Call Popen() twice with the same startupinfo object to make sure
3150 # that it's not modified
3151 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003152 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003153 with open(os.devnull, 'w') as null:
3154 proc = subprocess.Popen(cmd,
3155 stdout=null,
3156 stderr=subprocess.STDOUT,
3157 startupinfo=startupinfo)
3158 with proc:
3159 proc.communicate()
3160 self.assertEqual(proc.returncode, 0)
3161
3162 self.assertEqual(startupinfo.dwFlags,
3163 subprocess.STARTF_USESHOWWINDOW)
3164 self.assertIsNone(startupinfo.hStdInput)
3165 self.assertIsNone(startupinfo.hStdOutput)
3166 self.assertIsNone(startupinfo.hStdError)
3167 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3168 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3169
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003170 def test_creationflags(self):
3171 # creationflags argument
3172 CREATE_NEW_CONSOLE = 16
3173 sys.stderr.write(" a DOS box should flash briefly ...\n")
3174 subprocess.call(sys.executable +
3175 ' -c "import time; time.sleep(0.25)"',
3176 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003177
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003178 def test_invalid_args(self):
3179 # invalid arguments should raise ValueError
3180 self.assertRaises(ValueError, subprocess.call,
3181 [sys.executable, "-c",
3182 "import sys; sys.exit(47)"],
3183 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003184
Oren Milman0b3a87e2017-09-14 22:30:28 +03003185 @support.cpython_only
3186 def test_issue31471(self):
3187 # There shouldn't be an assertion failure in Popen() in case the env
3188 # argument has a bad keys() method.
3189 class BadEnv(dict):
3190 keys = None
3191 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003192 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003193
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003194 def test_close_fds(self):
3195 # close file descriptors
3196 rc = subprocess.call([sys.executable, "-c",
3197 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003198 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003199 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003200
Segev Finerb2a60832017-12-18 11:28:19 +02003201 def test_close_fds_with_stdio(self):
3202 import msvcrt
3203
3204 fds = os.pipe()
3205 self.addCleanup(os.close, fds[0])
3206 self.addCleanup(os.close, fds[1])
3207
3208 handles = []
3209 for fd in fds:
3210 os.set_inheritable(fd, True)
3211 handles.append(msvcrt.get_osfhandle(fd))
3212
3213 p = subprocess.Popen([sys.executable, "-c",
3214 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3215 stdout=subprocess.PIPE, close_fds=False)
3216 stdout, stderr = p.communicate()
3217 self.assertEqual(p.returncode, 0)
3218 int(stdout.strip()) # Check that stdout is an integer
3219
3220 p = subprocess.Popen([sys.executable, "-c",
3221 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3222 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3223 stdout, stderr = p.communicate()
3224 self.assertEqual(p.returncode, 1)
3225 self.assertIn(b"OSError", stderr)
3226
3227 # The same as the previous call, but with an empty handle_list
3228 handle_list = []
3229 startupinfo = subprocess.STARTUPINFO()
3230 startupinfo.lpAttributeList = {"handle_list": handle_list}
3231 p = subprocess.Popen([sys.executable, "-c",
3232 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3233 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3234 startupinfo=startupinfo, close_fds=True)
3235 stdout, stderr = p.communicate()
3236 self.assertEqual(p.returncode, 1)
3237 self.assertIn(b"OSError", stderr)
3238
3239 # Check for a warning due to using handle_list and close_fds=False
3240 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3241 startupinfo = subprocess.STARTUPINFO()
3242 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3243 p = subprocess.Popen([sys.executable, "-c",
3244 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3245 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3246 startupinfo=startupinfo, close_fds=False)
3247 stdout, stderr = p.communicate()
3248 self.assertEqual(p.returncode, 0)
3249
3250 def test_empty_attribute_list(self):
3251 startupinfo = subprocess.STARTUPINFO()
3252 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003253 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003254 startupinfo=startupinfo)
3255
3256 def test_empty_handle_list(self):
3257 startupinfo = subprocess.STARTUPINFO()
3258 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003259 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003260 startupinfo=startupinfo)
3261
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003262 def test_shell_sequence(self):
3263 # Run command through the shell (sequence)
3264 newenv = os.environ.copy()
3265 newenv["FRUIT"] = "physalis"
3266 p = subprocess.Popen(["set"], shell=1,
3267 stdout=subprocess.PIPE,
3268 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003269 with p:
3270 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003271
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003272 def test_shell_string(self):
3273 # Run command through the shell (string)
3274 newenv = os.environ.copy()
3275 newenv["FRUIT"] = "physalis"
3276 p = subprocess.Popen("set", shell=1,
3277 stdout=subprocess.PIPE,
3278 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003279 with p:
3280 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003281
Steve Dower050acae2016-09-06 20:16:17 -07003282 def test_shell_encodings(self):
3283 # Run command through the shell (string)
3284 for enc in ['ansi', 'oem']:
3285 newenv = os.environ.copy()
3286 newenv["FRUIT"] = "physalis"
3287 p = subprocess.Popen("set", shell=1,
3288 stdout=subprocess.PIPE,
3289 env=newenv,
3290 encoding=enc)
3291 with p:
3292 self.assertIn("physalis", p.stdout.read(), enc)
3293
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003294 def test_call_string(self):
3295 # call() function with string argument on Windows
3296 rc = subprocess.call(sys.executable +
3297 ' -c "import sys; sys.exit(47)"')
3298 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003299
Florent Xicluna4886d242010-03-08 13:27:26 +00003300 def _kill_process(self, method, *args):
3301 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003302 p = subprocess.Popen([sys.executable, "-c", """if 1:
3303 import sys, time
3304 sys.stdout.write('x\\n')
3305 sys.stdout.flush()
3306 time.sleep(30)
3307 """],
3308 stdin=subprocess.PIPE,
3309 stdout=subprocess.PIPE,
3310 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003311 with p:
3312 # Wait for the interpreter to be completely initialized before
3313 # sending any signal.
3314 p.stdout.read(1)
3315 getattr(p, method)(*args)
3316 _, stderr = p.communicate()
3317 self.assertStderrEqual(stderr, b'')
3318 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003319 self.assertNotEqual(returncode, 0)
3320
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003321 def _kill_dead_process(self, method, *args):
3322 p = subprocess.Popen([sys.executable, "-c", """if 1:
3323 import sys, time
3324 sys.stdout.write('x\\n')
3325 sys.stdout.flush()
3326 sys.exit(42)
3327 """],
3328 stdin=subprocess.PIPE,
3329 stdout=subprocess.PIPE,
3330 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003331 with p:
3332 # Wait for the interpreter to be completely initialized before
3333 # sending any signal.
3334 p.stdout.read(1)
3335 # The process should end after this
3336 time.sleep(1)
3337 # This shouldn't raise even though the child is now dead
3338 getattr(p, method)(*args)
3339 _, stderr = p.communicate()
3340 self.assertStderrEqual(stderr, b'')
3341 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003342 self.assertEqual(rc, 42)
3343
Florent Xicluna4886d242010-03-08 13:27:26 +00003344 def test_send_signal(self):
3345 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003346
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003347 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003348 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003349
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003350 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003351 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003352
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003353 def test_send_signal_dead(self):
3354 self._kill_dead_process('send_signal', signal.SIGTERM)
3355
3356 def test_kill_dead(self):
3357 self._kill_dead_process('kill')
3358
3359 def test_terminate_dead(self):
3360 self._kill_dead_process('terminate')
3361
Martin Panter23172bd2016-04-16 11:28:10 +00003362class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003363
3364 class RecordingPopen(subprocess.Popen):
3365 """A Popen that saves a reference to each instance for testing."""
3366 instances_created = []
3367
3368 def __init__(self, *args, **kwargs):
3369 super().__init__(*args, **kwargs)
3370 self.instances_created.append(self)
3371
3372 @mock.patch.object(subprocess.Popen, "_communicate")
3373 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3374 **kwargs):
3375 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3376
3377 This avoids the need to actually try and get test environments to send
3378 and receive signals reliably across platforms. The net effect of a ^C
3379 happening during a blocking subprocess execution which we want to clean
3380 up from is a KeyboardInterrupt coming out of communicate() or wait().
3381 """
3382
3383 mock__communicate.side_effect = KeyboardInterrupt
3384 try:
3385 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3386 # We patch out _wait() as no signal was involved so the
3387 # child process isn't actually going to exit rapidly.
3388 mock__wait.side_effect = KeyboardInterrupt
3389 with mock.patch.object(subprocess, "Popen",
3390 self.RecordingPopen):
3391 with self.assertRaises(KeyboardInterrupt):
3392 popener([sys.executable, "-c",
3393 "import time\ntime.sleep(9)\nimport sys\n"
3394 "sys.stderr.write('\\n!runaway child!\\n')"],
3395 stdout=subprocess.DEVNULL, **kwargs)
3396 for call in mock__wait.call_args_list[1:]:
3397 self.assertNotEqual(
3398 call, mock.call(timeout=None),
3399 "no open-ended wait() after the first allowed: "
3400 f"{mock__wait.call_args_list}")
3401 sigint_calls = []
3402 for call in mock__wait.call_args_list:
3403 if call == mock.call(timeout=0.25): # from Popen.__init__
3404 sigint_calls.append(call)
3405 self.assertLessEqual(mock__wait.call_count, 2,
3406 msg=mock__wait.call_args_list)
3407 self.assertEqual(len(sigint_calls), 1,
3408 msg=mock__wait.call_args_list)
3409 finally:
3410 # cleanup the forgotten (due to our mocks) child process
3411 process = self.RecordingPopen.instances_created.pop()
3412 process.kill()
3413 process.wait()
3414 self.assertEqual([], self.RecordingPopen.instances_created)
3415
3416 def test_call_keyboardinterrupt_no_kill(self):
3417 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3418
3419 def test_run_keyboardinterrupt_no_kill(self):
3420 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3421
3422 def test_context_manager_keyboardinterrupt_no_kill(self):
3423 def popen_via_context_manager(*args, **kwargs):
3424 with subprocess.Popen(*args, **kwargs) as unused_process:
3425 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3426 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3427
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003428 def test_getoutput(self):
3429 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3430 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3431 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003432
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003433 # we use mkdtemp in the next line to create an empty directory
3434 # under our exclusive control; from that, we can invent a pathname
3435 # that we _know_ won't exist. This is guaranteed to fail.
3436 dir = None
3437 try:
3438 dir = tempfile.mkdtemp()
3439 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003440 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003441 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003442 self.assertNotEqual(status, 0)
3443 finally:
3444 if dir is not None:
3445 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003446
Gregory P. Smithace55862015-04-07 15:57:54 -07003447 def test__all__(self):
3448 """Ensure that __all__ is populated properly."""
Patrick McLean2b2ead72019-09-12 10:15:44 -07003449 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003450 exported = set(subprocess.__all__)
3451 possible_exports = set()
3452 import types
3453 for name, value in subprocess.__dict__.items():
3454 if name.startswith('_'):
3455 continue
3456 if isinstance(value, (types.ModuleType,)):
3457 continue
3458 possible_exports.add(name)
3459 self.assertEqual(exported, possible_exports - intentionally_excluded)
3460
3461
Martin Panter23172bd2016-04-16 11:28:10 +00003462@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3463 "Test needs selectors.PollSelector")
3464class ProcessTestCaseNoPoll(ProcessTestCase):
3465 def setUp(self):
3466 self.orig_selector = subprocess._PopenSelector
3467 subprocess._PopenSelector = selectors.SelectSelector
3468 ProcessTestCase.setUp(self)
3469
3470 def tearDown(self):
3471 subprocess._PopenSelector = self.orig_selector
3472 ProcessTestCase.tearDown(self)
3473
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003474
Victor Stinner937ee9e2018-06-26 02:11:06 +02003475@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003476class CommandsWithSpaces (BaseTestCase):
3477
3478 def setUp(self):
3479 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003480 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003481 self.fname = fname.lower ()
3482 os.write(f, b"import sys;"
3483 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3484 )
3485 os.close(f)
3486
3487 def tearDown(self):
3488 os.remove(self.fname)
3489 super().tearDown()
3490
3491 def with_spaces(self, *args, **kwargs):
3492 kwargs['stdout'] = subprocess.PIPE
3493 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003494 with p:
3495 self.assertEqual(
3496 p.stdout.read ().decode("mbcs"),
3497 "2 [%r, 'ab cd']" % self.fname
3498 )
Tim Golden126c2962010-08-11 14:20:40 +00003499
3500 def test_shell_string_with_spaces(self):
3501 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003502 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3503 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003504
3505 def test_shell_sequence_with_spaces(self):
3506 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003507 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003508
3509 def test_noshell_string_with_spaces(self):
3510 # call() function with string argument with spaces on Windows
3511 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3512 "ab cd"))
3513
3514 def test_noshell_sequence_with_spaces(self):
3515 # call() function with sequence argument with spaces on Windows
3516 self.with_spaces([sys.executable, self.fname, "ab cd"])
3517
Brian Curtin79cdb662010-12-03 02:46:02 +00003518
Georg Brandla86b2622012-02-20 21:34:57 +01003519class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003520
3521 def test_pipe(self):
3522 with subprocess.Popen([sys.executable, "-c",
3523 "import sys;"
3524 "sys.stdout.write('stdout');"
3525 "sys.stderr.write('stderr');"],
3526 stdout=subprocess.PIPE,
3527 stderr=subprocess.PIPE) as proc:
3528 self.assertEqual(proc.stdout.read(), b"stdout")
3529 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3530
3531 self.assertTrue(proc.stdout.closed)
3532 self.assertTrue(proc.stderr.closed)
3533
3534 def test_returncode(self):
3535 with subprocess.Popen([sys.executable, "-c",
3536 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003537 pass
3538 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003539 self.assertEqual(proc.returncode, 100)
3540
3541 def test_communicate_stdin(self):
3542 with subprocess.Popen([sys.executable, "-c",
3543 "import sys;"
3544 "sys.exit(sys.stdin.read() == 'context')"],
3545 stdin=subprocess.PIPE) as proc:
3546 proc.communicate(b"context")
3547 self.assertEqual(proc.returncode, 1)
3548
3549 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003550 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003551 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003552 stdout=subprocess.PIPE,
3553 stderr=subprocess.PIPE) as proc:
3554 pass
3555
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003556 def test_broken_pipe_cleanup(self):
3557 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003558 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003559 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003560 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003561 proc = proc.__enter__()
3562 # Prepare to send enough data to overflow any OS pipe buffering and
3563 # guarantee a broken pipe error. Data is held in BufferedWriter
3564 # buffer until closed.
3565 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003566 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003567 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003568 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003569 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003570 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003571
Brian Curtin79cdb662010-12-03 02:46:02 +00003572
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003573if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003574 unittest.main()