blob: 2231ff49235c8f39ad42771276704610d69e8e01 [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')
62 if (os.access(shell_true, os.X_OK) and
63 subprocess.run([shell_true]).returncode == 0):
64 global ZERO_RETURN_CMD
65 ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup.
66
Florent Xiclunab1e94e82010-02-27 22:12:37 +000067
Florent Xiclunac049d872010-03-27 22:47:23 +000068class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069 def setUp(self):
70 # Try to minimize the number of children we have so this test
71 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000072 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000074 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030075 if not mswindows:
76 # subprocess._active is not used on Windows and is set to None.
77 for inst in subprocess._active:
78 inst.wait()
79 subprocess._cleanup()
80 self.assertFalse(
81 subprocess._active, "subprocess._active not empty"
82 )
Victor Stinnercc42c122017-07-28 18:00:22 +020083 self.doCleanups()
84 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000085
Florent Xiclunab1e94e82010-02-27 22:12:37 +000086 def assertStderrEqual(self, stderr, expected, msg=None):
87 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
88 # shutdown time. That frustrates tests trying to check stderr produced
89 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000090 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040091 # strip_python_stderr also strips whitespace, so we do too.
92 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000093 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000094
Florent Xiclunac049d872010-03-27 22:47:23 +000095
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080096class PopenTestException(Exception):
97 pass
98
99
100class PopenExecuteChildRaises(subprocess.Popen):
101 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
102 _execute_child fails.
103 """
104 def _execute_child(self, *args, **kwargs):
105 raise PopenTestException("Forced Exception for Test")
106
107
Florent Xiclunac049d872010-03-27 22:47:23 +0000108class ProcessTestCase(BaseTestCase):
109
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700110 def test_io_buffered_by_default(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700111 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700112 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
113 stderr=subprocess.PIPE)
114 try:
115 self.assertIsInstance(p.stdin, io.BufferedIOBase)
116 self.assertIsInstance(p.stdout, io.BufferedIOBase)
117 self.assertIsInstance(p.stderr, io.BufferedIOBase)
118 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700119 p.stdin.close()
120 p.stdout.close()
121 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700122 p.wait()
123
124 def test_io_unbuffered_works(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700125 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700126 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
127 stderr=subprocess.PIPE, bufsize=0)
128 try:
129 self.assertIsInstance(p.stdin, io.RawIOBase)
130 self.assertIsInstance(p.stdout, io.RawIOBase)
131 self.assertIsInstance(p.stderr, io.RawIOBase)
132 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700133 p.stdin.close()
134 p.stdout.close()
135 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700136 p.wait()
137
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000138 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000139 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000140 rc = subprocess.call([sys.executable, "-c",
141 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000142 self.assertEqual(rc, 47)
143
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400144 def test_call_timeout(self):
145 # call() function with timeout argument; we want to test that the child
146 # process gets killed when the timeout expires. If the child isn't
147 # killed, this call will deadlock since subprocess.call waits for the
148 # child.
149 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
150 [sys.executable, "-c", "while True: pass"],
151 timeout=0.1)
152
Peter Astrand454f7672005-01-01 09:36:35 +0000153 def test_check_call_zero(self):
154 # check_call() function with zero return code
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700155 rc = subprocess.check_call(ZERO_RETURN_CMD)
Peter Astrand454f7672005-01-01 09:36:35 +0000156 self.assertEqual(rc, 0)
157
158 def test_check_call_nonzero(self):
159 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000160 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000161 subprocess.check_call([sys.executable, "-c",
162 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000163 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000164
Georg Brandlf9734072008-12-07 15:30:06 +0000165 def test_check_output(self):
166 # check_output() function with zero return code
167 output = subprocess.check_output(
168 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000169 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000170
171 def test_check_output_nonzero(self):
172 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000173 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000174 subprocess.check_output(
175 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000176 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000177
178 def test_check_output_stderr(self):
179 # check_output() function stderr redirected to stdout
180 output = subprocess.check_output(
181 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
182 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000183 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000184
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300185 def test_check_output_stdin_arg(self):
186 # check_output() can be called with stdin set to a file
187 tf = tempfile.TemporaryFile()
188 self.addCleanup(tf.close)
189 tf.write(b'pear')
190 tf.seek(0)
191 output = subprocess.check_output(
192 [sys.executable, "-c",
193 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
194 stdin=tf)
195 self.assertIn(b'PEAR', output)
196
197 def test_check_output_input_arg(self):
198 # check_output() can be called with input set to a string
199 output = subprocess.check_output(
200 [sys.executable, "-c",
201 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
202 input=b'pear')
203 self.assertIn(b'PEAR', output)
204
Georg Brandlf9734072008-12-07 15:30:06 +0000205 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300206 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000207 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000208 output = subprocess.check_output(
209 [sys.executable, "-c", "print('will not be run')"],
210 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000211 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000212 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000213
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300214 def test_check_output_stdin_with_input_arg(self):
215 # check_output() refuses to accept 'stdin' with 'input'
216 tf = tempfile.TemporaryFile()
217 self.addCleanup(tf.close)
218 tf.write(b'pear')
219 tf.seek(0)
220 with self.assertRaises(ValueError) as c:
221 output = subprocess.check_output(
222 [sys.executable, "-c", "print('will not be run')"],
223 stdin=tf, input=b'hare')
224 self.fail("Expected ValueError when stdin and input args supplied.")
225 self.assertIn('stdin', c.exception.args[0])
226 self.assertIn('input', c.exception.args[0])
227
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400228 def test_check_output_timeout(self):
229 # check_output() function with timeout arg
230 with self.assertRaises(subprocess.TimeoutExpired) as c:
231 output = subprocess.check_output(
232 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200233 "import sys, time\n"
234 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400235 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200236 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400237 # Some heavily loaded buildbots (sparc Debian 3.x) require
238 # this much time to start and print.
239 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400240 self.fail("Expected TimeoutExpired.")
241 self.assertEqual(c.exception.output, b'BDFL')
242
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000243 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000244 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 newenv = os.environ.copy()
246 newenv["FRUIT"] = "banana"
247 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000248 'import sys, os;'
249 'sys.exit(os.getenv("FRUIT")=="banana")'],
250 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251 self.assertEqual(rc, 1)
252
Victor Stinner87b9bc32011-06-01 00:57:47 +0200253 def test_invalid_args(self):
254 # Popen() called with invalid arguments should raise TypeError
255 # but Popen.__del__ should not complain (issue #12085)
256 with support.captured_stderr() as s:
257 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
258 argcount = subprocess.Popen.__init__.__code__.co_argcount
259 too_many_args = [0] * (argcount + 1)
260 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
261 self.assertEqual(s.getvalue(), '')
262
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000264 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000265 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000266 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000267 self.addCleanup(p.stdout.close)
268 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269 p.wait()
270 self.assertEqual(p.stdin, None)
271
272 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200273 # .stdout is None when not redirected, and the child's stdout will
274 # be inherited from the parent. In order to test this we run a
275 # subprocess in a subprocess:
276 # this_test
277 # \-- subprocess created by this test (parent)
278 # \-- subprocess created by the parent subprocess (child)
279 # The parent doesn't specify stdout, so the child will use the
280 # parent's stdout. This test checks that the message printed by the
281 # child goes to the parent stdout. The parent also checks that the
282 # child's stdout is None. See #11963.
283 code = ('import sys; from subprocess import Popen, PIPE;'
284 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
285 ' stdin=PIPE, stderr=PIPE);'
286 'p.wait(); assert p.stdout is None;')
287 p = subprocess.Popen([sys.executable, "-c", code],
288 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
289 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000290 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200291 out, err = p.communicate()
292 self.assertEqual(p.returncode, 0, err)
293 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294
295 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000296 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000297 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000299 self.addCleanup(p.stdout.close)
300 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000301 p.wait()
302 self.assertEqual(p.stderr, None)
303
Chris Jerdonek776cb192012-10-08 15:56:43 -0700304 def _assert_python(self, pre_args, **kwargs):
305 # We include sys.exit() to prevent the test runner from hanging
306 # whenever python is found.
307 args = pre_args + ["import sys; sys.exit(47)"]
308 p = subprocess.Popen(args, **kwargs)
309 p.wait()
310 self.assertEqual(47, p.returncode)
311
312 def test_executable(self):
313 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700314 #
315 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
316 # determine where its standard library is, so we need the directory
317 # of args[0] to be valid for the Popen() call to Python to succeed.
318 # See also issue #16170 and issue #7774.
319 doesnotexist = os.path.join(os.path.dirname(sys.executable),
320 "doesnotexist")
321 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700322
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300323 def test_bytes_executable(self):
324 doesnotexist = os.path.join(os.path.dirname(sys.executable),
325 "doesnotexist")
326 self._assert_python([doesnotexist, "-c"],
327 executable=os.fsencode(sys.executable))
328
329 def test_pathlike_executable(self):
330 doesnotexist = os.path.join(os.path.dirname(sys.executable),
331 "doesnotexist")
332 self._assert_python([doesnotexist, "-c"],
333 executable=FakePath(sys.executable))
334
Chris Jerdonek776cb192012-10-08 15:56:43 -0700335 def test_executable_takes_precedence(self):
336 # Check that the executable argument takes precedence over args[0].
337 #
338 # Verify first that the call succeeds without the executable arg.
339 pre_args = [sys.executable, "-c"]
340 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100341 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100342 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100343 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700344
Victor Stinner937ee9e2018-06-26 02:11:06 +0200345 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700346 def test_executable_replaces_shell(self):
347 # Check that the executable argument replaces the default shell
348 # when shell=True.
349 self._assert_python([], executable=sys.executable, shell=True)
350
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300351 @unittest.skipIf(mswindows, "executable argument replaces shell")
352 def test_bytes_executable_replaces_shell(self):
353 self._assert_python([], executable=os.fsencode(sys.executable),
354 shell=True)
355
356 @unittest.skipIf(mswindows, "executable argument replaces shell")
357 def test_pathlike_executable_replaces_shell(self):
358 self._assert_python([], executable=FakePath(sys.executable),
359 shell=True)
360
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700361 # For use in the test_cwd* tests below.
362 def _normalize_cwd(self, cwd):
363 # Normalize an expected cwd (for Tru64 support).
364 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
365 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300366 with support.change_cwd(cwd):
367 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700368
369 # For use in the test_cwd* tests below.
370 def _split_python_path(self):
371 # Return normalized (python_dir, python_base).
372 python_path = os.path.realpath(sys.executable)
373 return os.path.split(python_path)
374
375 # For use in the test_cwd* tests below.
376 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
377 # Invoke Python via Popen, and assert that (1) the call succeeds,
378 # and that (2) the current working directory of the child process
379 # matches *expected_cwd*.
380 p = subprocess.Popen([python_arg, "-c",
381 "import os, sys; "
382 "sys.stdout.write(os.getcwd()); "
383 "sys.exit(47)"],
384 stdout=subprocess.PIPE,
385 **kwargs)
386 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000387 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700388 self.assertEqual(47, p.returncode)
389 normcase = os.path.normcase
390 self.assertEqual(normcase(expected_cwd),
391 normcase(p.stdout.read().decode("utf-8")))
392
393 def test_cwd(self):
394 # Check that cwd changes the cwd for the child process.
395 temp_dir = tempfile.gettempdir()
396 temp_dir = self._normalize_cwd(temp_dir)
397 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
398
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300399 def test_cwd_with_bytes(self):
400 temp_dir = tempfile.gettempdir()
401 temp_dir = self._normalize_cwd(temp_dir)
402 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
403
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530404 def test_cwd_with_pathlike(self):
405 temp_dir = tempfile.gettempdir()
406 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200407 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530408
Victor Stinner937ee9e2018-06-26 02:11:06 +0200409 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700410 def test_cwd_with_relative_arg(self):
411 # Check that Popen looks for args[0] relative to cwd if args[0]
412 # is relative.
413 python_dir, python_base = self._split_python_path()
414 rel_python = os.path.join(os.curdir, python_base)
415 with support.temp_cwd() as wrong_dir:
416 # Before calling with the correct cwd, confirm that the call fails
417 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700418 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700419 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700420 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700421 [rel_python], cwd=wrong_dir)
422 python_dir = self._normalize_cwd(python_dir)
423 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
424
Victor Stinner937ee9e2018-06-26 02:11:06 +0200425 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700426 def test_cwd_with_relative_executable(self):
427 # Check that Popen looks for executable relative to cwd if executable
428 # is relative (and that executable takes precedence over args[0]).
429 python_dir, python_base = self._split_python_path()
430 rel_python = os.path.join(os.curdir, python_base)
431 doesntexist = "somethingyoudonthave"
432 with support.temp_cwd() as wrong_dir:
433 # Before calling with the correct cwd, confirm that the call fails
434 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700435 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700436 [doesntexist], executable=rel_python)
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,
439 cwd=wrong_dir)
440 python_dir = self._normalize_cwd(python_dir)
441 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
442 cwd=python_dir)
443
444 def test_cwd_with_absolute_arg(self):
445 # Check that Popen can find the executable when the cwd is wrong
446 # if args[0] is an absolute path.
447 python_dir, python_base = self._split_python_path()
448 abs_python = os.path.join(python_dir, python_base)
449 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300450 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700451 # Before calling with an absolute path, confirm that using a
452 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700453 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700454 [rel_python], cwd=wrong_dir)
455 wrong_dir = self._normalize_cwd(wrong_dir)
456 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
457
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100458 @unittest.skipIf(sys.base_prefix != sys.prefix,
459 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000460 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700461 python_dir, python_base = self._split_python_path()
462 python_dir = self._normalize_cwd(python_dir)
463 self._assert_cwd(python_dir, "somethingyoudonthave",
464 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000465
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100466 @unittest.skipIf(sys.base_prefix != sys.prefix,
467 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000468 @unittest.skipIf(sysconfig.is_python_build(),
469 "need an installed Python. See #7774")
470 def test_executable_without_cwd(self):
471 # For a normal installation, it should work without 'cwd'
472 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700473 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
474 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000475
476 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000477 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478 p = subprocess.Popen([sys.executable, "-c",
479 'import sys; sys.exit(sys.stdin.read() == "pear")'],
480 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000481 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482 p.stdin.close()
483 p.wait()
484 self.assertEqual(p.returncode, 1)
485
486 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000487 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000488 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000489 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000491 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492 os.lseek(d, 0, 0)
493 p = subprocess.Popen([sys.executable, "-c",
494 'import sys; sys.exit(sys.stdin.read() == "pear")'],
495 stdin=d)
496 p.wait()
497 self.assertEqual(p.returncode, 1)
498
499 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000500 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000502 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000503 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504 tf.seek(0)
505 p = subprocess.Popen([sys.executable, "-c",
506 'import sys; sys.exit(sys.stdin.read() == "pear")'],
507 stdin=tf)
508 p.wait()
509 self.assertEqual(p.returncode, 1)
510
511 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000512 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000513 p = subprocess.Popen([sys.executable, "-c",
514 'import sys; sys.stdout.write("orange")'],
515 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200516 with p:
517 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518
519 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000520 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000521 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000522 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523 d = tf.fileno()
524 p = subprocess.Popen([sys.executable, "-c",
525 'import sys; sys.stdout.write("orange")'],
526 stdout=d)
527 p.wait()
528 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000529 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530
531 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000532 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000533 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000534 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000535 p = subprocess.Popen([sys.executable, "-c",
536 'import sys; sys.stdout.write("orange")'],
537 stdout=tf)
538 p.wait()
539 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000540 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000541
542 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000543 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000544 p = subprocess.Popen([sys.executable, "-c",
545 'import sys; sys.stderr.write("strawberry")'],
546 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200547 with p:
548 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549
550 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000551 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000552 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000553 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554 d = tf.fileno()
555 p = subprocess.Popen([sys.executable, "-c",
556 'import sys; sys.stderr.write("strawberry")'],
557 stderr=d)
558 p.wait()
559 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000560 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561
562 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000563 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000564 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000565 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000566 p = subprocess.Popen([sys.executable, "-c",
567 'import sys; sys.stderr.write("strawberry")'],
568 stderr=tf)
569 p.wait()
570 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000571 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000572
Martin Panterc7635892016-05-13 01:54:44 +0000573 def test_stderr_redirect_with_no_stdout_redirect(self):
574 # test stderr=STDOUT while stdout=None (not set)
575
576 # - grandchild prints to stderr
577 # - child redirects grandchild's stderr to its stdout
578 # - the parent should get grandchild's stderr in child's stdout
579 p = subprocess.Popen([sys.executable, "-c",
580 'import sys, subprocess;'
581 'rc = subprocess.call([sys.executable, "-c",'
582 ' "import sys;"'
583 ' "sys.stderr.write(\'42\')"],'
584 ' stderr=subprocess.STDOUT);'
585 'sys.exit(rc)'],
586 stdout=subprocess.PIPE,
587 stderr=subprocess.PIPE)
588 stdout, stderr = p.communicate()
589 #NOTE: stdout should get stderr from grandchild
590 self.assertStderrEqual(stdout, b'42')
591 self.assertStderrEqual(stderr, b'') # should be empty
592 self.assertEqual(p.returncode, 0)
593
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000594 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000595 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000597 'import sys;'
598 'sys.stdout.write("apple");'
599 'sys.stdout.flush();'
600 'sys.stderr.write("orange")'],
601 stdout=subprocess.PIPE,
602 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200603 with p:
604 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000605
606 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000607 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000608 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000609 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000610 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000611 'import sys;'
612 'sys.stdout.write("apple");'
613 'sys.stdout.flush();'
614 'sys.stderr.write("orange")'],
615 stdout=tf,
616 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000617 p.wait()
618 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000619 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000620
Thomas Wouters89f507f2006-12-13 04:49:30 +0000621 def test_stdout_filedes_of_stdout(self):
622 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200623 # To avoid printing the text on stdout, we do something similar to
624 # test_stdout_none (see above). The parent subprocess calls the child
625 # subprocess passing stdout=1, and this test uses stdout=PIPE in
626 # order to capture and check the output of the parent. See #11963.
627 code = ('import sys, subprocess; '
628 'rc = subprocess.call([sys.executable, "-c", '
629 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
630 'b\'test with stdout=1\'))"], stdout=1); '
631 'assert rc == 18')
632 p = subprocess.Popen([sys.executable, "-c", code],
633 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
634 self.addCleanup(p.stdout.close)
635 self.addCleanup(p.stderr.close)
636 out, err = p.communicate()
637 self.assertEqual(p.returncode, 0, err)
638 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000639
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200640 def test_stdout_devnull(self):
641 p = subprocess.Popen([sys.executable, "-c",
642 'for i in range(10240):'
643 'print("x" * 1024)'],
644 stdout=subprocess.DEVNULL)
645 p.wait()
646 self.assertEqual(p.stdout, None)
647
648 def test_stderr_devnull(self):
649 p = subprocess.Popen([sys.executable, "-c",
650 'import sys\n'
651 'for i in range(10240):'
652 'sys.stderr.write("x" * 1024)'],
653 stderr=subprocess.DEVNULL)
654 p.wait()
655 self.assertEqual(p.stderr, None)
656
657 def test_stdin_devnull(self):
658 p = subprocess.Popen([sys.executable, "-c",
659 'import sys;'
660 'sys.stdin.read(1)'],
661 stdin=subprocess.DEVNULL)
662 p.wait()
663 self.assertEqual(p.stdin, None)
664
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000665 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000666 newenv = os.environ.copy()
667 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200668 with subprocess.Popen([sys.executable, "-c",
669 'import sys,os;'
670 'sys.stdout.write(os.getenv("FRUIT"))'],
671 stdout=subprocess.PIPE,
672 env=newenv) as p:
673 stdout, stderr = p.communicate()
674 self.assertEqual(stdout, b"orange")
675
Victor Stinner62d51182011-06-23 01:02:25 +0200676 # Windows requires at least the SYSTEMROOT environment variable to start
677 # Python
678 @unittest.skipIf(sys.platform == 'win32',
679 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700680 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
681 'The Python shared library cannot be loaded '
682 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200683 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700684 """Verify that env={} is as empty as possible."""
685
Gregory P. Smith85aba232017-05-30 16:21:47 -0700686 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700687 """Determine if an environment variable is under our control."""
688 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
689 # on adding even when the environment in exec is empty.
690 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700691 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400692 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000693 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
694 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700695
Victor Stinnerf1512a22011-06-21 17:18:38 +0200696 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700697 'import os; print(list(os.environ.keys()))'],
698 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200699 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700700 child_env_names = eval(stdout.strip())
701 self.assertIsInstance(child_env_names, list)
702 child_env_names = [k for k in child_env_names
703 if not is_env_var_to_ignore(k)]
704 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000705
Serhiy Storchakad174d242017-06-23 19:39:27 +0300706 def test_invalid_cmd(self):
707 # null character in the command name
708 cmd = sys.executable + '\0'
709 with self.assertRaises(ValueError):
710 subprocess.Popen([cmd, "-c", "pass"])
711
712 # null character in the command argument
713 with self.assertRaises(ValueError):
714 subprocess.Popen([sys.executable, "-c", "pass#\0"])
715
716 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300717 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300718 newenv = os.environ.copy()
719 newenv["FRUIT\0VEGETABLE"] = "cabbage"
720 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700721 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300722
Ville Skyttä49b27342017-08-03 09:00:59 +0300723 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300724 newenv = os.environ.copy()
725 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
726 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700727 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300728
Ville Skyttä49b27342017-08-03 09:00:59 +0300729 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300730 newenv = os.environ.copy()
731 newenv["FRUIT=ORANGE"] = "lemon"
732 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700733 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300734
Ville Skyttä49b27342017-08-03 09:00:59 +0300735 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300736 newenv = os.environ.copy()
737 newenv["FRUIT"] = "orange=lemon"
738 with subprocess.Popen([sys.executable, "-c",
739 'import sys, os;'
740 'sys.stdout.write(os.getenv("FRUIT"))'],
741 stdout=subprocess.PIPE,
742 env=newenv) as p:
743 stdout, stderr = p.communicate()
744 self.assertEqual(stdout, b"orange=lemon")
745
Peter Astrandcbac93c2005-03-03 20:24:28 +0000746 def test_communicate_stdin(self):
747 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000748 'import sys;'
749 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000750 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000751 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000752 self.assertEqual(p.returncode, 1)
753
754 def test_communicate_stdout(self):
755 p = subprocess.Popen([sys.executable, "-c",
756 'import sys; sys.stdout.write("pineapple")'],
757 stdout=subprocess.PIPE)
758 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000759 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000760 self.assertEqual(stderr, None)
761
762 def test_communicate_stderr(self):
763 p = subprocess.Popen([sys.executable, "-c",
764 'import sys; sys.stderr.write("pineapple")'],
765 stderr=subprocess.PIPE)
766 (stdout, stderr) = p.communicate()
767 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000768 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000769
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000770 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000771 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000772 'import sys,os;'
773 'sys.stderr.write("pineapple");'
774 'sys.stdout.write(sys.stdin.read())'],
775 stdin=subprocess.PIPE,
776 stdout=subprocess.PIPE,
777 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000778 self.addCleanup(p.stdout.close)
779 self.addCleanup(p.stderr.close)
780 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000781 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000782 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000783 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000784
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400785 def test_communicate_timeout(self):
786 p = subprocess.Popen([sys.executable, "-c",
787 'import sys,os,time;'
788 'sys.stderr.write("pineapple\\n");'
789 'time.sleep(1);'
790 'sys.stderr.write("pear\\n");'
791 'sys.stdout.write(sys.stdin.read())'],
792 universal_newlines=True,
793 stdin=subprocess.PIPE,
794 stdout=subprocess.PIPE,
795 stderr=subprocess.PIPE)
796 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
797 timeout=0.3)
798 # Make sure we can keep waiting for it, and that we get the whole output
799 # after it completes.
800 (stdout, stderr) = p.communicate()
801 self.assertEqual(stdout, "banana")
802 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
803
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700804 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200805 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400806 p = subprocess.Popen([sys.executable, "-c",
807 'import sys,os,time;'
808 'sys.stdout.write("a" * (64 * 1024));'
809 'time.sleep(0.2);'
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 stdout=subprocess.PIPE)
816 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
817 (stdout, _) = p.communicate()
818 self.assertEqual(len(stdout), 4 * 64 * 1024)
819
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000820 # Test for the fd leak reported in http://bugs.python.org/issue2791.
821 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000822 for stdin_pipe in (False, True):
823 for stdout_pipe in (False, True):
824 for stderr_pipe in (False, True):
825 options = {}
826 if stdin_pipe:
827 options['stdin'] = subprocess.PIPE
828 if stdout_pipe:
829 options['stdout'] = subprocess.PIPE
830 if stderr_pipe:
831 options['stderr'] = subprocess.PIPE
832 if not options:
833 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700834 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000835 p.communicate()
836 if p.stdin is not None:
837 self.assertTrue(p.stdin.closed)
838 if p.stdout is not None:
839 self.assertTrue(p.stdout.closed)
840 if p.stderr is not None:
841 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000842
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000844 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000845 p = subprocess.Popen([sys.executable, "-c",
846 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 (stdout, stderr) = p.communicate()
848 self.assertEqual(stdout, None)
849 self.assertEqual(stderr, None)
850
851 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000852 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000853 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000854 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000856 os.close(x)
857 os.close(y)
858 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000859 'import sys,os;'
860 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200861 'sys.stderr.write("x" * %d);'
862 'sys.stdout.write(sys.stdin.read())' %
863 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000864 stdin=subprocess.PIPE,
865 stdout=subprocess.PIPE,
866 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000867 self.addCleanup(p.stdout.close)
868 self.addCleanup(p.stderr.close)
869 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200870 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000871 (stdout, stderr) = p.communicate(string_to_write)
872 self.assertEqual(stdout, string_to_write)
873
874 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000875 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000876 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000877 'import sys,os;'
878 'sys.stdout.write(sys.stdin.read())'],
879 stdin=subprocess.PIPE,
880 stdout=subprocess.PIPE,
881 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000882 self.addCleanup(p.stdout.close)
883 self.addCleanup(p.stderr.close)
884 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000885 p.stdin.write(b"banana")
886 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000887 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000888 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000889
andyclegg7fed7bd2017-10-23 03:01:19 +0100890 def test_universal_newlines_and_text(self):
891 args = [
892 sys.executable, "-c",
893 'import sys,os;' + SETBINARY +
894 'buf = sys.stdout.buffer;'
895 'buf.write(sys.stdin.readline().encode());'
896 'buf.flush();'
897 'buf.write(b"line2\\n");'
898 'buf.flush();'
899 'buf.write(sys.stdin.read().encode());'
900 'buf.flush();'
901 'buf.write(b"line4\\n");'
902 'buf.flush();'
903 'buf.write(b"line5\\r\\n");'
904 'buf.flush();'
905 'buf.write(b"line6\\r");'
906 'buf.flush();'
907 'buf.write(b"\\nline7");'
908 'buf.flush();'
909 'buf.write(b"\\nline8");']
910
911 for extra_kwarg in ('universal_newlines', 'text'):
912 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
913 'stdout': subprocess.PIPE,
914 extra_kwarg: True})
915 with p:
916 p.stdin.write("line1\n")
917 p.stdin.flush()
918 self.assertEqual(p.stdout.readline(), "line1\n")
919 p.stdin.write("line3\n")
920 p.stdin.close()
921 self.addCleanup(p.stdout.close)
922 self.assertEqual(p.stdout.readline(),
923 "line2\n")
924 self.assertEqual(p.stdout.read(6),
925 "line3\n")
926 self.assertEqual(p.stdout.read(),
927 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000928
929 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000930 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000932 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200933 'buf = sys.stdout.buffer;'
934 'buf.write(b"line2\\n");'
935 'buf.flush();'
936 'buf.write(b"line4\\n");'
937 'buf.flush();'
938 'buf.write(b"line5\\r\\n");'
939 'buf.flush();'
940 'buf.write(b"line6\\r");'
941 'buf.flush();'
942 'buf.write(b"\\nline7");'
943 'buf.flush();'
944 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200945 stderr=subprocess.PIPE,
946 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000947 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000948 self.addCleanup(p.stdout.close)
949 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000950 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200951 self.assertEqual(stdout,
952 "line2\nline4\nline5\nline6\nline7\nline8")
953
954 def test_universal_newlines_communicate_stdin(self):
955 # universal newlines through communicate(), with only stdin
956 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300957 'import sys,os;' + SETBINARY + textwrap.dedent('''
958 s = sys.stdin.readline()
959 assert s == "line1\\n", repr(s)
960 s = sys.stdin.read()
961 assert s == "line3\\n", repr(s)
962 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200963 stdin=subprocess.PIPE,
964 universal_newlines=1)
965 (stdout, stderr) = p.communicate("line1\nline3\n")
966 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000967
Andrew Svetlovf3765072012-08-14 18:35:17 +0300968 def test_universal_newlines_communicate_input_none(self):
969 # Test communicate(input=None) with universal newlines.
970 #
971 # We set stdout to PIPE because, as of this writing, a different
972 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700973 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +0300974 stdin=subprocess.PIPE,
975 stdout=subprocess.PIPE,
976 universal_newlines=True)
977 p.communicate()
978 self.assertEqual(p.returncode, 0)
979
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300980 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300981 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300982 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300983 'import sys,os;' + SETBINARY + textwrap.dedent('''
984 s = sys.stdin.buffer.readline()
985 sys.stdout.buffer.write(s)
986 sys.stdout.buffer.write(b"line2\\r")
987 sys.stderr.buffer.write(b"eline2\\n")
988 s = sys.stdin.buffer.read()
989 sys.stdout.buffer.write(s)
990 sys.stdout.buffer.write(b"line4\\n")
991 sys.stdout.buffer.write(b"line5\\r\\n")
992 sys.stderr.buffer.write(b"eline6\\r")
993 sys.stderr.buffer.write(b"eline7\\r\\nz")
994 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300995 stdin=subprocess.PIPE,
996 stderr=subprocess.PIPE,
997 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300998 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300999 self.addCleanup(p.stdout.close)
1000 self.addCleanup(p.stderr.close)
1001 (stdout, stderr) = p.communicate("line1\nline3\n")
1002 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001003 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001004 # Python debug build push something like "[42442 refs]\n"
1005 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001006 # Don't use assertStderrEqual because it strips CR and LF from output.
1007 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001008
Andrew Svetlov82860712012-08-19 22:13:41 +03001009 def test_universal_newlines_communicate_encodings(self):
1010 # Check that universal newlines mode works for various encodings,
1011 # in particular for encodings in the UTF-16 and UTF-32 families.
1012 # See issue #15595.
1013 #
1014 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1015 # without, and UTF-16 and UTF-32.
1016 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001017 code = ("import sys; "
1018 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1019 encoding)
1020 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001021 # We set stdin to be non-None because, as of this writing,
1022 # a different code path is used when the number of pipes is
1023 # zero or one.
1024 popen = subprocess.Popen(args,
1025 stdin=subprocess.PIPE,
1026 stdout=subprocess.PIPE,
1027 encoding=encoding)
1028 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001029 self.assertEqual(stdout, '1\n2\n3\n4')
1030
Steve Dower050acae2016-09-06 20:16:17 -07001031 def test_communicate_errors(self):
1032 for errors, expected in [
1033 ('ignore', ''),
1034 ('replace', '\ufffd\ufffd'),
1035 ('surrogateescape', '\udc80\udc80'),
1036 ('backslashreplace', '\\x80\\x80'),
1037 ]:
1038 code = ("import sys; "
1039 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1040 args = [sys.executable, '-c', code]
1041 # We set stdin to be non-None because, as of this writing,
1042 # a different code path is used when the number of pipes is
1043 # zero or one.
1044 popen = subprocess.Popen(args,
1045 stdin=subprocess.PIPE,
1046 stdout=subprocess.PIPE,
1047 encoding='utf-8',
1048 errors=errors)
1049 stdout, stderr = popen.communicate(input='')
1050 self.assertEqual(stdout, '[{}]'.format(expected))
1051
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001052 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001053 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001054 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001055 max_handles = 1026 # too much for most UNIX systems
1056 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001057 max_handles = 2050 # too much for (at least some) Windows setups
1058 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001059 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001060 try:
1061 for i in range(max_handles):
1062 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001063 tmpfile = os.path.join(tmpdir, support.TESTFN)
1064 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001065 except OSError as e:
1066 if e.errno != errno.EMFILE:
1067 raise
1068 break
1069 else:
1070 self.skipTest("failed to reach the file descriptor limit "
1071 "(tried %d)" % max_handles)
1072 # Close a couple of them (should be enough for a subprocess)
1073 for i in range(10):
1074 os.close(handles.pop())
1075 # Loop creating some subprocesses. If one of them leaks some fds,
1076 # the next loop iteration will fail by reaching the max fd limit.
1077 for i in range(15):
1078 p = subprocess.Popen([sys.executable, "-c",
1079 "import sys;"
1080 "sys.stdout.write(sys.stdin.read())"],
1081 stdin=subprocess.PIPE,
1082 stdout=subprocess.PIPE,
1083 stderr=subprocess.PIPE)
1084 data = p.communicate(b"lime")[0]
1085 self.assertEqual(data, b"lime")
1086 finally:
1087 for h in handles:
1088 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001089 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001090
1091 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001092 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1093 '"a b c" d e')
1094 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1095 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001096 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1097 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001098 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1099 'a\\\\\\b "de fg" h')
1100 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1101 'a\\\\\\"b c d')
1102 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1103 '"a\\\\b c" d e')
1104 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1105 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001106 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1107 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001108
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001109 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001110 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001111 "import os; os.read(0, 1)"],
1112 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001113 self.addCleanup(p.stdin.close)
1114 self.assertIsNone(p.poll())
1115 os.write(p.stdin.fileno(), b'A')
1116 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001117 # Subsequent invocations should just return the returncode
1118 self.assertEqual(p.poll(), 0)
1119
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001120 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001121 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001122 self.assertEqual(p.wait(), 0)
1123 # Subsequent invocations should just return the returncode
1124 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001125
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001126 def test_wait_timeout(self):
1127 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001128 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001129 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001130 p.wait(timeout=0.0001)
1131 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001132 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1133 # time to start.
1134 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001135
Peter Astrand738131d2004-11-30 21:04:45 +00001136 def test_invalid_bufsize(self):
1137 # an invalid type of the bufsize argument should raise
1138 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001139 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001140 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001141
Guido van Rossum46a05a72007-06-07 21:56:45 +00001142 def test_bufsize_is_none(self):
1143 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001144 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001145 self.assertEqual(p.wait(), 0)
1146 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001147 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001148 self.assertEqual(p.wait(), 0)
1149
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001150 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1151 # subprocess may deadlock with bufsize=1, see issue #21332
1152 with subprocess.Popen([sys.executable, "-c", "import sys;"
1153 "sys.stdout.write(sys.stdin.readline());"
1154 "sys.stdout.flush()"],
1155 stdin=subprocess.PIPE,
1156 stdout=subprocess.PIPE,
1157 stderr=subprocess.DEVNULL,
1158 bufsize=1,
1159 universal_newlines=universal_newlines) as p:
1160 p.stdin.write(line) # expect that it flushes the line in text mode
1161 os.close(p.stdin.fileno()) # close it without flushing the buffer
1162 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001163 with support.SuppressCrashReport():
1164 try:
1165 p.stdin.close()
1166 except OSError:
1167 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001168 p.stdin = None
1169 self.assertEqual(p.returncode, 0)
1170 self.assertEqual(read_line, expected)
1171
1172 def test_bufsize_equal_one_text_mode(self):
1173 # line is flushed in text mode with bufsize=1.
1174 # we should get the full line in return
1175 line = "line\n"
1176 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1177
1178 def test_bufsize_equal_one_binary_mode(self):
1179 # line is not flushed in binary mode with bufsize=1.
1180 # we should get empty response
1181 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001182 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1183 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001184
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001185 def test_leaking_fds_on_error(self):
1186 # see bug #5179: Popen leaks file descriptors to PIPEs if
1187 # the child fails to execute; this will eventually exhaust
1188 # the maximum number of open fds. 1024 seems a very common
1189 # value for that limit, but Windows has 2048, so we loop
1190 # 1024 times (each call leaked two fds).
1191 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001192 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001193 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001194 stdout=subprocess.PIPE,
1195 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001196
Victor Stinner9a83f652017-08-21 23:51:31 +02001197 def test_nonexisting_with_pipes(self):
1198 # bpo-30121: Popen with pipes must close properly pipes on error.
1199 # Previously, os.close() was called with a Windows handle which is not
1200 # a valid file descriptor.
1201 #
1202 # Run the test in a subprocess to control how the CRT reports errors
1203 # and to get stderr content.
1204 try:
1205 import msvcrt
1206 msvcrt.CrtSetReportMode
1207 except (AttributeError, ImportError):
1208 self.skipTest("need msvcrt.CrtSetReportMode")
1209
1210 code = textwrap.dedent(f"""
1211 import msvcrt
1212 import subprocess
1213
1214 cmd = {NONEXISTING_CMD!r}
1215
1216 for report_type in [msvcrt.CRT_WARN,
1217 msvcrt.CRT_ERROR,
1218 msvcrt.CRT_ASSERT]:
1219 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1220 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1221
1222 try:
Zachary Ware55376462018-02-19 14:02:38 -06001223 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001224 stdout=subprocess.PIPE,
1225 stderr=subprocess.PIPE)
1226 except OSError:
1227 pass
1228 """)
1229 cmd = [sys.executable, "-c", code]
1230 proc = subprocess.Popen(cmd,
1231 stderr=subprocess.PIPE,
1232 universal_newlines=True)
1233 with proc:
1234 stderr = proc.communicate()[1]
1235 self.assertEqual(stderr, "")
1236 self.assertEqual(proc.returncode, 0)
1237
Antoine Pitroua8392712013-08-30 23:38:13 +02001238 def test_double_close_on_error(self):
1239 # Issue #18851
1240 fds = []
1241 def open_fds():
1242 for i in range(20):
1243 fds.extend(os.pipe())
1244 time.sleep(0.001)
1245 t = threading.Thread(target=open_fds)
1246 t.start()
1247 try:
1248 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001249 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001250 stdin=subprocess.PIPE,
1251 stdout=subprocess.PIPE,
1252 stderr=subprocess.PIPE)
1253 finally:
1254 t.join()
1255 exc = None
1256 for fd in fds:
1257 # If a double close occurred, some of those fds will
1258 # already have been closed by mistake, and os.close()
1259 # here will raise.
1260 try:
1261 os.close(fd)
1262 except OSError as e:
1263 exc = e
1264 if exc is not None:
1265 raise exc
1266
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001267 def test_threadsafe_wait(self):
1268 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1269 proc = subprocess.Popen([sys.executable, '-c',
1270 'import time; time.sleep(12)'])
1271 self.assertEqual(proc.returncode, None)
1272 results = []
1273
1274 def kill_proc_timer_thread():
1275 results.append(('thread-start-poll-result', proc.poll()))
1276 # terminate it from the thread and wait for the result.
1277 proc.kill()
1278 proc.wait()
1279 results.append(('thread-after-kill-and-wait', proc.returncode))
1280 # this wait should be a no-op given the above.
1281 proc.wait()
1282 results.append(('thread-after-second-wait', proc.returncode))
1283
1284 # This is a timing sensitive test, the failure mode is
1285 # triggered when both the main thread and this thread are in
1286 # the wait() call at once. The delay here is to allow the
1287 # main thread to most likely be blocked in its wait() call.
1288 t = threading.Timer(0.2, kill_proc_timer_thread)
1289 t.start()
1290
Victor Stinner937ee9e2018-06-26 02:11:06 +02001291 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001292 expected_errorcode = 1
1293 else:
1294 # Should be -9 because of the proc.kill() from the thread.
1295 expected_errorcode = -9
1296
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001297 # Wait for the process to finish; the thread should kill it
1298 # long before it finishes on its own. Supplying a timeout
1299 # triggers a different code path for better coverage.
1300 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001301 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001302 msg="unexpected result in wait from main thread")
1303
1304 # This should be a no-op with no change in returncode.
1305 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001306 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001307 msg="unexpected result in second main wait.")
1308
1309 t.join()
1310 # Ensure that all of the thread results are as expected.
1311 # When a race condition occurs in wait(), the returncode could
1312 # be set by the wrong thread that doesn't actually have it
1313 # leading to an incorrect value.
1314 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001315 ('thread-after-kill-and-wait', expected_errorcode),
1316 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001317 results)
1318
Victor Stinnerb3693582010-05-21 20:13:12 +00001319 def test_issue8780(self):
1320 # Ensure that stdout is inherited from the parent
1321 # if stdout=PIPE is not used
1322 code = ';'.join((
1323 'import subprocess, sys',
1324 'retcode = subprocess.call('
1325 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1326 'assert retcode == 0'))
1327 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001328 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001329
Tim Goldenaf5ac392010-08-06 13:03:56 +00001330 def test_handles_closed_on_exception(self):
1331 # If CreateProcess exits with an error, ensure the
1332 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001333 ifhandle, ifname = tempfile.mkstemp()
1334 ofhandle, ofname = tempfile.mkstemp()
1335 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001336 try:
1337 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1338 stderr=efhandle)
1339 except OSError:
1340 os.close(ifhandle)
1341 os.remove(ifname)
1342 os.close(ofhandle)
1343 os.remove(ofname)
1344 os.close(efhandle)
1345 os.remove(efname)
1346 self.assertFalse(os.path.exists(ifname))
1347 self.assertFalse(os.path.exists(ofname))
1348 self.assertFalse(os.path.exists(efname))
1349
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001350 def test_communicate_epipe(self):
1351 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001352 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001353 stdin=subprocess.PIPE,
1354 stdout=subprocess.PIPE,
1355 stderr=subprocess.PIPE)
1356 self.addCleanup(p.stdout.close)
1357 self.addCleanup(p.stderr.close)
1358 self.addCleanup(p.stdin.close)
1359 p.communicate(b"x" * 2**20)
1360
1361 def test_communicate_epipe_only_stdin(self):
1362 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001363 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001364 stdin=subprocess.PIPE)
1365 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001366 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001367 p.communicate(b"x" * 2**20)
1368
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001369 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1370 "Requires signal.SIGUSR1")
1371 @unittest.skipUnless(hasattr(os, 'kill'),
1372 "Requires os.kill")
1373 @unittest.skipUnless(hasattr(os, 'getppid'),
1374 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001375 def test_communicate_eintr(self):
1376 # Issue #12493: communicate() should handle EINTR
1377 def handler(signum, frame):
1378 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001379 old_handler = signal.signal(signal.SIGUSR1, handler)
1380 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001381
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001382 args = [sys.executable, "-c",
1383 'import os, signal;'
1384 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001385 for stream in ('stdout', 'stderr'):
1386 kw = {stream: subprocess.PIPE}
1387 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001388 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001389 process.communicate()
1390
Tim Peterse718f612004-10-12 21:51:32 +00001391
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001392 # This test is Linux-ish specific for simplicity to at least have
1393 # some coverage. It is not a platform specific bug.
1394 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1395 "Linux specific")
1396 def test_failed_child_execute_fd_leak(self):
1397 """Test for the fork() failure fd leak reported in issue16327."""
1398 fd_directory = '/proc/%d/fd' % os.getpid()
1399 fds_before_popen = os.listdir(fd_directory)
1400 with self.assertRaises(PopenTestException):
1401 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001402 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001403 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1404
1405 # NOTE: This test doesn't verify that the real _execute_child
1406 # does not close the file descriptors itself on the way out
1407 # during an exception. Code inspection has confirmed that.
1408
1409 fds_after_exception = os.listdir(fd_directory)
1410 self.assertEqual(fds_before_popen, fds_after_exception)
1411
Victor Stinner937ee9e2018-06-26 02:11:06 +02001412 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001413 def test_file_not_found_includes_filename(self):
1414 with self.assertRaises(FileNotFoundError) as c:
1415 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1416 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1417
Victor Stinner937ee9e2018-06-26 02:11:06 +02001418 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001419 def test_file_not_found_with_bad_cwd(self):
1420 with self.assertRaises(FileNotFoundError) as c:
1421 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1422 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1423
Gregory P. Smith6e730002015-04-14 16:14:25 -07001424
1425class RunFuncTestCase(BaseTestCase):
1426 def run_python(self, code, **kwargs):
1427 """Run Python code in a subprocess using subprocess.run"""
1428 argv = [sys.executable, "-c", code]
1429 return subprocess.run(argv, **kwargs)
1430
1431 def test_returncode(self):
1432 # call() function with sequence argument
1433 cp = self.run_python("import sys; sys.exit(47)")
1434 self.assertEqual(cp.returncode, 47)
1435 with self.assertRaises(subprocess.CalledProcessError):
1436 cp.check_returncode()
1437
1438 def test_check(self):
1439 with self.assertRaises(subprocess.CalledProcessError) as c:
1440 self.run_python("import sys; sys.exit(47)", check=True)
1441 self.assertEqual(c.exception.returncode, 47)
1442
1443 def test_check_zero(self):
1444 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001445 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001446 self.assertEqual(cp.returncode, 0)
1447
1448 def test_timeout(self):
1449 # run() function with timeout argument; we want to test that the child
1450 # process gets killed when the timeout expires. If the child isn't
1451 # killed, this call will deadlock since subprocess.run waits for the
1452 # child.
1453 with self.assertRaises(subprocess.TimeoutExpired):
1454 self.run_python("while True: pass", timeout=0.0001)
1455
1456 def test_capture_stdout(self):
1457 # capture stdout with zero return code
1458 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1459 self.assertIn(b'BDFL', cp.stdout)
1460
1461 def test_capture_stderr(self):
1462 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1463 stderr=subprocess.PIPE)
1464 self.assertIn(b'BDFL', cp.stderr)
1465
1466 def test_check_output_stdin_arg(self):
1467 # run() can be called with stdin set to a file
1468 tf = tempfile.TemporaryFile()
1469 self.addCleanup(tf.close)
1470 tf.write(b'pear')
1471 tf.seek(0)
1472 cp = self.run_python(
1473 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1474 stdin=tf, stdout=subprocess.PIPE)
1475 self.assertIn(b'PEAR', cp.stdout)
1476
1477 def test_check_output_input_arg(self):
1478 # check_output() can be called with input set to a string
1479 cp = self.run_python(
1480 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1481 input=b'pear', stdout=subprocess.PIPE)
1482 self.assertIn(b'PEAR', cp.stdout)
1483
1484 def test_check_output_stdin_with_input_arg(self):
1485 # run() refuses to accept 'stdin' with 'input'
1486 tf = tempfile.TemporaryFile()
1487 self.addCleanup(tf.close)
1488 tf.write(b'pear')
1489 tf.seek(0)
1490 with self.assertRaises(ValueError,
1491 msg="Expected ValueError when stdin and input args supplied.") as c:
1492 output = self.run_python("print('will not be run')",
1493 stdin=tf, input=b'hare')
1494 self.assertIn('stdin', c.exception.args[0])
1495 self.assertIn('input', c.exception.args[0])
1496
1497 def test_check_output_timeout(self):
1498 with self.assertRaises(subprocess.TimeoutExpired) as c:
1499 cp = self.run_python((
1500 "import sys, time\n"
1501 "sys.stdout.write('BDFL')\n"
1502 "sys.stdout.flush()\n"
1503 "time.sleep(3600)"),
1504 # Some heavily loaded buildbots (sparc Debian 3.x) require
1505 # this much time to start and print.
1506 timeout=3, stdout=subprocess.PIPE)
1507 self.assertEqual(c.exception.output, b'BDFL')
1508 # output is aliased to stdout
1509 self.assertEqual(c.exception.stdout, b'BDFL')
1510
1511 def test_run_kwargs(self):
1512 newenv = os.environ.copy()
1513 newenv["FRUIT"] = "banana"
1514 cp = self.run_python(('import sys, os;'
1515 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1516 env=newenv)
1517 self.assertEqual(cp.returncode, 33)
1518
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001519 def test_run_with_pathlike_path(self):
1520 # bpo-31961: test run(pathlike_object)
1521 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001522 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001523 prog = 'tree.com' if mswindows else 'ls'
1524 path = shutil.which(prog)
1525 if path is None:
1526 self.skipTest(f'{prog} required for this test')
1527 path = FakePath(path)
1528 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1529 self.assertEqual(res.returncode, 0)
1530 with self.assertRaises(TypeError):
1531 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1532
1533 def test_run_with_bytes_path_and_arguments(self):
1534 # bpo-31961: test run([bytes_object, b'additional arguments'])
1535 path = os.fsencode(sys.executable)
1536 args = [path, '-c', b'import sys; sys.exit(57)']
1537 res = subprocess.run(args)
1538 self.assertEqual(res.returncode, 57)
1539
1540 def test_run_with_pathlike_path_and_arguments(self):
1541 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1542 path = FakePath(sys.executable)
1543 args = [path, '-c', 'import sys; sys.exit(57)']
1544 res = subprocess.run(args)
1545 self.assertEqual(res.returncode, 57)
1546
Bo Baylesce0f33d2018-01-30 00:40:39 -06001547 def test_capture_output(self):
1548 cp = self.run_python(("import sys;"
1549 "sys.stdout.write('BDFL'); "
1550 "sys.stderr.write('FLUFL')"),
1551 capture_output=True)
1552 self.assertIn(b'BDFL', cp.stdout)
1553 self.assertIn(b'FLUFL', cp.stderr)
1554
1555 def test_stdout_with_capture_output_arg(self):
1556 # run() refuses to accept 'stdout' with 'capture_output'
1557 tf = tempfile.TemporaryFile()
1558 self.addCleanup(tf.close)
1559 with self.assertRaises(ValueError,
1560 msg=("Expected ValueError when stdout and capture_output "
1561 "args supplied.")) as c:
1562 output = self.run_python("print('will not be run')",
1563 capture_output=True, stdout=tf)
1564 self.assertIn('stdout', c.exception.args[0])
1565 self.assertIn('capture_output', c.exception.args[0])
1566
1567 def test_stderr_with_capture_output_arg(self):
1568 # run() refuses to accept 'stderr' with 'capture_output'
1569 tf = tempfile.TemporaryFile()
1570 self.addCleanup(tf.close)
1571 with self.assertRaises(ValueError,
1572 msg=("Expected ValueError when stderr and capture_output "
1573 "args supplied.")) as c:
1574 output = self.run_python("print('will not be run')",
1575 capture_output=True, stderr=tf)
1576 self.assertIn('stderr', c.exception.args[0])
1577 self.assertIn('capture_output', c.exception.args[0])
1578
Gregory P. Smith580d2782019-09-11 04:23:05 -05001579 # This test _might_ wind up a bit fragile on loaded build+test machines
1580 # as it depends on the timing with wide enough margins for normal situations
1581 # but does assert that it happened "soon enough" to believe the right thing
1582 # happened.
1583 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1584 def test_run_with_shell_timeout_and_capture_output(self):
1585 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1586 before_secs = time.monotonic()
1587 try:
1588 subprocess.run('sleep 3', shell=True, timeout=0.1,
1589 capture_output=True) # New session unspecified.
1590 except subprocess.TimeoutExpired as exc:
1591 after_secs = time.monotonic()
1592 stacks = traceback.format_exc() # assertRaises doesn't give this.
1593 else:
1594 self.fail("TimeoutExpired not raised.")
1595 self.assertLess(after_secs - before_secs, 1.5,
1596 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1597 f"{stacks}```")
1598
Gregory P. Smith6e730002015-04-14 16:14:25 -07001599
Gregory P. Smith693aa802019-09-13 14:43:35 +01001600def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001601 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001602 if grp:
1603 try:
1604 grp.getgrnam(name_group)
1605 except KeyError:
1606 continue
1607 return name_group
1608 else:
1609 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1610
1611
Victor Stinner937ee9e2018-06-26 02:11:06 +02001612@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001613class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001614
Gregory P. Smith5591b022012-10-10 03:34:47 -07001615 def setUp(self):
1616 super().setUp()
1617 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1618
1619 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001620 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001621 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001622 except OSError as e:
1623 # This avoids hard coding the errno value or the OS perror()
1624 # string and instead capture the exception that we want to see
1625 # below for comparison.
1626 desired_exception = e
1627 else:
Martin Pantereb995702016-07-28 01:11:04 +00001628 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001629 self._nonexistent_dir)
1630 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001631
Gregory P. Smith5591b022012-10-10 03:34:47 -07001632 def test_exception_cwd(self):
1633 """Test error in the child raised in the parent for a bad cwd."""
1634 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001635 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001636 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001637 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001638 except OSError as e:
1639 # Test that the child process chdir failure actually makes
1640 # it up to the parent process as the correct exception.
1641 self.assertEqual(desired_exception.errno, e.errno)
1642 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001643 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001644 else:
1645 self.fail("Expected OSError: %s" % desired_exception)
1646
Gregory P. Smith5591b022012-10-10 03:34:47 -07001647 def test_exception_bad_executable(self):
1648 """Test error in the child raised in the parent for a bad executable."""
1649 desired_exception = self._get_chdir_exception()
1650 try:
1651 p = subprocess.Popen([sys.executable, "-c", ""],
1652 executable=self._nonexistent_dir)
1653 except OSError as e:
1654 # Test that the child process exec failure actually makes
1655 # it up to the parent process as the correct exception.
1656 self.assertEqual(desired_exception.errno, e.errno)
1657 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001658 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001659 else:
1660 self.fail("Expected OSError: %s" % desired_exception)
1661
1662 def test_exception_bad_args_0(self):
1663 """Test error in the child raised in the parent for a bad args[0]."""
1664 desired_exception = self._get_chdir_exception()
1665 try:
1666 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1667 except OSError as e:
1668 # Test that the child process exec failure actually makes
1669 # it up to the parent process as the correct exception.
1670 self.assertEqual(desired_exception.errno, e.errno)
1671 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001672 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001673 else:
1674 self.fail("Expected OSError: %s" % desired_exception)
1675
Ammar Askar3fc499b2017-09-06 02:41:30 -04001676 # We mock the __del__ method for Popen in the next two tests
1677 # because it does cleanup based on the pid returned by fork_exec
1678 # along with issuing a resource warning if it still exists. Since
1679 # we don't actually spawn a process in these tests we can forego
1680 # the destructor. An alternative would be to set _child_created to
1681 # False before the destructor is called but there is no easy way
1682 # to do that
1683 class PopenNoDestructor(subprocess.Popen):
1684 def __del__(self):
1685 pass
1686
1687 @mock.patch("subprocess._posixsubprocess.fork_exec")
1688 def test_exception_errpipe_normal(self, fork_exec):
1689 """Test error passing done through errpipe_write in the good case"""
1690 def proper_error(*args):
1691 errpipe_write = args[13]
1692 # Write the hex for the error code EISDIR: 'is a directory'
1693 err_code = '{:x}'.format(errno.EISDIR).encode()
1694 os.write(errpipe_write, b"OSError:" + err_code + b":")
1695 return 0
1696
1697 fork_exec.side_effect = proper_error
1698
Victor Stinner11045c92017-10-05 06:32:53 -07001699 with mock.patch("subprocess.os.waitpid",
1700 side_effect=ChildProcessError):
1701 with self.assertRaises(IsADirectoryError):
1702 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001703
1704 @mock.patch("subprocess._posixsubprocess.fork_exec")
1705 def test_exception_errpipe_bad_data(self, fork_exec):
1706 """Test error passing done through errpipe_write where its not
1707 in the expected format"""
1708 error_data = b"\xFF\x00\xDE\xAD"
1709 def bad_error(*args):
1710 errpipe_write = args[13]
1711 # Anything can be in the pipe, no assumptions should
1712 # be made about its encoding, so we'll write some
1713 # arbitrary hex bytes to test it out
1714 os.write(errpipe_write, error_data)
1715 return 0
1716
1717 fork_exec.side_effect = bad_error
1718
Victor Stinner11045c92017-10-05 06:32:53 -07001719 with mock.patch("subprocess.os.waitpid",
1720 side_effect=ChildProcessError):
1721 with self.assertRaises(subprocess.SubprocessError) as e:
1722 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001723
1724 self.assertIn(repr(error_data), str(e.exception))
1725
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001726 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1727 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001728 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001729 # Blindly assume that cat exists on systems with /proc/self/status...
1730 default_proc_status = subprocess.check_output(
1731 ['cat', '/proc/self/status'],
1732 restore_signals=False)
1733 for line in default_proc_status.splitlines():
1734 if line.startswith(b'SigIgn'):
1735 default_sig_ign_mask = line
1736 break
1737 else:
1738 self.skipTest("SigIgn not found in /proc/self/status.")
1739 restored_proc_status = subprocess.check_output(
1740 ['cat', '/proc/self/status'],
1741 restore_signals=True)
1742 for line in restored_proc_status.splitlines():
1743 if line.startswith(b'SigIgn'):
1744 restored_sig_ign_mask = line
1745 break
1746 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1747 msg="restore_signals=True should've unblocked "
1748 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001749
1750 def test_start_new_session(self):
1751 # For code coverage of calling setsid(). We don't care if we get an
1752 # EPERM error from it depending on the test execution environment, that
1753 # still indicates that it was called.
1754 try:
1755 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001756 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001757 start_new_session=True)
1758 except OSError as e:
1759 if e.errno != errno.EPERM:
1760 raise
1761 else:
Victor Stinner58840432019-06-14 19:31:43 +02001762 parent_sid = os.getsid(0)
1763 child_sid = int(output)
1764 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001765
Patrick McLean2b2ead72019-09-12 10:15:44 -07001766 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1767 def test_user(self):
1768 # For code coverage of the user parameter. We don't care if we get an
1769 # EPERM error from it depending on the test execution environment, that
1770 # still indicates that it was called.
1771
1772 uid = os.geteuid()
1773 test_users = [65534 if uid != 65534 else 65533, uid]
1774 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1775
1776 if pwd is not None:
1777 test_users.append(name_uid)
1778
1779 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001780 # posix_spawn() may be used with close_fds=False
1781 for close_fds in (False, True):
1782 with self.subTest(user=user, close_fds=close_fds):
1783 try:
1784 output = subprocess.check_output(
1785 [sys.executable, "-c",
1786 "import os; print(os.getuid())"],
1787 user=user,
1788 close_fds=close_fds)
1789 except PermissionError: # (EACCES, EPERM)
1790 pass
1791 except OSError as e:
1792 if e.errno not in (errno.EACCES, errno.EPERM):
1793 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001794 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001795 if isinstance(user, str):
1796 user_uid = pwd.getpwnam(user).pw_uid
1797 else:
1798 user_uid = user
1799 child_user = int(output)
1800 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001801
1802 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001803 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001804
1805 if pwd is None:
1806 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001807 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001808
1809 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1810 def test_user_error(self):
1811 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001812 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001813
1814 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1815 def test_group(self):
1816 gid = os.getegid()
1817 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001818 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001819
1820 if grp is not None:
1821 group_list.append(name_group)
1822
1823 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001824 # posix_spawn() may be used with close_fds=False
1825 for close_fds in (False, True):
1826 with self.subTest(group=group, close_fds=close_fds):
1827 try:
1828 output = subprocess.check_output(
1829 [sys.executable, "-c",
1830 "import os; print(os.getgid())"],
1831 group=group,
1832 close_fds=close_fds)
1833 except PermissionError: # (EACCES, EPERM)
1834 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001835 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001836 if isinstance(group, str):
1837 group_gid = grp.getgrnam(group).gr_gid
1838 else:
1839 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001840
Victor Stinnerfaca8552019-09-25 15:52:49 +02001841 child_group = int(output)
1842 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001843
1844 # make sure we bomb on negative values
1845 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001846 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001847
1848 if grp is None:
1849 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001850 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001851
1852 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1853 def test_group_error(self):
1854 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001855 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001856
1857 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1858 def test_extra_groups(self):
1859 gid = os.getegid()
1860 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001861 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001862 perm_error = False
1863
1864 if grp is not None:
1865 group_list.append(name_group)
1866
1867 try:
1868 output = subprocess.check_output(
1869 [sys.executable, "-c",
1870 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1871 extra_groups=group_list)
1872 except OSError as ex:
1873 if ex.errno != errno.EPERM:
1874 raise
1875 perm_error = True
1876
1877 else:
1878 parent_groups = os.getgroups()
1879 child_groups = json.loads(output)
1880
1881 if grp is not None:
1882 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
1883 for g in group_list]
1884 else:
1885 desired_gids = group_list
1886
1887 if perm_error:
1888 self.assertEqual(set(child_groups), set(parent_groups))
1889 else:
1890 self.assertEqual(set(desired_gids), set(child_groups))
1891
1892 # make sure we bomb on negative values
1893 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001894 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001895
1896 if grp is None:
1897 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001898 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07001899 extra_groups=[name_group])
1900
1901 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
1902 def test_extra_groups_error(self):
1903 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001904 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001905
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001906 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
1907 'POSIX umask() is not available.')
1908 def test_umask(self):
1909 tmpdir = None
1910 try:
1911 tmpdir = tempfile.mkdtemp()
1912 name = os.path.join(tmpdir, "beans")
1913 # We set an unusual umask in the child so as a unique mode
1914 # for us to test the child's touched file for.
1915 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001916 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001917 umask=0o053)
1918 # Ignore execute permissions entirely in our test,
1919 # filesystems could be mounted to ignore or force that.
1920 st_mode = os.stat(name).st_mode & 0o666
1921 expected_mode = 0o624
1922 self.assertEqual(expected_mode, st_mode,
1923 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
1924 finally:
1925 if tmpdir is not None:
1926 shutil.rmtree(tmpdir)
1927
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001928 def test_run_abort(self):
1929 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001930 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001931 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001932 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001933 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001934 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001935
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001936 def test_CalledProcessError_str_signal(self):
1937 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1938 error_string = str(err)
1939 # We're relying on the repr() of the signal.Signals intenum to provide
1940 # the word signal, the signal name and the numeric value.
1941 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001942 # We're not being specific about the signal name as some signals have
1943 # multiple names and which name is revealed can vary.
1944 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001945 self.assertIn(str(signal.SIGABRT), error_string)
1946
1947 def test_CalledProcessError_str_unknown_signal(self):
1948 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1949 error_string = str(err)
1950 self.assertIn("unknown signal 9876543.", error_string)
1951
1952 def test_CalledProcessError_str_non_zero(self):
1953 err = subprocess.CalledProcessError(2, "fake cmd")
1954 error_string = str(err)
1955 self.assertIn("non-zero exit status 2.", error_string)
1956
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001957 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001958 # DISCLAIMER: Setting environment variables is *not* a good use
1959 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001960 p = subprocess.Popen([sys.executable, "-c",
1961 'import sys,os;'
1962 'sys.stdout.write(os.getenv("FRUIT"))'],
1963 stdout=subprocess.PIPE,
1964 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001965 with p:
1966 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001967
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001968 def test_preexec_exception(self):
1969 def raise_it():
1970 raise ValueError("What if two swallows carried a coconut?")
1971 try:
1972 p = subprocess.Popen([sys.executable, "-c", ""],
1973 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001974 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001975 self.assertTrue(
1976 subprocess._posixsubprocess,
1977 "Expected a ValueError from the preexec_fn")
1978 except ValueError as e:
1979 self.assertIn("coconut", e.args[0])
1980 else:
1981 self.fail("Exception raised by preexec_fn did not make it "
1982 "to the parent process.")
1983
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001984 class _TestExecuteChildPopen(subprocess.Popen):
1985 """Used to test behavior at the end of _execute_child."""
1986 def __init__(self, testcase, *args, **kwargs):
1987 self._testcase = testcase
1988 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001989
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001990 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001991 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001992 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001993 finally:
1994 # Open a bunch of file descriptors and verify that
1995 # none of them are the same as the ones the Popen
1996 # instance is using for stdin/stdout/stderr.
1997 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1998 for _ in range(8)]
1999 try:
2000 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002001 self._testcase.assertNotIn(
2002 fd, (self.stdin.fileno(), self.stdout.fileno(),
2003 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002004 msg="At least one fd was closed early.")
2005 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002006 for fd in devzero_fds:
2007 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002008
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002009 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2010 def test_preexec_errpipe_does_not_double_close_pipes(self):
2011 """Issue16140: Don't double close pipes on preexec error."""
2012
2013 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002014 raise subprocess.SubprocessError(
2015 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002016
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002017 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002018 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002019 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002020 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2021 stderr=subprocess.PIPE, preexec_fn=raise_it)
2022
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002023 def test_preexec_gc_module_failure(self):
2024 # This tests the code that disables garbage collection if the child
2025 # process will execute any Python.
2026 def raise_runtime_error():
2027 raise RuntimeError("this shouldn't escape")
2028 enabled = gc.isenabled()
2029 orig_gc_disable = gc.disable
2030 orig_gc_isenabled = gc.isenabled
2031 try:
2032 gc.disable()
2033 self.assertFalse(gc.isenabled())
2034 subprocess.call([sys.executable, '-c', ''],
2035 preexec_fn=lambda: None)
2036 self.assertFalse(gc.isenabled(),
2037 "Popen enabled gc when it shouldn't.")
2038
2039 gc.enable()
2040 self.assertTrue(gc.isenabled())
2041 subprocess.call([sys.executable, '-c', ''],
2042 preexec_fn=lambda: None)
2043 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2044
2045 gc.disable = raise_runtime_error
2046 self.assertRaises(RuntimeError, subprocess.Popen,
2047 [sys.executable, '-c', ''],
2048 preexec_fn=lambda: None)
2049
2050 del gc.isenabled # force an AttributeError
2051 self.assertRaises(AttributeError, subprocess.Popen,
2052 [sys.executable, '-c', ''],
2053 preexec_fn=lambda: None)
2054 finally:
2055 gc.disable = orig_gc_disable
2056 gc.isenabled = orig_gc_isenabled
2057 if not enabled:
2058 gc.disable()
2059
Martin Panterf7fdbda2015-12-05 09:51:52 +00002060 @unittest.skipIf(
2061 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002062 def test_preexec_fork_failure(self):
2063 # The internal code did not preserve the previous exception when
2064 # re-enabling garbage collection
2065 try:
2066 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2067 except ImportError as err:
2068 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2069 limits = getrlimit(RLIMIT_NPROC)
2070 [_, hard] = limits
2071 setrlimit(RLIMIT_NPROC, (0, hard))
2072 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002073 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002074 subprocess.call([sys.executable, '-c', ''],
2075 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002076 except BlockingIOError:
2077 # Forking should raise EAGAIN, translated to BlockingIOError
2078 pass
2079 else:
2080 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002081
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002082 def test_args_string(self):
2083 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002084 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002085 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002086 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002087 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002088 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2089 sys.executable)
2090 os.chmod(fname, 0o700)
2091 p = subprocess.Popen(fname)
2092 p.wait()
2093 os.remove(fname)
2094 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002095
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002096 def test_invalid_args(self):
2097 # invalid arguments should raise ValueError
2098 self.assertRaises(ValueError, subprocess.call,
2099 [sys.executable, "-c",
2100 "import sys; sys.exit(47)"],
2101 startupinfo=47)
2102 self.assertRaises(ValueError, subprocess.call,
2103 [sys.executable, "-c",
2104 "import sys; sys.exit(47)"],
2105 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002106
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002107 def test_shell_sequence(self):
2108 # Run command through the shell (sequence)
2109 newenv = os.environ.copy()
2110 newenv["FRUIT"] = "apple"
2111 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2112 stdout=subprocess.PIPE,
2113 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002114 with p:
2115 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002116
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002117 def test_shell_string(self):
2118 # Run command through the shell (string)
2119 newenv = os.environ.copy()
2120 newenv["FRUIT"] = "apple"
2121 p = subprocess.Popen("echo $FRUIT", shell=1,
2122 stdout=subprocess.PIPE,
2123 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002124 with p:
2125 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002126
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002127 def test_call_string(self):
2128 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002129 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002130 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002131 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002132 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002133 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2134 sys.executable)
2135 os.chmod(fname, 0o700)
2136 rc = subprocess.call(fname)
2137 os.remove(fname)
2138 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002139
Stefan Krah9542cc62010-07-19 14:20:53 +00002140 def test_specific_shell(self):
2141 # Issue #9265: Incorrect name passed as arg[0].
2142 shells = []
2143 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2144 for name in ['bash', 'ksh']:
2145 sh = os.path.join(prefix, name)
2146 if os.path.isfile(sh):
2147 shells.append(sh)
2148 if not shells: # Will probably work for any shell but csh.
2149 self.skipTest("bash or ksh required for this test")
2150 sh = '/bin/sh'
2151 if os.path.isfile(sh) and not os.path.islink(sh):
2152 # Test will fail if /bin/sh is a symlink to csh.
2153 shells.append(sh)
2154 for sh in shells:
2155 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2156 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002157 with p:
2158 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002159
Florent Xicluna4886d242010-03-08 13:27:26 +00002160 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002161 # Do not inherit file handles from the parent.
2162 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002163 # Also set the SIGINT handler to the default to make sure it's not
2164 # being ignored (some tests rely on that.)
2165 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2166 try:
2167 p = subprocess.Popen([sys.executable, "-c", """if 1:
2168 import sys, time
2169 sys.stdout.write('x\\n')
2170 sys.stdout.flush()
2171 time.sleep(30)
2172 """],
2173 close_fds=True,
2174 stdin=subprocess.PIPE,
2175 stdout=subprocess.PIPE,
2176 stderr=subprocess.PIPE)
2177 finally:
2178 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002179 # Wait for the interpreter to be completely initialized before
2180 # sending any signal.
2181 p.stdout.read(1)
2182 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002183 return p
2184
Charles-François Natali53221e32013-01-12 16:52:20 +01002185 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2186 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002187 def _kill_dead_process(self, method, *args):
2188 # Do not inherit file handles from the parent.
2189 # It should fix failures on some platforms.
2190 p = subprocess.Popen([sys.executable, "-c", """if 1:
2191 import sys, time
2192 sys.stdout.write('x\\n')
2193 sys.stdout.flush()
2194 """],
2195 close_fds=True,
2196 stdin=subprocess.PIPE,
2197 stdout=subprocess.PIPE,
2198 stderr=subprocess.PIPE)
2199 # Wait for the interpreter to be completely initialized before
2200 # sending any signal.
2201 p.stdout.read(1)
2202 # The process should end after this
2203 time.sleep(1)
2204 # This shouldn't raise even though the child is now dead
2205 getattr(p, method)(*args)
2206 p.communicate()
2207
Florent Xicluna4886d242010-03-08 13:27:26 +00002208 def test_send_signal(self):
2209 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002210 _, stderr = p.communicate()
2211 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002212 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002213
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002214 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002215 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002216 _, stderr = p.communicate()
2217 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002218 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002219
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002220 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002221 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002222 _, stderr = p.communicate()
2223 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002224 self.assertEqual(p.wait(), -signal.SIGTERM)
2225
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002226 def test_send_signal_dead(self):
2227 # Sending a signal to a dead process
2228 self._kill_dead_process('send_signal', signal.SIGINT)
2229
2230 def test_kill_dead(self):
2231 # Killing a dead process
2232 self._kill_dead_process('kill')
2233
2234 def test_terminate_dead(self):
2235 # Terminating a dead process
2236 self._kill_dead_process('terminate')
2237
Victor Stinnerdaf45552013-08-28 00:53:59 +02002238 def _save_fds(self, save_fds):
2239 fds = []
2240 for fd in save_fds:
2241 inheritable = os.get_inheritable(fd)
2242 saved = os.dup(fd)
2243 fds.append((fd, saved, inheritable))
2244 return fds
2245
2246 def _restore_fds(self, fds):
2247 for fd, saved, inheritable in fds:
2248 os.dup2(saved, fd, inheritable=inheritable)
2249 os.close(saved)
2250
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002251 def check_close_std_fds(self, fds):
2252 # Issue #9905: test that subprocess pipes still work properly with
2253 # some standard fds closed
2254 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002255 saved_fds = self._save_fds(fds)
2256 for fd, saved, inheritable in saved_fds:
2257 if fd == 0:
2258 stdin = saved
2259 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002260 try:
2261 for fd in fds:
2262 os.close(fd)
2263 out, err = subprocess.Popen([sys.executable, "-c",
2264 'import sys;'
2265 'sys.stdout.write("apple");'
2266 'sys.stdout.flush();'
2267 'sys.stderr.write("orange")'],
2268 stdin=stdin,
2269 stdout=subprocess.PIPE,
2270 stderr=subprocess.PIPE).communicate()
2271 err = support.strip_python_stderr(err)
2272 self.assertEqual((out, err), (b'apple', b'orange'))
2273 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002274 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002275
2276 def test_close_fd_0(self):
2277 self.check_close_std_fds([0])
2278
2279 def test_close_fd_1(self):
2280 self.check_close_std_fds([1])
2281
2282 def test_close_fd_2(self):
2283 self.check_close_std_fds([2])
2284
2285 def test_close_fds_0_1(self):
2286 self.check_close_std_fds([0, 1])
2287
2288 def test_close_fds_0_2(self):
2289 self.check_close_std_fds([0, 2])
2290
2291 def test_close_fds_1_2(self):
2292 self.check_close_std_fds([1, 2])
2293
2294 def test_close_fds_0_1_2(self):
2295 # Issue #10806: test that subprocess pipes still work properly with
2296 # all standard fds closed.
2297 self.check_close_std_fds([0, 1, 2])
2298
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002299 def test_small_errpipe_write_fd(self):
2300 """Issue #15798: Popen should work when stdio fds are available."""
2301 new_stdin = os.dup(0)
2302 new_stdout = os.dup(1)
2303 try:
2304 os.close(0)
2305 os.close(1)
2306
2307 # Side test: if errpipe_write fails to have its CLOEXEC
2308 # flag set this should cause the parent to think the exec
2309 # failed. Extremely unlikely: everyone supports CLOEXEC.
2310 subprocess.Popen([
2311 sys.executable, "-c",
2312 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2313 finally:
2314 # Restore original stdin and stdout
2315 os.dup2(new_stdin, 0)
2316 os.dup2(new_stdout, 1)
2317 os.close(new_stdin)
2318 os.close(new_stdout)
2319
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002320 def test_remapping_std_fds(self):
2321 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002322 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002323 try:
2324 temp_fds = [fd for fd, fname in temps]
2325
2326 # unlink the files -- we won't need to reopen them
2327 for fd, fname in temps:
2328 os.unlink(fname)
2329
2330 # write some data to what will become stdin, and rewind
2331 os.write(temp_fds[1], b"STDIN")
2332 os.lseek(temp_fds[1], 0, 0)
2333
2334 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002335 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002336 try:
2337 # duplicate the file objects over the standard fd's
2338 for fd, temp_fd in enumerate(temp_fds):
2339 os.dup2(temp_fd, fd)
2340
2341 # now use those files in the "wrong" order, so that subprocess
2342 # has to rearrange them in the child
2343 p = subprocess.Popen([sys.executable, "-c",
2344 'import sys; got = sys.stdin.read();'
2345 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2346 stdin=temp_fds[1],
2347 stdout=temp_fds[2],
2348 stderr=temp_fds[0])
2349 p.wait()
2350 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002351 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002352
2353 for fd in temp_fds:
2354 os.lseek(fd, 0, 0)
2355
2356 out = os.read(temp_fds[2], 1024)
2357 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2358 self.assertEqual(out, b"got STDIN")
2359 self.assertEqual(err, b"err")
2360
2361 finally:
2362 for fd in temp_fds:
2363 os.close(fd)
2364
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002365 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2366 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002367 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002368 temp_fds = [fd for fd, fname in temps]
2369 try:
2370 # unlink the files -- we won't need to reopen them
2371 for fd, fname in temps:
2372 os.unlink(fname)
2373
2374 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002375 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002376 try:
2377 # duplicate the temp files over the standard fd's 0, 1, 2
2378 for fd, temp_fd in enumerate(temp_fds):
2379 os.dup2(temp_fd, fd)
2380
2381 # write some data to what will become stdin, and rewind
2382 os.write(stdin_no, b"STDIN")
2383 os.lseek(stdin_no, 0, 0)
2384
2385 # now use those files in the given order, so that subprocess
2386 # has to rearrange them in the child
2387 p = subprocess.Popen([sys.executable, "-c",
2388 'import sys; got = sys.stdin.read();'
2389 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2390 stdin=stdin_no,
2391 stdout=stdout_no,
2392 stderr=stderr_no)
2393 p.wait()
2394
2395 for fd in temp_fds:
2396 os.lseek(fd, 0, 0)
2397
2398 out = os.read(stdout_no, 1024)
2399 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2400 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002401 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002402
2403 self.assertEqual(out, b"got STDIN")
2404 self.assertEqual(err, b"err")
2405
2406 finally:
2407 for fd in temp_fds:
2408 os.close(fd)
2409
2410 # When duping fds, if there arises a situation where one of the fds is
2411 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2412 # This tests all combinations of this.
2413 def test_swap_fds(self):
2414 self.check_swap_fds(0, 1, 2)
2415 self.check_swap_fds(0, 2, 1)
2416 self.check_swap_fds(1, 0, 2)
2417 self.check_swap_fds(1, 2, 0)
2418 self.check_swap_fds(2, 0, 1)
2419 self.check_swap_fds(2, 1, 0)
2420
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002421 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2422 saved_fds = self._save_fds(range(3))
2423 try:
2424 for from_fd in from_fds:
2425 with tempfile.TemporaryFile() as f:
2426 os.dup2(f.fileno(), from_fd)
2427
2428 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2429 os.close(fd_to_close)
2430
2431 arg_names = ['stdin', 'stdout', 'stderr']
2432 kwargs = {}
2433 for from_fd, to_fd in zip(from_fds, to_fds):
2434 kwargs[arg_names[to_fd]] = from_fd
2435
2436 code = textwrap.dedent(r'''
2437 import os, sys
2438 skipped_fd = int(sys.argv[1])
2439 for fd in range(3):
2440 if fd != skipped_fd:
2441 os.write(fd, str(fd).encode('ascii'))
2442 ''')
2443
2444 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2445
2446 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2447 **kwargs)
2448 self.assertEqual(rc, 0)
2449
2450 for from_fd, to_fd in zip(from_fds, to_fds):
2451 os.lseek(from_fd, 0, os.SEEK_SET)
2452 read_bytes = os.read(from_fd, 1024)
2453 read_fds = list(map(int, read_bytes.decode('ascii')))
2454 msg = textwrap.dedent(f"""
2455 When testing {from_fds} to {to_fds} redirection,
2456 parent descriptor {from_fd} got redirected
2457 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2458 """)
2459 self.assertEqual([to_fd], read_fds, msg)
2460 finally:
2461 self._restore_fds(saved_fds)
2462
2463 # Check that subprocess can remap std fds correctly even
2464 # if one of them is closed (#32844).
2465 def test_swap_std_fds_with_one_closed(self):
2466 for from_fds in itertools.combinations(range(3), 2):
2467 for to_fds in itertools.permutations(range(3), 2):
2468 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2469
Victor Stinner13bb71c2010-04-23 21:41:56 +00002470 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002471 def prepare():
2472 raise ValueError("surrogate:\uDCff")
2473
2474 try:
2475 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002476 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002477 preexec_fn=prepare)
2478 except ValueError as err:
2479 # Pure Python implementations keeps the message
2480 self.assertIsNone(subprocess._posixsubprocess)
2481 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002482 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002483 # _posixsubprocess uses a default message
2484 self.assertIsNotNone(subprocess._posixsubprocess)
2485 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2486 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002487 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002488
Victor Stinner13bb71c2010-04-23 21:41:56 +00002489 def test_undecodable_env(self):
2490 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002491 encoded_value = value.encode("ascii", "surrogateescape")
2492
Victor Stinner13bb71c2010-04-23 21:41:56 +00002493 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002494 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002495 env = os.environ.copy()
2496 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002497 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002498 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002499 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002500 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002501 stdout = subprocess.check_output(
2502 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002503 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002504 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002505 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002506
2507 # test bytes
2508 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002509 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002510 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002511 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002512 stdout = subprocess.check_output(
2513 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002514 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002515 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002516 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002517
Victor Stinnerb745a742010-05-18 17:17:23 +00002518 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002519 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2520 args = list(ZERO_RETURN_CMD[1:])
2521 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002522 program = os.fsencode(program)
2523
2524 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002525 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002526 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002527
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002528 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002529 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002530 exitcode = subprocess.call(cmd, shell=True)
2531 self.assertEqual(exitcode, 0)
2532
Victor Stinnerb745a742010-05-18 17:17:23 +00002533 # bytes program, unicode PATH
2534 env = os.environ.copy()
2535 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002536 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002537 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002538
2539 # bytes program, bytes PATH
2540 envb = os.environb.copy()
2541 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002542 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002543 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002544
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002545 def test_pipe_cloexec(self):
2546 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2547 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2548
2549 p1 = subprocess.Popen([sys.executable, sleeper],
2550 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2551 stderr=subprocess.PIPE, close_fds=False)
2552
2553 self.addCleanup(p1.communicate, b'')
2554
2555 p2 = subprocess.Popen([sys.executable, fd_status],
2556 stdout=subprocess.PIPE, close_fds=False)
2557
2558 output, error = p2.communicate()
2559 result_fds = set(map(int, output.split(b',')))
2560 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2561 p1.stderr.fileno()])
2562
2563 self.assertFalse(result_fds & unwanted_fds,
2564 "Expected no fds from %r to be open in child, "
2565 "found %r" %
2566 (unwanted_fds, result_fds & unwanted_fds))
2567
2568 def test_pipe_cloexec_real_tools(self):
2569 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2570 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2571
2572 subdata = b'zxcvbn'
2573 data = subdata * 4 + b'\n'
2574
2575 p1 = subprocess.Popen([sys.executable, qcat],
2576 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2577 close_fds=False)
2578
2579 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2580 stdin=p1.stdout, stdout=subprocess.PIPE,
2581 close_fds=False)
2582
2583 self.addCleanup(p1.wait)
2584 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002585 def kill_p1():
2586 try:
2587 p1.terminate()
2588 except ProcessLookupError:
2589 pass
2590 def kill_p2():
2591 try:
2592 p2.terminate()
2593 except ProcessLookupError:
2594 pass
2595 self.addCleanup(kill_p1)
2596 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002597
2598 p1.stdin.write(data)
2599 p1.stdin.close()
2600
2601 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2602
2603 self.assertTrue(readfiles, "The child hung")
2604 self.assertEqual(p2.stdout.read(), data)
2605
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002606 p1.stdout.close()
2607 p2.stdout.close()
2608
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002609 def test_close_fds(self):
2610 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2611
2612 fds = os.pipe()
2613 self.addCleanup(os.close, fds[0])
2614 self.addCleanup(os.close, fds[1])
2615
2616 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002617 # add a bunch more fds
2618 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002619 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002620 self.addCleanup(os.close, fd)
2621 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002622
Victor Stinnerdaf45552013-08-28 00:53:59 +02002623 for fd in open_fds:
2624 os.set_inheritable(fd, True)
2625
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002626 p = subprocess.Popen([sys.executable, fd_status],
2627 stdout=subprocess.PIPE, close_fds=False)
2628 output, ignored = p.communicate()
2629 remaining_fds = set(map(int, output.split(b',')))
2630
2631 self.assertEqual(remaining_fds & open_fds, open_fds,
2632 "Some fds were closed")
2633
2634 p = subprocess.Popen([sys.executable, fd_status],
2635 stdout=subprocess.PIPE, close_fds=True)
2636 output, ignored = p.communicate()
2637 remaining_fds = set(map(int, output.split(b',')))
2638
2639 self.assertFalse(remaining_fds & open_fds,
2640 "Some fds were left open")
2641 self.assertIn(1, remaining_fds, "Subprocess failed")
2642
Gregory P. Smith8facece2012-01-21 14:01:08 -08002643 # Keep some of the fd's we opened open in the subprocess.
2644 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2645 fds_to_keep = set(open_fds.pop() for _ in range(8))
2646 p = subprocess.Popen([sys.executable, fd_status],
2647 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002648 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002649 output, ignored = p.communicate()
2650 remaining_fds = set(map(int, output.split(b',')))
2651
izbyshev2d8f0632017-12-19 03:26:49 +07002652 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002653 "Some fds not in pass_fds were left open")
2654 self.assertIn(1, remaining_fds, "Subprocess failed")
2655
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002656
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002657 @unittest.skipIf(sys.platform.startswith("freebsd") and
2658 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2659 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002660 def test_close_fds_when_max_fd_is_lowered(self):
2661 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2662 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2663
Gregory P. Smith634aa682014-06-15 17:51:04 -07002664 # This launches the meat of the test in a child process to
2665 # avoid messing with the larger unittest processes maximum
2666 # number of file descriptors.
2667 # This process launches:
2668 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2669 # a bunch of high open fds above the new lower rlimit.
2670 # Those are reported via stdout before launching a new
2671 # process with close_fds=False to run the actual test:
2672 # +--> The TEST: This one launches a fd_status.py
2673 # subprocess with close_fds=True so we can find out if
2674 # any of the fds above the lowered rlimit are still open.
2675 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2676 '''
2677 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002678 open_fds = set()
2679 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002680 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002681 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002682 open_fds.add(fd)
2683
2684 # Leave a two pairs of low ones available for use by the
2685 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002686 # We also leave 10 more open as some Python buildbots run into
2687 # "too many open files" errors during the test if we do not.
2688 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002689 os.close(fd)
2690 open_fds.remove(fd)
2691
2692 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002693 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002694 os.set_inheritable(fd, True)
2695
2696 max_fd_open = max(open_fds)
2697
Gregory P. Smith634aa682014-06-15 17:51:04 -07002698 # Communicate the open_fds to the parent unittest.TestCase process.
2699 print(','.join(map(str, sorted(open_fds))))
2700 sys.stdout.flush()
2701
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002702 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2703 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002704 # 29 is lower than the highest fds we are leaving open.
2705 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002706 # Launch a new Python interpreter with our low fd rlim_cur that
2707 # inherits open fds above that limit. It then uses subprocess
2708 # with close_fds=True to get a report of open fds in the child.
2709 # An explicit list of fds to check is passed to fd_status.py as
2710 # letting fd_status rely on its default logic would miss the
2711 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002712 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002713 [sys.executable, '-c',
2714 textwrap.dedent("""
2715 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002716 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002717 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002718 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002719 """.format(max_fd=max_fd_open+1))],
2720 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002721 finally:
2722 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002723 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002724
2725 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002726 output_lines = output.splitlines()
2727 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002728 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002729 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2730 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002731
Gregory P. Smith634aa682014-06-15 17:51:04 -07002732 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002733 msg="Some fds were left open.")
2734
2735
Victor Stinner88701e22011-06-01 13:13:04 +02002736 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2737 # descriptor of a pipe closed in the parent process is valid in the
2738 # child process according to fstat(), but the mode of the file
2739 # descriptor is invalid, and read or write raise an error.
2740 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002741 def test_pass_fds(self):
2742 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2743
2744 open_fds = set()
2745
2746 for x in range(5):
2747 fds = os.pipe()
2748 self.addCleanup(os.close, fds[0])
2749 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002750 os.set_inheritable(fds[0], True)
2751 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002752 open_fds.update(fds)
2753
2754 for fd in open_fds:
2755 p = subprocess.Popen([sys.executable, fd_status],
2756 stdout=subprocess.PIPE, close_fds=True,
2757 pass_fds=(fd, ))
2758 output, ignored = p.communicate()
2759
2760 remaining_fds = set(map(int, output.split(b',')))
2761 to_be_closed = open_fds - {fd}
2762
2763 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2764 self.assertFalse(remaining_fds & to_be_closed,
2765 "fd to be closed passed")
2766
2767 # pass_fds overrides close_fds with a warning.
2768 with self.assertWarns(RuntimeWarning) as context:
2769 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002770 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002771 close_fds=False, pass_fds=(fd, )))
2772 self.assertIn('overriding close_fds', str(context.warning))
2773
Victor Stinnerdaf45552013-08-28 00:53:59 +02002774 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002775 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002776
2777 inheritable, non_inheritable = os.pipe()
2778 self.addCleanup(os.close, inheritable)
2779 self.addCleanup(os.close, non_inheritable)
2780 os.set_inheritable(inheritable, True)
2781 os.set_inheritable(non_inheritable, False)
2782 pass_fds = (inheritable, non_inheritable)
2783 args = [sys.executable, script]
2784 args += list(map(str, pass_fds))
2785
2786 p = subprocess.Popen(args,
2787 stdout=subprocess.PIPE, close_fds=True,
2788 pass_fds=pass_fds)
2789 output, ignored = p.communicate()
2790 fds = set(map(int, output.split(b',')))
2791
2792 # the inheritable file descriptor must be inherited, so its inheritable
2793 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002794 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002795
2796 # inheritable flag must not be changed in the parent process
2797 self.assertEqual(os.get_inheritable(inheritable), True)
2798 self.assertEqual(os.get_inheritable(non_inheritable), False)
2799
Gregory P. Smithce344102018-09-10 17:46:22 -07002800
2801 # bpo-32270: Ensure that descriptors specified in pass_fds
2802 # are inherited even if they are used in redirections.
2803 # Contributed by @izbyshev.
2804 def test_pass_fds_redirected(self):
2805 """Regression test for https://bugs.python.org/issue32270."""
2806 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2807 pass_fds = []
2808 for _ in range(2):
2809 fd = os.open(os.devnull, os.O_RDWR)
2810 self.addCleanup(os.close, fd)
2811 pass_fds.append(fd)
2812
2813 stdout_r, stdout_w = os.pipe()
2814 self.addCleanup(os.close, stdout_r)
2815 self.addCleanup(os.close, stdout_w)
2816 pass_fds.insert(1, stdout_w)
2817
2818 with subprocess.Popen([sys.executable, fd_status],
2819 stdin=pass_fds[0],
2820 stdout=pass_fds[1],
2821 stderr=pass_fds[2],
2822 close_fds=True,
2823 pass_fds=pass_fds):
2824 output = os.read(stdout_r, 1024)
2825 fds = {int(num) for num in output.split(b',')}
2826
2827 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2828
2829
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002830 def test_stdout_stdin_are_single_inout_fd(self):
2831 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002832 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002833 stdout=inout, stdin=inout)
2834 p.wait()
2835
2836 def test_stdout_stderr_are_single_inout_fd(self):
2837 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002838 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002839 stdout=inout, stderr=inout)
2840 p.wait()
2841
2842 def test_stderr_stdin_are_single_inout_fd(self):
2843 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002844 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002845 stderr=inout, stdin=inout)
2846 p.wait()
2847
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002848 def test_wait_when_sigchild_ignored(self):
2849 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2850 sigchild_ignore = support.findfile("sigchild_ignore.py",
2851 subdir="subprocessdata")
2852 p = subprocess.Popen([sys.executable, sigchild_ignore],
2853 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2854 stdout, stderr = p.communicate()
2855 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002856 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002857 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002858
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002859 def test_select_unbuffered(self):
2860 # Issue #11459: bufsize=0 should really set the pipes as
2861 # unbuffered (and therefore let select() work properly).
2862 select = support.import_module("select")
2863 p = subprocess.Popen([sys.executable, "-c",
2864 'import sys;'
2865 'sys.stdout.write("apple")'],
2866 stdout=subprocess.PIPE,
2867 bufsize=0)
2868 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002869 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002870 try:
2871 self.assertEqual(f.read(4), b"appl")
2872 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2873 finally:
2874 p.wait()
2875
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002876 def test_zombie_fast_process_del(self):
2877 # Issue #12650: on Unix, if Popen.__del__() was called before the
2878 # process exited, it wouldn't be added to subprocess._active, and would
2879 # remain a zombie.
2880 # spawn a Popen, and delete its reference before it exits
2881 p = subprocess.Popen([sys.executable, "-c",
2882 'import sys, time;'
2883 'time.sleep(0.2)'],
2884 stdout=subprocess.PIPE,
2885 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002886 self.addCleanup(p.stdout.close)
2887 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002888 ident = id(p)
2889 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002890 with support.check_warnings(('', ResourceWarning)):
2891 p = None
2892
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002893 if mswindows:
2894 # subprocess._active is not used on Windows and is set to None.
2895 self.assertIsNone(subprocess._active)
2896 else:
2897 # check that p is in the active processes list
2898 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002899
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002900 def test_leak_fast_process_del_killed(self):
2901 # Issue #12650: on Unix, if Popen.__del__() was called before the
2902 # process exited, and the process got killed by a signal, it would never
2903 # be removed from subprocess._active, which triggered a FD and memory
2904 # leak.
2905 # spawn a Popen, delete its reference and kill it
2906 p = subprocess.Popen([sys.executable, "-c",
2907 'import time;'
2908 'time.sleep(3)'],
2909 stdout=subprocess.PIPE,
2910 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002911 self.addCleanup(p.stdout.close)
2912 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002913 ident = id(p)
2914 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002915 with support.check_warnings(('', ResourceWarning)):
2916 p = None
2917
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002918 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002919 if mswindows:
2920 # subprocess._active is not used on Windows and is set to None.
2921 self.assertIsNone(subprocess._active)
2922 else:
2923 # check that p is in the active processes list
2924 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002925
2926 # let some time for the process to exit, and create a new Popen: this
2927 # should trigger the wait() of p
2928 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002929 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002930 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002931 stdout=subprocess.PIPE,
2932 stderr=subprocess.PIPE) as proc:
2933 pass
2934 # p should have been wait()ed on, and removed from the _active list
2935 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002936 if mswindows:
2937 # subprocess._active is not used on Windows and is set to None.
2938 self.assertIsNone(subprocess._active)
2939 else:
2940 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002941
Charles-François Natali249cdc32013-08-25 18:24:45 +02002942 def test_close_fds_after_preexec(self):
2943 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2944
2945 # this FD is used as dup2() target by preexec_fn, and should be closed
2946 # in the child process
2947 fd = os.dup(1)
2948 self.addCleanup(os.close, fd)
2949
2950 p = subprocess.Popen([sys.executable, fd_status],
2951 stdout=subprocess.PIPE, close_fds=True,
2952 preexec_fn=lambda: os.dup2(1, fd))
2953 output, ignored = p.communicate()
2954
2955 remaining_fds = set(map(int, output.split(b',')))
2956
2957 self.assertNotIn(fd, remaining_fds)
2958
Victor Stinner8f437aa2014-10-05 17:25:19 +02002959 @support.cpython_only
2960 def test_fork_exec(self):
2961 # Issue #22290: fork_exec() must not crash on memory allocation failure
2962 # or other errors
2963 import _posixsubprocess
2964 gc_enabled = gc.isenabled()
2965 try:
2966 # Use a preexec function and enable the garbage collector
2967 # to force fork_exec() to re-enable the garbage collector
2968 # on error.
2969 func = lambda: None
2970 gc.enable()
2971
Victor Stinner8f437aa2014-10-05 17:25:19 +02002972 for args, exe_list, cwd, env_list in (
2973 (123, [b"exe"], None, [b"env"]),
2974 ([b"arg"], 123, None, [b"env"]),
2975 ([b"arg"], [b"exe"], 123, [b"env"]),
2976 ([b"arg"], [b"exe"], None, 123),
2977 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07002978 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02002979 _posixsubprocess.fork_exec(
2980 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002981 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002982 -1, -1, -1, -1,
2983 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07002984 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07002985 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07002986 func)
2987 # Attempt to prevent
2988 # "TypeError: fork_exec() takes exactly N arguments (M given)"
2989 # from passing the test. More refactoring to have us start
2990 # with a valid *args list, confirm a good call with that works
2991 # before mutating it in various ways to ensure that bad calls
2992 # with individual arg type errors raise a typeerror would be
2993 # ideal. Saving that for a future PR...
2994 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02002995 finally:
2996 if not gc_enabled:
2997 gc.disable()
2998
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002999 @support.cpython_only
3000 def test_fork_exec_sorted_fd_sanity_check(self):
3001 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3002 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003003 class BadInt:
3004 first = True
3005 def __init__(self, value):
3006 self.value = value
3007 def __int__(self):
3008 if self.first:
3009 self.first = False
3010 return self.value
3011 raise ValueError
3012
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003013 gc_enabled = gc.isenabled()
3014 try:
3015 gc.enable()
3016
3017 for fds_to_keep in (
3018 (-1, 2, 3, 4, 5), # Negative number.
3019 ('str', 4), # Not an int.
3020 (18, 23, 42, 2**63), # Out of range.
3021 (5, 4), # Not sorted.
3022 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003023 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003024 ):
3025 with self.assertRaises(
3026 ValueError,
3027 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3028 _posixsubprocess.fork_exec(
3029 [b"false"], [b"false"],
3030 True, fds_to_keep, None, [b"env"],
3031 -1, -1, -1, -1,
3032 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003033 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003034 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003035 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003036 self.assertIn('fds_to_keep', str(c.exception))
3037 finally:
3038 if not gc_enabled:
3039 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003040
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003041 def test_communicate_BrokenPipeError_stdin_close(self):
3042 # By not setting stdout or stderr or a timeout we force the fast path
3043 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003044 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003045 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3046 mock_proc_stdin.close.side_effect = BrokenPipeError
3047 proc.communicate() # Should swallow BrokenPipeError from close.
3048 mock_proc_stdin.close.assert_called_with()
3049
3050 def test_communicate_BrokenPipeError_stdin_write(self):
3051 # By not setting stdout or stderr or a timeout we force the fast path
3052 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003053 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003054 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3055 mock_proc_stdin.write.side_effect = BrokenPipeError
3056 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3057 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3058 mock_proc_stdin.close.assert_called_once_with()
3059
3060 def test_communicate_BrokenPipeError_stdin_flush(self):
3061 # Setting stdin and stdout forces the ._communicate() code path.
3062 # python -h exits faster than python -c pass (but spams stdout).
3063 proc = subprocess.Popen([sys.executable, '-h'],
3064 stdin=subprocess.PIPE,
3065 stdout=subprocess.PIPE)
3066 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3067 open(os.devnull, 'wb') as dev_null:
3068 mock_proc_stdin.flush.side_effect = BrokenPipeError
3069 # because _communicate registers a selector using proc.stdin...
3070 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3071 # _communicate() should swallow BrokenPipeError from flush.
3072 proc.communicate(b'stuff')
3073 mock_proc_stdin.flush.assert_called_once_with()
3074
3075 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3076 # Setting stdin and stdout forces the ._communicate() code path.
3077 # python -h exits faster than python -c pass (but spams stdout).
3078 proc = subprocess.Popen([sys.executable, '-h'],
3079 stdin=subprocess.PIPE,
3080 stdout=subprocess.PIPE)
3081 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3082 mock_proc_stdin.close.side_effect = BrokenPipeError
3083 # _communicate() should swallow BrokenPipeError from close.
3084 proc.communicate(timeout=999)
3085 mock_proc_stdin.close.assert_called_once_with()
3086
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003087 @unittest.skipUnless(_testcapi is not None
3088 and hasattr(_testcapi, 'W_STOPCODE'),
3089 'need _testcapi.W_STOPCODE')
3090 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003091 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003092 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003093 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003094
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003095 # Wait until the real process completes to avoid zombie process
3096 pid = proc.pid
3097 pid, status = os.waitpid(pid, 0)
3098 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003099
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003100 status = _testcapi.W_STOPCODE(3)
3101 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
3102 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003103
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003104 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003105
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003106
Victor Stinner937ee9e2018-06-26 02:11:06 +02003107@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003108class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003109
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003110 def test_startupinfo(self):
3111 # startupinfo argument
3112 # We uses hardcoded constants, because we do not want to
3113 # depend on win32all.
3114 STARTF_USESHOWWINDOW = 1
3115 SW_MAXIMIZE = 3
3116 startupinfo = subprocess.STARTUPINFO()
3117 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3118 startupinfo.wShowWindow = SW_MAXIMIZE
3119 # Since Python is a console process, it won't be affected
3120 # by wShowWindow, but the argument should be silently
3121 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003122 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003123 startupinfo=startupinfo)
3124
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303125 def test_startupinfo_keywords(self):
3126 # startupinfo argument
3127 # We use hardcoded constants, because we do not want to
3128 # depend on win32all.
3129 STARTF_USERSHOWWINDOW = 1
3130 SW_MAXIMIZE = 3
3131 startupinfo = subprocess.STARTUPINFO(
3132 dwFlags=STARTF_USERSHOWWINDOW,
3133 wShowWindow=SW_MAXIMIZE
3134 )
3135 # Since Python is a console process, it won't be affected
3136 # by wShowWindow, but the argument should be silently
3137 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003138 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303139 startupinfo=startupinfo)
3140
Victor Stinner483422f2018-07-05 22:54:17 +02003141 def test_startupinfo_copy(self):
3142 # bpo-34044: Popen must not modify input STARTUPINFO structure
3143 startupinfo = subprocess.STARTUPINFO()
3144 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3145 startupinfo.wShowWindow = subprocess.SW_HIDE
3146
3147 # Call Popen() twice with the same startupinfo object to make sure
3148 # that it's not modified
3149 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003150 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003151 with open(os.devnull, 'w') as null:
3152 proc = subprocess.Popen(cmd,
3153 stdout=null,
3154 stderr=subprocess.STDOUT,
3155 startupinfo=startupinfo)
3156 with proc:
3157 proc.communicate()
3158 self.assertEqual(proc.returncode, 0)
3159
3160 self.assertEqual(startupinfo.dwFlags,
3161 subprocess.STARTF_USESHOWWINDOW)
3162 self.assertIsNone(startupinfo.hStdInput)
3163 self.assertIsNone(startupinfo.hStdOutput)
3164 self.assertIsNone(startupinfo.hStdError)
3165 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3166 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3167
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003168 def test_creationflags(self):
3169 # creationflags argument
3170 CREATE_NEW_CONSOLE = 16
3171 sys.stderr.write(" a DOS box should flash briefly ...\n")
3172 subprocess.call(sys.executable +
3173 ' -c "import time; time.sleep(0.25)"',
3174 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003175
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003176 def test_invalid_args(self):
3177 # invalid arguments should raise ValueError
3178 self.assertRaises(ValueError, subprocess.call,
3179 [sys.executable, "-c",
3180 "import sys; sys.exit(47)"],
3181 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003182
Oren Milman0b3a87e2017-09-14 22:30:28 +03003183 @support.cpython_only
3184 def test_issue31471(self):
3185 # There shouldn't be an assertion failure in Popen() in case the env
3186 # argument has a bad keys() method.
3187 class BadEnv(dict):
3188 keys = None
3189 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003190 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003191
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003192 def test_close_fds(self):
3193 # close file descriptors
3194 rc = subprocess.call([sys.executable, "-c",
3195 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003196 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003197 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003198
Segev Finerb2a60832017-12-18 11:28:19 +02003199 def test_close_fds_with_stdio(self):
3200 import msvcrt
3201
3202 fds = os.pipe()
3203 self.addCleanup(os.close, fds[0])
3204 self.addCleanup(os.close, fds[1])
3205
3206 handles = []
3207 for fd in fds:
3208 os.set_inheritable(fd, True)
3209 handles.append(msvcrt.get_osfhandle(fd))
3210
3211 p = subprocess.Popen([sys.executable, "-c",
3212 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3213 stdout=subprocess.PIPE, close_fds=False)
3214 stdout, stderr = p.communicate()
3215 self.assertEqual(p.returncode, 0)
3216 int(stdout.strip()) # Check that stdout is an integer
3217
3218 p = subprocess.Popen([sys.executable, "-c",
3219 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3220 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3221 stdout, stderr = p.communicate()
3222 self.assertEqual(p.returncode, 1)
3223 self.assertIn(b"OSError", stderr)
3224
3225 # The same as the previous call, but with an empty handle_list
3226 handle_list = []
3227 startupinfo = subprocess.STARTUPINFO()
3228 startupinfo.lpAttributeList = {"handle_list": handle_list}
3229 p = subprocess.Popen([sys.executable, "-c",
3230 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3231 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3232 startupinfo=startupinfo, close_fds=True)
3233 stdout, stderr = p.communicate()
3234 self.assertEqual(p.returncode, 1)
3235 self.assertIn(b"OSError", stderr)
3236
3237 # Check for a warning due to using handle_list and close_fds=False
3238 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3239 startupinfo = subprocess.STARTUPINFO()
3240 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3241 p = subprocess.Popen([sys.executable, "-c",
3242 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3243 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3244 startupinfo=startupinfo, close_fds=False)
3245 stdout, stderr = p.communicate()
3246 self.assertEqual(p.returncode, 0)
3247
3248 def test_empty_attribute_list(self):
3249 startupinfo = subprocess.STARTUPINFO()
3250 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003251 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003252 startupinfo=startupinfo)
3253
3254 def test_empty_handle_list(self):
3255 startupinfo = subprocess.STARTUPINFO()
3256 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003257 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003258 startupinfo=startupinfo)
3259
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003260 def test_shell_sequence(self):
3261 # Run command through the shell (sequence)
3262 newenv = os.environ.copy()
3263 newenv["FRUIT"] = "physalis"
3264 p = subprocess.Popen(["set"], shell=1,
3265 stdout=subprocess.PIPE,
3266 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003267 with p:
3268 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003269
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003270 def test_shell_string(self):
3271 # Run command through the shell (string)
3272 newenv = os.environ.copy()
3273 newenv["FRUIT"] = "physalis"
3274 p = subprocess.Popen("set", shell=1,
3275 stdout=subprocess.PIPE,
3276 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003277 with p:
3278 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003279
Steve Dower050acae2016-09-06 20:16:17 -07003280 def test_shell_encodings(self):
3281 # Run command through the shell (string)
3282 for enc in ['ansi', 'oem']:
3283 newenv = os.environ.copy()
3284 newenv["FRUIT"] = "physalis"
3285 p = subprocess.Popen("set", shell=1,
3286 stdout=subprocess.PIPE,
3287 env=newenv,
3288 encoding=enc)
3289 with p:
3290 self.assertIn("physalis", p.stdout.read(), enc)
3291
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003292 def test_call_string(self):
3293 # call() function with string argument on Windows
3294 rc = subprocess.call(sys.executable +
3295 ' -c "import sys; sys.exit(47)"')
3296 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003297
Florent Xicluna4886d242010-03-08 13:27:26 +00003298 def _kill_process(self, method, *args):
3299 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003300 p = subprocess.Popen([sys.executable, "-c", """if 1:
3301 import sys, time
3302 sys.stdout.write('x\\n')
3303 sys.stdout.flush()
3304 time.sleep(30)
3305 """],
3306 stdin=subprocess.PIPE,
3307 stdout=subprocess.PIPE,
3308 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003309 with p:
3310 # Wait for the interpreter to be completely initialized before
3311 # sending any signal.
3312 p.stdout.read(1)
3313 getattr(p, method)(*args)
3314 _, stderr = p.communicate()
3315 self.assertStderrEqual(stderr, b'')
3316 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003317 self.assertNotEqual(returncode, 0)
3318
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003319 def _kill_dead_process(self, method, *args):
3320 p = subprocess.Popen([sys.executable, "-c", """if 1:
3321 import sys, time
3322 sys.stdout.write('x\\n')
3323 sys.stdout.flush()
3324 sys.exit(42)
3325 """],
3326 stdin=subprocess.PIPE,
3327 stdout=subprocess.PIPE,
3328 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003329 with p:
3330 # Wait for the interpreter to be completely initialized before
3331 # sending any signal.
3332 p.stdout.read(1)
3333 # The process should end after this
3334 time.sleep(1)
3335 # This shouldn't raise even though the child is now dead
3336 getattr(p, method)(*args)
3337 _, stderr = p.communicate()
3338 self.assertStderrEqual(stderr, b'')
3339 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003340 self.assertEqual(rc, 42)
3341
Florent Xicluna4886d242010-03-08 13:27:26 +00003342 def test_send_signal(self):
3343 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003344
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003345 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003346 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003347
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003348 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003349 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003350
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003351 def test_send_signal_dead(self):
3352 self._kill_dead_process('send_signal', signal.SIGTERM)
3353
3354 def test_kill_dead(self):
3355 self._kill_dead_process('kill')
3356
3357 def test_terminate_dead(self):
3358 self._kill_dead_process('terminate')
3359
Martin Panter23172bd2016-04-16 11:28:10 +00003360class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003361
3362 class RecordingPopen(subprocess.Popen):
3363 """A Popen that saves a reference to each instance for testing."""
3364 instances_created = []
3365
3366 def __init__(self, *args, **kwargs):
3367 super().__init__(*args, **kwargs)
3368 self.instances_created.append(self)
3369
3370 @mock.patch.object(subprocess.Popen, "_communicate")
3371 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3372 **kwargs):
3373 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3374
3375 This avoids the need to actually try and get test environments to send
3376 and receive signals reliably across platforms. The net effect of a ^C
3377 happening during a blocking subprocess execution which we want to clean
3378 up from is a KeyboardInterrupt coming out of communicate() or wait().
3379 """
3380
3381 mock__communicate.side_effect = KeyboardInterrupt
3382 try:
3383 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3384 # We patch out _wait() as no signal was involved so the
3385 # child process isn't actually going to exit rapidly.
3386 mock__wait.side_effect = KeyboardInterrupt
3387 with mock.patch.object(subprocess, "Popen",
3388 self.RecordingPopen):
3389 with self.assertRaises(KeyboardInterrupt):
3390 popener([sys.executable, "-c",
3391 "import time\ntime.sleep(9)\nimport sys\n"
3392 "sys.stderr.write('\\n!runaway child!\\n')"],
3393 stdout=subprocess.DEVNULL, **kwargs)
3394 for call in mock__wait.call_args_list[1:]:
3395 self.assertNotEqual(
3396 call, mock.call(timeout=None),
3397 "no open-ended wait() after the first allowed: "
3398 f"{mock__wait.call_args_list}")
3399 sigint_calls = []
3400 for call in mock__wait.call_args_list:
3401 if call == mock.call(timeout=0.25): # from Popen.__init__
3402 sigint_calls.append(call)
3403 self.assertLessEqual(mock__wait.call_count, 2,
3404 msg=mock__wait.call_args_list)
3405 self.assertEqual(len(sigint_calls), 1,
3406 msg=mock__wait.call_args_list)
3407 finally:
3408 # cleanup the forgotten (due to our mocks) child process
3409 process = self.RecordingPopen.instances_created.pop()
3410 process.kill()
3411 process.wait()
3412 self.assertEqual([], self.RecordingPopen.instances_created)
3413
3414 def test_call_keyboardinterrupt_no_kill(self):
3415 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3416
3417 def test_run_keyboardinterrupt_no_kill(self):
3418 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3419
3420 def test_context_manager_keyboardinterrupt_no_kill(self):
3421 def popen_via_context_manager(*args, **kwargs):
3422 with subprocess.Popen(*args, **kwargs) as unused_process:
3423 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3424 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3425
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003426 def test_getoutput(self):
3427 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3428 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3429 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003430
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003431 # we use mkdtemp in the next line to create an empty directory
3432 # under our exclusive control; from that, we can invent a pathname
3433 # that we _know_ won't exist. This is guaranteed to fail.
3434 dir = None
3435 try:
3436 dir = tempfile.mkdtemp()
3437 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003438 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003439 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003440 self.assertNotEqual(status, 0)
3441 finally:
3442 if dir is not None:
3443 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003444
Gregory P. Smithace55862015-04-07 15:57:54 -07003445 def test__all__(self):
3446 """Ensure that __all__ is populated properly."""
Patrick McLean2b2ead72019-09-12 10:15:44 -07003447 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003448 exported = set(subprocess.__all__)
3449 possible_exports = set()
3450 import types
3451 for name, value in subprocess.__dict__.items():
3452 if name.startswith('_'):
3453 continue
3454 if isinstance(value, (types.ModuleType,)):
3455 continue
3456 possible_exports.add(name)
3457 self.assertEqual(exported, possible_exports - intentionally_excluded)
3458
3459
Martin Panter23172bd2016-04-16 11:28:10 +00003460@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3461 "Test needs selectors.PollSelector")
3462class ProcessTestCaseNoPoll(ProcessTestCase):
3463 def setUp(self):
3464 self.orig_selector = subprocess._PopenSelector
3465 subprocess._PopenSelector = selectors.SelectSelector
3466 ProcessTestCase.setUp(self)
3467
3468 def tearDown(self):
3469 subprocess._PopenSelector = self.orig_selector
3470 ProcessTestCase.tearDown(self)
3471
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003472
Victor Stinner937ee9e2018-06-26 02:11:06 +02003473@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003474class CommandsWithSpaces (BaseTestCase):
3475
3476 def setUp(self):
3477 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003478 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003479 self.fname = fname.lower ()
3480 os.write(f, b"import sys;"
3481 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3482 )
3483 os.close(f)
3484
3485 def tearDown(self):
3486 os.remove(self.fname)
3487 super().tearDown()
3488
3489 def with_spaces(self, *args, **kwargs):
3490 kwargs['stdout'] = subprocess.PIPE
3491 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003492 with p:
3493 self.assertEqual(
3494 p.stdout.read ().decode("mbcs"),
3495 "2 [%r, 'ab cd']" % self.fname
3496 )
Tim Golden126c2962010-08-11 14:20:40 +00003497
3498 def test_shell_string_with_spaces(self):
3499 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003500 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3501 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003502
3503 def test_shell_sequence_with_spaces(self):
3504 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003505 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003506
3507 def test_noshell_string_with_spaces(self):
3508 # call() function with string argument with spaces on Windows
3509 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3510 "ab cd"))
3511
3512 def test_noshell_sequence_with_spaces(self):
3513 # call() function with sequence argument with spaces on Windows
3514 self.with_spaces([sys.executable, self.fname, "ab cd"])
3515
Brian Curtin79cdb662010-12-03 02:46:02 +00003516
Georg Brandla86b2622012-02-20 21:34:57 +01003517class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003518
3519 def test_pipe(self):
3520 with subprocess.Popen([sys.executable, "-c",
3521 "import sys;"
3522 "sys.stdout.write('stdout');"
3523 "sys.stderr.write('stderr');"],
3524 stdout=subprocess.PIPE,
3525 stderr=subprocess.PIPE) as proc:
3526 self.assertEqual(proc.stdout.read(), b"stdout")
3527 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3528
3529 self.assertTrue(proc.stdout.closed)
3530 self.assertTrue(proc.stderr.closed)
3531
3532 def test_returncode(self):
3533 with subprocess.Popen([sys.executable, "-c",
3534 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003535 pass
3536 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003537 self.assertEqual(proc.returncode, 100)
3538
3539 def test_communicate_stdin(self):
3540 with subprocess.Popen([sys.executable, "-c",
3541 "import sys;"
3542 "sys.exit(sys.stdin.read() == 'context')"],
3543 stdin=subprocess.PIPE) as proc:
3544 proc.communicate(b"context")
3545 self.assertEqual(proc.returncode, 1)
3546
3547 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003548 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003549 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003550 stdout=subprocess.PIPE,
3551 stderr=subprocess.PIPE) as proc:
3552 pass
3553
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003554 def test_broken_pipe_cleanup(self):
3555 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003556 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003557 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003558 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003559 proc = proc.__enter__()
3560 # Prepare to send enough data to overflow any OS pipe buffering and
3561 # guarantee a broken pipe error. Data is held in BufferedWriter
3562 # buffer until closed.
3563 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003564 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003565 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003566 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003567 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003568 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003569
Brian Curtin79cdb662010-12-03 02:46:02 +00003570
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003571if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003572 unittest.main()