blob: 0162424e2fd6b690dc63efd1c9a16ebed5a24121 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00002from unittest import mock
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Hai Shi0c4f0f32020-06-30 21:46:31 +08004from test.support import import_helper
5from test.support import os_helper
6from test.support import warnings_helper
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import subprocess
8import sys
9import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -040010import io
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +030011import itertools
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000012import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000013import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000014import tempfile
15import time
Gregory P. Smith580d2782019-09-11 04:23:05 -050016import traceback
Guido van Rossum48b069a2020-04-07 09:50:06 -070017import types
Charles-François Natali3a4586a2013-11-08 19:56:59 +010018import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000019import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000020import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040021import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020022import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050023import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030024import textwrap
Patrick McLean2b2ead72019-09-12 10:15:44 -070025import json
Hai Shi0c4f0f32020-06-30 21:46:31 +080026from test.support.os_helper import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050027
28try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020029 import _testcapi
30except ImportError:
31 _testcapi = None
32
Patrick McLean2b2ead72019-09-12 10:15:44 -070033try:
34 import pwd
35except ImportError:
36 pwd = None
37try:
38 import grp
39except ImportError:
40 grp = None
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020041
Steve Dower22d06982016-09-06 19:38:15 -070042if support.PGO:
43 raise unittest.SkipTest("test is not helpful for PGO")
44
Victor Stinner937ee9e2018-06-26 02:11:06 +020045mswindows = (sys.platform == "win32")
46
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000047#
48# Depends on the following external programs: Python
49#
50
Victor Stinner937ee9e2018-06-26 02:11:06 +020051if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000052 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
53 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000054else:
55 SETBINARY = ''
56
Victor Stinner9a83f652017-08-21 23:51:31 +020057NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010058# Ignore errors that indicate the command was not found
59NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020060
Gregory P. Smith67b93f82019-10-12 16:35:53 -070061ZERO_RETURN_CMD = (sys.executable, '-c', 'pass')
62
63
64def setUpModule():
65 shell_true = shutil.which('true')
Pablo Galindo46113e02019-10-13 02:40:24 +010066 if shell_true is None:
67 return
Gregory P. Smith67b93f82019-10-12 16:35:53 -070068 if (os.access(shell_true, os.X_OK) and
69 subprocess.run([shell_true]).returncode == 0):
70 global ZERO_RETURN_CMD
71 ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup.
72
Florent Xiclunab1e94e82010-02-27 22:12:37 +000073
Florent Xiclunac049d872010-03-27 22:47:23 +000074class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075 def setUp(self):
76 # Try to minimize the number of children we have so this test
77 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000078 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000080 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030081 if not mswindows:
82 # subprocess._active is not used on Windows and is set to None.
83 for inst in subprocess._active:
84 inst.wait()
85 subprocess._cleanup()
86 self.assertFalse(
87 subprocess._active, "subprocess._active not empty"
88 )
Victor Stinnercc42c122017-07-28 18:00:22 +020089 self.doCleanups()
90 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000091
Florent Xiclunac049d872010-03-27 22:47:23 +000092
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080093class PopenTestException(Exception):
94 pass
95
96
97class PopenExecuteChildRaises(subprocess.Popen):
98 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
99 _execute_child fails.
100 """
101 def _execute_child(self, *args, **kwargs):
102 raise PopenTestException("Forced Exception for Test")
103
104
Florent Xiclunac049d872010-03-27 22:47:23 +0000105class ProcessTestCase(BaseTestCase):
106
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700107 def test_io_buffered_by_default(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700108 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700109 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
110 stderr=subprocess.PIPE)
111 try:
112 self.assertIsInstance(p.stdin, io.BufferedIOBase)
113 self.assertIsInstance(p.stdout, io.BufferedIOBase)
114 self.assertIsInstance(p.stderr, io.BufferedIOBase)
115 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700116 p.stdin.close()
117 p.stdout.close()
118 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700119 p.wait()
120
121 def test_io_unbuffered_works(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700122 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700123 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
124 stderr=subprocess.PIPE, bufsize=0)
125 try:
126 self.assertIsInstance(p.stdin, io.RawIOBase)
127 self.assertIsInstance(p.stdout, io.RawIOBase)
128 self.assertIsInstance(p.stderr, io.RawIOBase)
129 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700130 p.stdin.close()
131 p.stdout.close()
132 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700133 p.wait()
134
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000135 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000136 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000137 rc = subprocess.call([sys.executable, "-c",
138 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000139 self.assertEqual(rc, 47)
140
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400141 def test_call_timeout(self):
142 # call() function with timeout argument; we want to test that the child
143 # process gets killed when the timeout expires. If the child isn't
144 # killed, this call will deadlock since subprocess.call waits for the
145 # child.
146 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
147 [sys.executable, "-c", "while True: pass"],
148 timeout=0.1)
149
Peter Astrand454f7672005-01-01 09:36:35 +0000150 def test_check_call_zero(self):
151 # check_call() function with zero return code
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700152 rc = subprocess.check_call(ZERO_RETURN_CMD)
Peter Astrand454f7672005-01-01 09:36:35 +0000153 self.assertEqual(rc, 0)
154
155 def test_check_call_nonzero(self):
156 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000157 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000158 subprocess.check_call([sys.executable, "-c",
159 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000160 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000161
Georg Brandlf9734072008-12-07 15:30:06 +0000162 def test_check_output(self):
163 # check_output() function with zero return code
164 output = subprocess.check_output(
165 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000166 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000167
168 def test_check_output_nonzero(self):
169 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000170 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000171 subprocess.check_output(
172 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000173 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000174
175 def test_check_output_stderr(self):
176 # check_output() function stderr redirected to stdout
177 output = subprocess.check_output(
178 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
179 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000180 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000181
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300182 def test_check_output_stdin_arg(self):
183 # check_output() can be called with stdin set to a file
184 tf = tempfile.TemporaryFile()
185 self.addCleanup(tf.close)
186 tf.write(b'pear')
187 tf.seek(0)
188 output = subprocess.check_output(
189 [sys.executable, "-c",
190 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
191 stdin=tf)
192 self.assertIn(b'PEAR', output)
193
194 def test_check_output_input_arg(self):
195 # check_output() can be called with input set to a string
196 output = subprocess.check_output(
197 [sys.executable, "-c",
198 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
199 input=b'pear')
200 self.assertIn(b'PEAR', output)
201
Georg Brandlf9734072008-12-07 15:30:06 +0000202 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300203 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000204 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000205 output = subprocess.check_output(
206 [sys.executable, "-c", "print('will not be run')"],
207 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000208 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000209 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000210
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300211 def test_check_output_stdin_with_input_arg(self):
212 # check_output() refuses to accept 'stdin' with 'input'
213 tf = tempfile.TemporaryFile()
214 self.addCleanup(tf.close)
215 tf.write(b'pear')
216 tf.seek(0)
217 with self.assertRaises(ValueError) as c:
218 output = subprocess.check_output(
219 [sys.executable, "-c", "print('will not be run')"],
220 stdin=tf, input=b'hare')
221 self.fail("Expected ValueError when stdin and input args supplied.")
222 self.assertIn('stdin', c.exception.args[0])
223 self.assertIn('input', c.exception.args[0])
224
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400225 def test_check_output_timeout(self):
226 # check_output() function with timeout arg
227 with self.assertRaises(subprocess.TimeoutExpired) as c:
228 output = subprocess.check_output(
229 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200230 "import sys, time\n"
231 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400232 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200233 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400234 # Some heavily loaded buildbots (sparc Debian 3.x) require
235 # this much time to start and print.
236 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400237 self.fail("Expected TimeoutExpired.")
238 self.assertEqual(c.exception.output, b'BDFL')
239
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000240 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000241 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 newenv = os.environ.copy()
243 newenv["FRUIT"] = "banana"
244 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000245 'import sys, os;'
246 'sys.exit(os.getenv("FRUIT")=="banana")'],
247 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000248 self.assertEqual(rc, 1)
249
Victor Stinner87b9bc32011-06-01 00:57:47 +0200250 def test_invalid_args(self):
251 # Popen() called with invalid arguments should raise TypeError
252 # but Popen.__del__ should not complain (issue #12085)
253 with support.captured_stderr() as s:
254 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
255 argcount = subprocess.Popen.__init__.__code__.co_argcount
256 too_many_args = [0] * (argcount + 1)
257 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
258 self.assertEqual(s.getvalue(), '')
259
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000260 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000261 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000262 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000264 self.addCleanup(p.stdout.close)
265 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000266 p.wait()
267 self.assertEqual(p.stdin, None)
268
269 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200270 # .stdout is None when not redirected, and the child's stdout will
271 # be inherited from the parent. In order to test this we run a
272 # subprocess in a subprocess:
273 # this_test
274 # \-- subprocess created by this test (parent)
275 # \-- subprocess created by the parent subprocess (child)
276 # The parent doesn't specify stdout, so the child will use the
277 # parent's stdout. This test checks that the message printed by the
278 # child goes to the parent stdout. The parent also checks that the
279 # child's stdout is None. See #11963.
280 code = ('import sys; from subprocess import Popen, PIPE;'
281 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
282 ' stdin=PIPE, stderr=PIPE);'
283 'p.wait(); assert p.stdout is None;')
284 p = subprocess.Popen([sys.executable, "-c", code],
285 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
286 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000287 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200288 out, err = p.communicate()
289 self.assertEqual(p.returncode, 0, err)
290 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291
292 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000293 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000294 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000295 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000296 self.addCleanup(p.stdout.close)
297 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298 p.wait()
299 self.assertEqual(p.stderr, None)
300
Chris Jerdonek776cb192012-10-08 15:56:43 -0700301 def _assert_python(self, pre_args, **kwargs):
302 # We include sys.exit() to prevent the test runner from hanging
303 # whenever python is found.
304 args = pre_args + ["import sys; sys.exit(47)"]
305 p = subprocess.Popen(args, **kwargs)
306 p.wait()
307 self.assertEqual(47, p.returncode)
308
309 def test_executable(self):
310 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700311 #
312 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
313 # determine where its standard library is, so we need the directory
314 # of args[0] to be valid for the Popen() call to Python to succeed.
315 # See also issue #16170 and issue #7774.
316 doesnotexist = os.path.join(os.path.dirname(sys.executable),
317 "doesnotexist")
318 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700319
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300320 def test_bytes_executable(self):
321 doesnotexist = os.path.join(os.path.dirname(sys.executable),
322 "doesnotexist")
323 self._assert_python([doesnotexist, "-c"],
324 executable=os.fsencode(sys.executable))
325
326 def test_pathlike_executable(self):
327 doesnotexist = os.path.join(os.path.dirname(sys.executable),
328 "doesnotexist")
329 self._assert_python([doesnotexist, "-c"],
330 executable=FakePath(sys.executable))
331
Chris Jerdonek776cb192012-10-08 15:56:43 -0700332 def test_executable_takes_precedence(self):
333 # Check that the executable argument takes precedence over args[0].
334 #
335 # Verify first that the call succeeds without the executable arg.
336 pre_args = [sys.executable, "-c"]
337 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100338 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100339 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100340 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700341
Victor Stinner937ee9e2018-06-26 02:11:06 +0200342 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700343 def test_executable_replaces_shell(self):
344 # Check that the executable argument replaces the default shell
345 # when shell=True.
346 self._assert_python([], executable=sys.executable, shell=True)
347
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300348 @unittest.skipIf(mswindows, "executable argument replaces shell")
349 def test_bytes_executable_replaces_shell(self):
350 self._assert_python([], executable=os.fsencode(sys.executable),
351 shell=True)
352
353 @unittest.skipIf(mswindows, "executable argument replaces shell")
354 def test_pathlike_executable_replaces_shell(self):
355 self._assert_python([], executable=FakePath(sys.executable),
356 shell=True)
357
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700358 # For use in the test_cwd* tests below.
359 def _normalize_cwd(self, cwd):
360 # Normalize an expected cwd (for Tru64 support).
361 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
362 # strings. See bug #1063571.
Hai Shi0c4f0f32020-06-30 21:46:31 +0800363 with os_helper.change_cwd(cwd):
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300364 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700365
366 # For use in the test_cwd* tests below.
367 def _split_python_path(self):
368 # Return normalized (python_dir, python_base).
369 python_path = os.path.realpath(sys.executable)
370 return os.path.split(python_path)
371
372 # For use in the test_cwd* tests below.
373 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
374 # Invoke Python via Popen, and assert that (1) the call succeeds,
375 # and that (2) the current working directory of the child process
376 # matches *expected_cwd*.
377 p = subprocess.Popen([python_arg, "-c",
378 "import os, sys; "
379 "sys.stdout.write(os.getcwd()); "
380 "sys.exit(47)"],
381 stdout=subprocess.PIPE,
382 **kwargs)
383 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000384 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700385 self.assertEqual(47, p.returncode)
386 normcase = os.path.normcase
387 self.assertEqual(normcase(expected_cwd),
388 normcase(p.stdout.read().decode("utf-8")))
389
390 def test_cwd(self):
391 # Check that cwd changes the cwd for the child process.
392 temp_dir = tempfile.gettempdir()
393 temp_dir = self._normalize_cwd(temp_dir)
394 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
395
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300396 def test_cwd_with_bytes(self):
397 temp_dir = tempfile.gettempdir()
398 temp_dir = self._normalize_cwd(temp_dir)
399 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
400
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530401 def test_cwd_with_pathlike(self):
402 temp_dir = tempfile.gettempdir()
403 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200404 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530405
Victor Stinner937ee9e2018-06-26 02:11:06 +0200406 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700407 def test_cwd_with_relative_arg(self):
408 # Check that Popen looks for args[0] relative to cwd if args[0]
409 # is relative.
410 python_dir, python_base = self._split_python_path()
411 rel_python = os.path.join(os.curdir, python_base)
Hai Shi0c4f0f32020-06-30 21:46:31 +0800412 with os_helper.temp_cwd() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700413 # Before calling with the correct cwd, confirm that the call fails
414 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700415 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700416 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700417 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700418 [rel_python], cwd=wrong_dir)
419 python_dir = self._normalize_cwd(python_dir)
420 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
421
Victor Stinner937ee9e2018-06-26 02:11:06 +0200422 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700423 def test_cwd_with_relative_executable(self):
424 # Check that Popen looks for executable relative to cwd if executable
425 # is relative (and that executable takes precedence over args[0]).
426 python_dir, python_base = self._split_python_path()
427 rel_python = os.path.join(os.curdir, python_base)
428 doesntexist = "somethingyoudonthave"
Hai Shi0c4f0f32020-06-30 21:46:31 +0800429 with os_helper.temp_cwd() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700430 # Before calling with the correct cwd, confirm that the call fails
431 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700432 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700433 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700434 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700435 [doesntexist], executable=rel_python,
436 cwd=wrong_dir)
437 python_dir = self._normalize_cwd(python_dir)
438 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
439 cwd=python_dir)
440
441 def test_cwd_with_absolute_arg(self):
442 # Check that Popen can find the executable when the cwd is wrong
443 # if args[0] is an absolute path.
444 python_dir, python_base = self._split_python_path()
445 abs_python = os.path.join(python_dir, python_base)
446 rel_python = os.path.join(os.curdir, python_base)
Hai Shi0c4f0f32020-06-30 21:46:31 +0800447 with os_helper.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700448 # Before calling with an absolute path, confirm that using a
449 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700450 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700451 [rel_python], cwd=wrong_dir)
452 wrong_dir = self._normalize_cwd(wrong_dir)
453 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
454
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100455 @unittest.skipIf(sys.base_prefix != sys.prefix,
456 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000457 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700458 python_dir, python_base = self._split_python_path()
459 python_dir = self._normalize_cwd(python_dir)
460 self._assert_cwd(python_dir, "somethingyoudonthave",
461 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000462
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100463 @unittest.skipIf(sys.base_prefix != sys.prefix,
464 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000465 @unittest.skipIf(sysconfig.is_python_build(),
466 "need an installed Python. See #7774")
467 def test_executable_without_cwd(self):
468 # For a normal installation, it should work without 'cwd'
469 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700470 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
471 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000472
473 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000474 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000475 p = subprocess.Popen([sys.executable, "-c",
476 'import sys; sys.exit(sys.stdin.read() == "pear")'],
477 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000478 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479 p.stdin.close()
480 p.wait()
481 self.assertEqual(p.returncode, 1)
482
483 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000484 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000485 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000486 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000487 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000488 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 os.lseek(d, 0, 0)
490 p = subprocess.Popen([sys.executable, "-c",
491 'import sys; sys.exit(sys.stdin.read() == "pear")'],
492 stdin=d)
493 p.wait()
494 self.assertEqual(p.returncode, 1)
495
496 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000497 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000498 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000499 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000500 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501 tf.seek(0)
502 p = subprocess.Popen([sys.executable, "-c",
503 'import sys; sys.exit(sys.stdin.read() == "pear")'],
504 stdin=tf)
505 p.wait()
506 self.assertEqual(p.returncode, 1)
507
508 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000509 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000510 p = subprocess.Popen([sys.executable, "-c",
511 'import sys; sys.stdout.write("orange")'],
512 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200513 with p:
514 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000515
516 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000517 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000518 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000519 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520 d = tf.fileno()
521 p = subprocess.Popen([sys.executable, "-c",
522 'import sys; sys.stdout.write("orange")'],
523 stdout=d)
524 p.wait()
525 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000526 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527
528 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000529 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000530 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000531 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532 p = subprocess.Popen([sys.executable, "-c",
533 'import sys; sys.stdout.write("orange")'],
534 stdout=tf)
535 p.wait()
536 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000537 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000538
539 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000540 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000541 p = subprocess.Popen([sys.executable, "-c",
542 'import sys; sys.stderr.write("strawberry")'],
543 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200544 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100545 self.assertEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546
547 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000548 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000549 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000550 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551 d = tf.fileno()
552 p = subprocess.Popen([sys.executable, "-c",
553 'import sys; sys.stderr.write("strawberry")'],
554 stderr=d)
555 p.wait()
556 os.lseek(d, 0, 0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100557 self.assertEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558
559 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000560 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000561 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000562 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563 p = subprocess.Popen([sys.executable, "-c",
564 'import sys; sys.stderr.write("strawberry")'],
565 stderr=tf)
566 p.wait()
567 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100568 self.assertEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000569
Martin Panterc7635892016-05-13 01:54:44 +0000570 def test_stderr_redirect_with_no_stdout_redirect(self):
571 # test stderr=STDOUT while stdout=None (not set)
572
573 # - grandchild prints to stderr
574 # - child redirects grandchild's stderr to its stdout
575 # - the parent should get grandchild's stderr in child's stdout
576 p = subprocess.Popen([sys.executable, "-c",
577 'import sys, subprocess;'
578 'rc = subprocess.call([sys.executable, "-c",'
579 ' "import sys;"'
580 ' "sys.stderr.write(\'42\')"],'
581 ' stderr=subprocess.STDOUT);'
582 'sys.exit(rc)'],
583 stdout=subprocess.PIPE,
584 stderr=subprocess.PIPE)
585 stdout, stderr = p.communicate()
586 #NOTE: stdout should get stderr from grandchild
Victor Stinner6cac1132019-12-08 08:38:16 +0100587 self.assertEqual(stdout, b'42')
588 self.assertEqual(stderr, b'') # should be empty
Martin Panterc7635892016-05-13 01:54:44 +0000589 self.assertEqual(p.returncode, 0)
590
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000591 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000592 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000593 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000594 'import sys;'
595 'sys.stdout.write("apple");'
596 'sys.stdout.flush();'
597 'sys.stderr.write("orange")'],
598 stdout=subprocess.PIPE,
599 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200600 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100601 self.assertEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000602
603 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000604 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000605 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000606 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000607 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000608 'import sys;'
609 'sys.stdout.write("apple");'
610 'sys.stdout.flush();'
611 'sys.stderr.write("orange")'],
612 stdout=tf,
613 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000614 p.wait()
615 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100616 self.assertEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000617
Thomas Wouters89f507f2006-12-13 04:49:30 +0000618 def test_stdout_filedes_of_stdout(self):
619 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200620 # To avoid printing the text on stdout, we do something similar to
621 # test_stdout_none (see above). The parent subprocess calls the child
622 # subprocess passing stdout=1, and this test uses stdout=PIPE in
623 # order to capture and check the output of the parent. See #11963.
624 code = ('import sys, subprocess; '
625 'rc = subprocess.call([sys.executable, "-c", '
626 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
627 'b\'test with stdout=1\'))"], stdout=1); '
628 'assert rc == 18')
629 p = subprocess.Popen([sys.executable, "-c", code],
630 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
631 self.addCleanup(p.stdout.close)
632 self.addCleanup(p.stderr.close)
633 out, err = p.communicate()
634 self.assertEqual(p.returncode, 0, err)
635 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000636
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200637 def test_stdout_devnull(self):
638 p = subprocess.Popen([sys.executable, "-c",
639 'for i in range(10240):'
640 'print("x" * 1024)'],
641 stdout=subprocess.DEVNULL)
642 p.wait()
643 self.assertEqual(p.stdout, None)
644
645 def test_stderr_devnull(self):
646 p = subprocess.Popen([sys.executable, "-c",
647 'import sys\n'
648 'for i in range(10240):'
649 'sys.stderr.write("x" * 1024)'],
650 stderr=subprocess.DEVNULL)
651 p.wait()
652 self.assertEqual(p.stderr, None)
653
654 def test_stdin_devnull(self):
655 p = subprocess.Popen([sys.executable, "-c",
656 'import sys;'
657 'sys.stdin.read(1)'],
658 stdin=subprocess.DEVNULL)
659 p.wait()
660 self.assertEqual(p.stdin, None)
661
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000662 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663 newenv = os.environ.copy()
664 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200665 with subprocess.Popen([sys.executable, "-c",
666 'import sys,os;'
667 'sys.stdout.write(os.getenv("FRUIT"))'],
668 stdout=subprocess.PIPE,
669 env=newenv) as p:
670 stdout, stderr = p.communicate()
671 self.assertEqual(stdout, b"orange")
672
Victor Stinner62d51182011-06-23 01:02:25 +0200673 # Windows requires at least the SYSTEMROOT environment variable to start
674 # Python
675 @unittest.skipIf(sys.platform == 'win32',
676 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700677 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
678 'The Python shared library cannot be loaded '
679 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200680 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700681 """Verify that env={} is as empty as possible."""
682
Gregory P. Smith85aba232017-05-30 16:21:47 -0700683 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700684 """Determine if an environment variable is under our control."""
685 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
686 # on adding even when the environment in exec is empty.
687 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700688 return ('VERSIONER' in n or '__CF' in n or # MacOS
Nick Coghlan6ea41862017-06-11 13:16:15 +1000689 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
690 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700691
Victor Stinnerf1512a22011-06-21 17:18:38 +0200692 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700693 'import os; print(list(os.environ.keys()))'],
694 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200695 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700696 child_env_names = eval(stdout.strip())
697 self.assertIsInstance(child_env_names, list)
698 child_env_names = [k for k in child_env_names
699 if not is_env_var_to_ignore(k)]
700 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000701
Serhiy Storchakad174d242017-06-23 19:39:27 +0300702 def test_invalid_cmd(self):
703 # null character in the command name
704 cmd = sys.executable + '\0'
705 with self.assertRaises(ValueError):
706 subprocess.Popen([cmd, "-c", "pass"])
707
708 # null character in the command argument
709 with self.assertRaises(ValueError):
710 subprocess.Popen([sys.executable, "-c", "pass#\0"])
711
712 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300713 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300714 newenv = os.environ.copy()
715 newenv["FRUIT\0VEGETABLE"] = "cabbage"
716 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700717 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300718
Ville Skyttä49b27342017-08-03 09:00:59 +0300719 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300720 newenv = os.environ.copy()
721 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
722 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700723 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300724
Ville Skyttä49b27342017-08-03 09:00:59 +0300725 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300726 newenv = os.environ.copy()
727 newenv["FRUIT=ORANGE"] = "lemon"
728 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700729 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300730
Ville Skyttä49b27342017-08-03 09:00:59 +0300731 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300732 newenv = os.environ.copy()
733 newenv["FRUIT"] = "orange=lemon"
734 with subprocess.Popen([sys.executable, "-c",
735 'import sys, os;'
736 'sys.stdout.write(os.getenv("FRUIT"))'],
737 stdout=subprocess.PIPE,
738 env=newenv) as p:
739 stdout, stderr = p.communicate()
740 self.assertEqual(stdout, b"orange=lemon")
741
Peter Astrandcbac93c2005-03-03 20:24:28 +0000742 def test_communicate_stdin(self):
743 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000744 'import sys;'
745 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000746 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000747 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000748 self.assertEqual(p.returncode, 1)
749
750 def test_communicate_stdout(self):
751 p = subprocess.Popen([sys.executable, "-c",
752 'import sys; sys.stdout.write("pineapple")'],
753 stdout=subprocess.PIPE)
754 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000755 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000756 self.assertEqual(stderr, None)
757
758 def test_communicate_stderr(self):
759 p = subprocess.Popen([sys.executable, "-c",
760 'import sys; sys.stderr.write("pineapple")'],
761 stderr=subprocess.PIPE)
762 (stdout, stderr) = p.communicate()
763 self.assertEqual(stdout, None)
Victor Stinner6cac1132019-12-08 08:38:16 +0100764 self.assertEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000765
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000767 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000768 'import sys,os;'
769 'sys.stderr.write("pineapple");'
770 'sys.stdout.write(sys.stdin.read())'],
771 stdin=subprocess.PIPE,
772 stdout=subprocess.PIPE,
773 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000774 self.addCleanup(p.stdout.close)
775 self.addCleanup(p.stderr.close)
776 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000777 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000778 self.assertEqual(stdout, b"banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100779 self.assertEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000780
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400781 def test_communicate_timeout(self):
782 p = subprocess.Popen([sys.executable, "-c",
783 'import sys,os,time;'
784 'sys.stderr.write("pineapple\\n");'
785 'time.sleep(1);'
786 'sys.stderr.write("pear\\n");'
787 'sys.stdout.write(sys.stdin.read())'],
788 universal_newlines=True,
789 stdin=subprocess.PIPE,
790 stdout=subprocess.PIPE,
791 stderr=subprocess.PIPE)
792 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
793 timeout=0.3)
794 # Make sure we can keep waiting for it, and that we get the whole output
795 # after it completes.
796 (stdout, stderr) = p.communicate()
797 self.assertEqual(stdout, "banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100798 self.assertEqual(stderr.encode(), b"pineapple\npear\n")
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400799
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700800 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200801 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400802 p = subprocess.Popen([sys.executable, "-c",
803 'import sys,os,time;'
804 'sys.stdout.write("a" * (64 * 1024));'
805 'time.sleep(0.2);'
806 'sys.stdout.write("a" * (64 * 1024));'
807 'time.sleep(0.2);'
808 'sys.stdout.write("a" * (64 * 1024));'
809 'time.sleep(0.2);'
810 'sys.stdout.write("a" * (64 * 1024));'],
811 stdout=subprocess.PIPE)
812 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
813 (stdout, _) = p.communicate()
814 self.assertEqual(len(stdout), 4 * 64 * 1024)
815
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000816 # Test for the fd leak reported in http://bugs.python.org/issue2791.
817 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000818 for stdin_pipe in (False, True):
819 for stdout_pipe in (False, True):
820 for stderr_pipe in (False, True):
821 options = {}
822 if stdin_pipe:
823 options['stdin'] = subprocess.PIPE
824 if stdout_pipe:
825 options['stdout'] = subprocess.PIPE
826 if stderr_pipe:
827 options['stderr'] = subprocess.PIPE
828 if not options:
829 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700830 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000831 p.communicate()
832 if p.stdin is not None:
833 self.assertTrue(p.stdin.closed)
834 if p.stdout is not None:
835 self.assertTrue(p.stdout.closed)
836 if p.stderr is not None:
837 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000838
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000839 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000840 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000841 p = subprocess.Popen([sys.executable, "-c",
842 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843 (stdout, stderr) = p.communicate()
844 self.assertEqual(stdout, None)
845 self.assertEqual(stderr, None)
846
847 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000848 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000850 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000851 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000852 os.close(x)
853 os.close(y)
854 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000855 'import sys,os;'
856 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200857 'sys.stderr.write("x" * %d);'
858 'sys.stdout.write(sys.stdin.read())' %
859 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000860 stdin=subprocess.PIPE,
861 stdout=subprocess.PIPE,
862 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000863 self.addCleanup(p.stdout.close)
864 self.addCleanup(p.stderr.close)
865 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200866 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000867 (stdout, stderr) = p.communicate(string_to_write)
868 self.assertEqual(stdout, string_to_write)
869
870 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000871 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000872 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000873 'import sys,os;'
874 'sys.stdout.write(sys.stdin.read())'],
875 stdin=subprocess.PIPE,
876 stdout=subprocess.PIPE,
877 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000878 self.addCleanup(p.stdout.close)
879 self.addCleanup(p.stderr.close)
880 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000881 p.stdin.write(b"banana")
882 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000883 self.assertEqual(stdout, b"bananasplit")
Victor Stinner6cac1132019-12-08 08:38:16 +0100884 self.assertEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000885
andyclegg7fed7bd2017-10-23 03:01:19 +0100886 def test_universal_newlines_and_text(self):
887 args = [
888 sys.executable, "-c",
889 'import sys,os;' + SETBINARY +
890 'buf = sys.stdout.buffer;'
891 'buf.write(sys.stdin.readline().encode());'
892 'buf.flush();'
893 'buf.write(b"line2\\n");'
894 'buf.flush();'
895 'buf.write(sys.stdin.read().encode());'
896 'buf.flush();'
897 'buf.write(b"line4\\n");'
898 'buf.flush();'
899 'buf.write(b"line5\\r\\n");'
900 'buf.flush();'
901 'buf.write(b"line6\\r");'
902 'buf.flush();'
903 'buf.write(b"\\nline7");'
904 'buf.flush();'
905 'buf.write(b"\\nline8");']
906
907 for extra_kwarg in ('universal_newlines', 'text'):
908 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
909 'stdout': subprocess.PIPE,
910 extra_kwarg: True})
911 with p:
912 p.stdin.write("line1\n")
913 p.stdin.flush()
914 self.assertEqual(p.stdout.readline(), "line1\n")
915 p.stdin.write("line3\n")
916 p.stdin.close()
917 self.addCleanup(p.stdout.close)
918 self.assertEqual(p.stdout.readline(),
919 "line2\n")
920 self.assertEqual(p.stdout.read(6),
921 "line3\n")
922 self.assertEqual(p.stdout.read(),
923 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000924
925 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000926 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000927 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000928 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200929 'buf = sys.stdout.buffer;'
930 'buf.write(b"line2\\n");'
931 'buf.flush();'
932 'buf.write(b"line4\\n");'
933 'buf.flush();'
934 'buf.write(b"line5\\r\\n");'
935 'buf.flush();'
936 'buf.write(b"line6\\r");'
937 'buf.flush();'
938 'buf.write(b"\\nline7");'
939 'buf.flush();'
940 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200941 stderr=subprocess.PIPE,
942 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000943 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000944 self.addCleanup(p.stdout.close)
945 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000946 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200947 self.assertEqual(stdout,
948 "line2\nline4\nline5\nline6\nline7\nline8")
949
950 def test_universal_newlines_communicate_stdin(self):
951 # universal newlines through communicate(), with only stdin
952 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300953 'import sys,os;' + SETBINARY + textwrap.dedent('''
954 s = sys.stdin.readline()
955 assert s == "line1\\n", repr(s)
956 s = sys.stdin.read()
957 assert s == "line3\\n", repr(s)
958 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200959 stdin=subprocess.PIPE,
960 universal_newlines=1)
961 (stdout, stderr) = p.communicate("line1\nline3\n")
962 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000963
Andrew Svetlovf3765072012-08-14 18:35:17 +0300964 def test_universal_newlines_communicate_input_none(self):
965 # Test communicate(input=None) with universal newlines.
966 #
967 # We set stdout to PIPE because, as of this writing, a different
968 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700969 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +0300970 stdin=subprocess.PIPE,
971 stdout=subprocess.PIPE,
972 universal_newlines=True)
973 p.communicate()
974 self.assertEqual(p.returncode, 0)
975
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300976 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300977 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300978 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300979 'import sys,os;' + SETBINARY + textwrap.dedent('''
980 s = sys.stdin.buffer.readline()
981 sys.stdout.buffer.write(s)
982 sys.stdout.buffer.write(b"line2\\r")
983 sys.stderr.buffer.write(b"eline2\\n")
984 s = sys.stdin.buffer.read()
985 sys.stdout.buffer.write(s)
986 sys.stdout.buffer.write(b"line4\\n")
987 sys.stdout.buffer.write(b"line5\\r\\n")
988 sys.stderr.buffer.write(b"eline6\\r")
989 sys.stderr.buffer.write(b"eline7\\r\\nz")
990 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300991 stdin=subprocess.PIPE,
992 stderr=subprocess.PIPE,
993 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300994 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300995 self.addCleanup(p.stdout.close)
996 self.addCleanup(p.stderr.close)
997 (stdout, stderr) = p.communicate("line1\nline3\n")
998 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300999 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001000 # Python debug build push something like "[42442 refs]\n"
1001 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001002 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001003
Andrew Svetlov82860712012-08-19 22:13:41 +03001004 def test_universal_newlines_communicate_encodings(self):
1005 # Check that universal newlines mode works for various encodings,
1006 # in particular for encodings in the UTF-16 and UTF-32 families.
1007 # See issue #15595.
1008 #
1009 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1010 # without, and UTF-16 and UTF-32.
1011 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001012 code = ("import sys; "
1013 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1014 encoding)
1015 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001016 # We set stdin to be non-None because, as of this writing,
1017 # a different code path is used when the number of pipes is
1018 # zero or one.
1019 popen = subprocess.Popen(args,
1020 stdin=subprocess.PIPE,
1021 stdout=subprocess.PIPE,
1022 encoding=encoding)
1023 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001024 self.assertEqual(stdout, '1\n2\n3\n4')
1025
Steve Dower050acae2016-09-06 20:16:17 -07001026 def test_communicate_errors(self):
1027 for errors, expected in [
1028 ('ignore', ''),
1029 ('replace', '\ufffd\ufffd'),
1030 ('surrogateescape', '\udc80\udc80'),
1031 ('backslashreplace', '\\x80\\x80'),
1032 ]:
1033 code = ("import sys; "
1034 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1035 args = [sys.executable, '-c', code]
1036 # We set stdin to be non-None because, as of this writing,
1037 # a different code path is used when the number of pipes is
1038 # zero or one.
1039 popen = subprocess.Popen(args,
1040 stdin=subprocess.PIPE,
1041 stdout=subprocess.PIPE,
1042 encoding='utf-8',
1043 errors=errors)
1044 stdout, stderr = popen.communicate(input='')
1045 self.assertEqual(stdout, '[{}]'.format(expected))
1046
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001047 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001048 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001049 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001050 max_handles = 1026 # too much for most UNIX systems
1051 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001052 max_handles = 2050 # too much for (at least some) Windows setups
1053 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001054 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001055 try:
1056 for i in range(max_handles):
1057 try:
Hai Shi0c4f0f32020-06-30 21:46:31 +08001058 tmpfile = os.path.join(tmpdir, os_helper.TESTFN)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001059 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001060 except OSError as e:
1061 if e.errno != errno.EMFILE:
1062 raise
1063 break
1064 else:
1065 self.skipTest("failed to reach the file descriptor limit "
1066 "(tried %d)" % max_handles)
1067 # Close a couple of them (should be enough for a subprocess)
1068 for i in range(10):
1069 os.close(handles.pop())
1070 # Loop creating some subprocesses. If one of them leaks some fds,
1071 # the next loop iteration will fail by reaching the max fd limit.
1072 for i in range(15):
1073 p = subprocess.Popen([sys.executable, "-c",
1074 "import sys;"
1075 "sys.stdout.write(sys.stdin.read())"],
1076 stdin=subprocess.PIPE,
1077 stdout=subprocess.PIPE,
1078 stderr=subprocess.PIPE)
1079 data = p.communicate(b"lime")[0]
1080 self.assertEqual(data, b"lime")
1081 finally:
1082 for h in handles:
1083 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001084 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001085
1086 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001087 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1088 '"a b c" d e')
1089 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1090 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001091 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1092 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001093 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1094 'a\\\\\\b "de fg" h')
1095 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1096 'a\\\\\\"b c d')
1097 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1098 '"a\\\\b c" d e')
1099 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1100 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001101 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1102 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001103
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001104 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001105 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001106 "import os; os.read(0, 1)"],
1107 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001108 self.addCleanup(p.stdin.close)
1109 self.assertIsNone(p.poll())
1110 os.write(p.stdin.fileno(), b'A')
1111 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001112 # Subsequent invocations should just return the returncode
1113 self.assertEqual(p.poll(), 0)
1114
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001115 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001116 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001117 self.assertEqual(p.wait(), 0)
1118 # Subsequent invocations should just return the returncode
1119 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001120
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001121 def test_wait_timeout(self):
1122 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001123 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001124 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001125 p.wait(timeout=0.0001)
1126 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001127 self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001128
Peter Astrand738131d2004-11-30 21:04:45 +00001129 def test_invalid_bufsize(self):
1130 # an invalid type of the bufsize argument should raise
1131 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001132 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001133 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001134
Guido van Rossum46a05a72007-06-07 21:56:45 +00001135 def test_bufsize_is_none(self):
1136 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001137 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001138 self.assertEqual(p.wait(), 0)
1139 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001140 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001141 self.assertEqual(p.wait(), 0)
1142
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001143 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1144 # subprocess may deadlock with bufsize=1, see issue #21332
1145 with subprocess.Popen([sys.executable, "-c", "import sys;"
1146 "sys.stdout.write(sys.stdin.readline());"
1147 "sys.stdout.flush()"],
1148 stdin=subprocess.PIPE,
1149 stdout=subprocess.PIPE,
1150 stderr=subprocess.DEVNULL,
1151 bufsize=1,
1152 universal_newlines=universal_newlines) as p:
1153 p.stdin.write(line) # expect that it flushes the line in text mode
1154 os.close(p.stdin.fileno()) # close it without flushing the buffer
1155 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001156 with support.SuppressCrashReport():
1157 try:
1158 p.stdin.close()
1159 except OSError:
1160 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001161 p.stdin = None
1162 self.assertEqual(p.returncode, 0)
1163 self.assertEqual(read_line, expected)
1164
1165 def test_bufsize_equal_one_text_mode(self):
1166 # line is flushed in text mode with bufsize=1.
1167 # we should get the full line in return
1168 line = "line\n"
1169 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1170
1171 def test_bufsize_equal_one_binary_mode(self):
1172 # line is not flushed in binary mode with bufsize=1.
1173 # we should get empty response
1174 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001175 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1176 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001177
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001178 def test_leaking_fds_on_error(self):
1179 # see bug #5179: Popen leaks file descriptors to PIPEs if
1180 # the child fails to execute; this will eventually exhaust
1181 # the maximum number of open fds. 1024 seems a very common
1182 # value for that limit, but Windows has 2048, so we loop
1183 # 1024 times (each call leaked two fds).
1184 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001185 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001186 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001187 stdout=subprocess.PIPE,
1188 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001189
Victor Stinner9a83f652017-08-21 23:51:31 +02001190 def test_nonexisting_with_pipes(self):
1191 # bpo-30121: Popen with pipes must close properly pipes on error.
1192 # Previously, os.close() was called with a Windows handle which is not
1193 # a valid file descriptor.
1194 #
1195 # Run the test in a subprocess to control how the CRT reports errors
1196 # and to get stderr content.
1197 try:
1198 import msvcrt
1199 msvcrt.CrtSetReportMode
1200 except (AttributeError, ImportError):
1201 self.skipTest("need msvcrt.CrtSetReportMode")
1202
1203 code = textwrap.dedent(f"""
1204 import msvcrt
1205 import subprocess
1206
1207 cmd = {NONEXISTING_CMD!r}
1208
1209 for report_type in [msvcrt.CRT_WARN,
1210 msvcrt.CRT_ERROR,
1211 msvcrt.CRT_ASSERT]:
1212 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1213 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1214
1215 try:
Zachary Ware55376462018-02-19 14:02:38 -06001216 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001217 stdout=subprocess.PIPE,
1218 stderr=subprocess.PIPE)
1219 except OSError:
1220 pass
1221 """)
1222 cmd = [sys.executable, "-c", code]
1223 proc = subprocess.Popen(cmd,
1224 stderr=subprocess.PIPE,
1225 universal_newlines=True)
1226 with proc:
1227 stderr = proc.communicate()[1]
1228 self.assertEqual(stderr, "")
1229 self.assertEqual(proc.returncode, 0)
1230
Antoine Pitroua8392712013-08-30 23:38:13 +02001231 def test_double_close_on_error(self):
1232 # Issue #18851
1233 fds = []
1234 def open_fds():
1235 for i in range(20):
1236 fds.extend(os.pipe())
1237 time.sleep(0.001)
1238 t = threading.Thread(target=open_fds)
1239 t.start()
1240 try:
1241 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001242 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001243 stdin=subprocess.PIPE,
1244 stdout=subprocess.PIPE,
1245 stderr=subprocess.PIPE)
1246 finally:
1247 t.join()
1248 exc = None
1249 for fd in fds:
1250 # If a double close occurred, some of those fds will
1251 # already have been closed by mistake, and os.close()
1252 # here will raise.
1253 try:
1254 os.close(fd)
1255 except OSError as e:
1256 exc = e
1257 if exc is not None:
1258 raise exc
1259
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001260 def test_threadsafe_wait(self):
1261 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1262 proc = subprocess.Popen([sys.executable, '-c',
1263 'import time; time.sleep(12)'])
1264 self.assertEqual(proc.returncode, None)
1265 results = []
1266
1267 def kill_proc_timer_thread():
1268 results.append(('thread-start-poll-result', proc.poll()))
1269 # terminate it from the thread and wait for the result.
1270 proc.kill()
1271 proc.wait()
1272 results.append(('thread-after-kill-and-wait', proc.returncode))
1273 # this wait should be a no-op given the above.
1274 proc.wait()
1275 results.append(('thread-after-second-wait', proc.returncode))
1276
1277 # This is a timing sensitive test, the failure mode is
1278 # triggered when both the main thread and this thread are in
1279 # the wait() call at once. The delay here is to allow the
1280 # main thread to most likely be blocked in its wait() call.
1281 t = threading.Timer(0.2, kill_proc_timer_thread)
1282 t.start()
1283
Victor Stinner937ee9e2018-06-26 02:11:06 +02001284 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001285 expected_errorcode = 1
1286 else:
1287 # Should be -9 because of the proc.kill() from the thread.
1288 expected_errorcode = -9
1289
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001290 # Wait for the process to finish; the thread should kill it
1291 # long before it finishes on its own. Supplying a timeout
1292 # triggers a different code path for better coverage.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001293 proc.wait(timeout=support.SHORT_TIMEOUT)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001294 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001295 msg="unexpected result in wait from main thread")
1296
1297 # This should be a no-op with no change in returncode.
1298 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001299 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001300 msg="unexpected result in second main wait.")
1301
1302 t.join()
1303 # Ensure that all of the thread results are as expected.
1304 # When a race condition occurs in wait(), the returncode could
1305 # be set by the wrong thread that doesn't actually have it
1306 # leading to an incorrect value.
1307 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001308 ('thread-after-kill-and-wait', expected_errorcode),
1309 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001310 results)
1311
Victor Stinnerb3693582010-05-21 20:13:12 +00001312 def test_issue8780(self):
1313 # Ensure that stdout is inherited from the parent
1314 # if stdout=PIPE is not used
1315 code = ';'.join((
1316 'import subprocess, sys',
1317 'retcode = subprocess.call('
1318 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1319 'assert retcode == 0'))
1320 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001321 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001322
Tim Goldenaf5ac392010-08-06 13:03:56 +00001323 def test_handles_closed_on_exception(self):
1324 # If CreateProcess exits with an error, ensure the
1325 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001326 ifhandle, ifname = tempfile.mkstemp()
1327 ofhandle, ofname = tempfile.mkstemp()
1328 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001329 try:
1330 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1331 stderr=efhandle)
1332 except OSError:
1333 os.close(ifhandle)
1334 os.remove(ifname)
1335 os.close(ofhandle)
1336 os.remove(ofname)
1337 os.close(efhandle)
1338 os.remove(efname)
1339 self.assertFalse(os.path.exists(ifname))
1340 self.assertFalse(os.path.exists(ofname))
1341 self.assertFalse(os.path.exists(efname))
1342
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001343 def test_communicate_epipe(self):
1344 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001345 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001346 stdin=subprocess.PIPE,
1347 stdout=subprocess.PIPE,
1348 stderr=subprocess.PIPE)
1349 self.addCleanup(p.stdout.close)
1350 self.addCleanup(p.stderr.close)
1351 self.addCleanup(p.stdin.close)
1352 p.communicate(b"x" * 2**20)
1353
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001354 def test_repr(self):
1355 # Run a command that waits for user input, to check the repr() of
1356 # a Proc object while and after the sub-process runs.
1357 code = 'import sys; input(); sys.exit(57)'
1358 cmd = [sys.executable, '-c', code]
1359 result = "<Popen: returncode: {}"
1360
1361 with subprocess.Popen(
1362 cmd, stdin=subprocess.PIPE, universal_newlines=True) as proc:
1363 self.assertIsNone(proc.returncode)
1364 self.assertTrue(
1365 repr(proc).startswith(result.format(proc.returncode)) and
1366 repr(proc).endswith('>')
1367 )
1368
1369 proc.communicate(input='exit...\n')
1370 proc.wait()
1371
1372 self.assertIsNotNone(proc.returncode)
1373 self.assertTrue(
1374 repr(proc).startswith(result.format(proc.returncode)) and
1375 repr(proc).endswith('>')
1376 )
1377
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001378 def test_communicate_epipe_only_stdin(self):
1379 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001380 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001381 stdin=subprocess.PIPE)
1382 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001383 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001384 p.communicate(b"x" * 2**20)
1385
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001386 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1387 "Requires signal.SIGUSR1")
1388 @unittest.skipUnless(hasattr(os, 'kill'),
1389 "Requires os.kill")
1390 @unittest.skipUnless(hasattr(os, 'getppid'),
1391 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001392 def test_communicate_eintr(self):
1393 # Issue #12493: communicate() should handle EINTR
1394 def handler(signum, frame):
1395 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001396 old_handler = signal.signal(signal.SIGUSR1, handler)
1397 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001398
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001399 args = [sys.executable, "-c",
1400 'import os, signal;'
1401 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001402 for stream in ('stdout', 'stderr'):
1403 kw = {stream: subprocess.PIPE}
1404 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001405 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001406 process.communicate()
1407
Tim Peterse718f612004-10-12 21:51:32 +00001408
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001409 # This test is Linux-ish specific for simplicity to at least have
1410 # some coverage. It is not a platform specific bug.
1411 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1412 "Linux specific")
1413 def test_failed_child_execute_fd_leak(self):
1414 """Test for the fork() failure fd leak reported in issue16327."""
1415 fd_directory = '/proc/%d/fd' % os.getpid()
1416 fds_before_popen = os.listdir(fd_directory)
1417 with self.assertRaises(PopenTestException):
1418 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001419 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001420 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1421
1422 # NOTE: This test doesn't verify that the real _execute_child
1423 # does not close the file descriptors itself on the way out
1424 # during an exception. Code inspection has confirmed that.
1425
1426 fds_after_exception = os.listdir(fd_directory)
1427 self.assertEqual(fds_before_popen, fds_after_exception)
1428
Victor Stinner937ee9e2018-06-26 02:11:06 +02001429 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001430 def test_file_not_found_includes_filename(self):
1431 with self.assertRaises(FileNotFoundError) as c:
1432 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1433 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1434
Victor Stinner937ee9e2018-06-26 02:11:06 +02001435 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001436 def test_file_not_found_with_bad_cwd(self):
1437 with self.assertRaises(FileNotFoundError) as c:
1438 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1439 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1440
Batuhan Taşkaya4dc5a9d2019-12-30 19:02:04 +03001441 def test_class_getitems(self):
Guido van Rossum48b069a2020-04-07 09:50:06 -07001442 self.assertIsInstance(subprocess.Popen[bytes], types.GenericAlias)
1443 self.assertIsInstance(subprocess.CompletedProcess[str], types.GenericAlias)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001444
1445class RunFuncTestCase(BaseTestCase):
1446 def run_python(self, code, **kwargs):
1447 """Run Python code in a subprocess using subprocess.run"""
1448 argv = [sys.executable, "-c", code]
1449 return subprocess.run(argv, **kwargs)
1450
1451 def test_returncode(self):
1452 # call() function with sequence argument
1453 cp = self.run_python("import sys; sys.exit(47)")
1454 self.assertEqual(cp.returncode, 47)
1455 with self.assertRaises(subprocess.CalledProcessError):
1456 cp.check_returncode()
1457
1458 def test_check(self):
1459 with self.assertRaises(subprocess.CalledProcessError) as c:
1460 self.run_python("import sys; sys.exit(47)", check=True)
1461 self.assertEqual(c.exception.returncode, 47)
1462
1463 def test_check_zero(self):
1464 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001465 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001466 self.assertEqual(cp.returncode, 0)
1467
1468 def test_timeout(self):
1469 # run() function with timeout argument; we want to test that the child
1470 # process gets killed when the timeout expires. If the child isn't
1471 # killed, this call will deadlock since subprocess.run waits for the
1472 # child.
1473 with self.assertRaises(subprocess.TimeoutExpired):
1474 self.run_python("while True: pass", timeout=0.0001)
1475
1476 def test_capture_stdout(self):
1477 # capture stdout with zero return code
1478 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1479 self.assertIn(b'BDFL', cp.stdout)
1480
1481 def test_capture_stderr(self):
1482 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1483 stderr=subprocess.PIPE)
1484 self.assertIn(b'BDFL', cp.stderr)
1485
1486 def test_check_output_stdin_arg(self):
1487 # run() can be called with stdin set to a file
1488 tf = tempfile.TemporaryFile()
1489 self.addCleanup(tf.close)
1490 tf.write(b'pear')
1491 tf.seek(0)
1492 cp = self.run_python(
1493 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1494 stdin=tf, stdout=subprocess.PIPE)
1495 self.assertIn(b'PEAR', cp.stdout)
1496
1497 def test_check_output_input_arg(self):
1498 # check_output() can be called with input set to a string
1499 cp = self.run_python(
1500 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1501 input=b'pear', stdout=subprocess.PIPE)
1502 self.assertIn(b'PEAR', cp.stdout)
1503
1504 def test_check_output_stdin_with_input_arg(self):
1505 # run() refuses to accept 'stdin' with 'input'
1506 tf = tempfile.TemporaryFile()
1507 self.addCleanup(tf.close)
1508 tf.write(b'pear')
1509 tf.seek(0)
1510 with self.assertRaises(ValueError,
1511 msg="Expected ValueError when stdin and input args supplied.") as c:
1512 output = self.run_python("print('will not be run')",
1513 stdin=tf, input=b'hare')
1514 self.assertIn('stdin', c.exception.args[0])
1515 self.assertIn('input', c.exception.args[0])
1516
1517 def test_check_output_timeout(self):
1518 with self.assertRaises(subprocess.TimeoutExpired) as c:
1519 cp = self.run_python((
1520 "import sys, time\n"
1521 "sys.stdout.write('BDFL')\n"
1522 "sys.stdout.flush()\n"
1523 "time.sleep(3600)"),
1524 # Some heavily loaded buildbots (sparc Debian 3.x) require
1525 # this much time to start and print.
1526 timeout=3, stdout=subprocess.PIPE)
1527 self.assertEqual(c.exception.output, b'BDFL')
1528 # output is aliased to stdout
1529 self.assertEqual(c.exception.stdout, b'BDFL')
1530
1531 def test_run_kwargs(self):
1532 newenv = os.environ.copy()
1533 newenv["FRUIT"] = "banana"
1534 cp = self.run_python(('import sys, os;'
1535 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1536 env=newenv)
1537 self.assertEqual(cp.returncode, 33)
1538
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001539 def test_run_with_pathlike_path(self):
1540 # bpo-31961: test run(pathlike_object)
1541 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001542 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001543 prog = 'tree.com' if mswindows else 'ls'
1544 path = shutil.which(prog)
1545 if path is None:
1546 self.skipTest(f'{prog} required for this test')
1547 path = FakePath(path)
1548 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1549 self.assertEqual(res.returncode, 0)
1550 with self.assertRaises(TypeError):
1551 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1552
1553 def test_run_with_bytes_path_and_arguments(self):
1554 # bpo-31961: test run([bytes_object, b'additional arguments'])
1555 path = os.fsencode(sys.executable)
1556 args = [path, '-c', b'import sys; sys.exit(57)']
1557 res = subprocess.run(args)
1558 self.assertEqual(res.returncode, 57)
1559
1560 def test_run_with_pathlike_path_and_arguments(self):
1561 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1562 path = FakePath(sys.executable)
1563 args = [path, '-c', 'import sys; sys.exit(57)']
1564 res = subprocess.run(args)
1565 self.assertEqual(res.returncode, 57)
1566
Bo Baylesce0f33d2018-01-30 00:40:39 -06001567 def test_capture_output(self):
1568 cp = self.run_python(("import sys;"
1569 "sys.stdout.write('BDFL'); "
1570 "sys.stderr.write('FLUFL')"),
1571 capture_output=True)
1572 self.assertIn(b'BDFL', cp.stdout)
1573 self.assertIn(b'FLUFL', cp.stderr)
1574
1575 def test_stdout_with_capture_output_arg(self):
1576 # run() refuses to accept 'stdout' with 'capture_output'
1577 tf = tempfile.TemporaryFile()
1578 self.addCleanup(tf.close)
1579 with self.assertRaises(ValueError,
1580 msg=("Expected ValueError when stdout and capture_output "
1581 "args supplied.")) as c:
1582 output = self.run_python("print('will not be run')",
1583 capture_output=True, stdout=tf)
1584 self.assertIn('stdout', c.exception.args[0])
1585 self.assertIn('capture_output', c.exception.args[0])
1586
1587 def test_stderr_with_capture_output_arg(self):
1588 # run() refuses to accept 'stderr' with 'capture_output'
1589 tf = tempfile.TemporaryFile()
1590 self.addCleanup(tf.close)
1591 with self.assertRaises(ValueError,
1592 msg=("Expected ValueError when stderr and capture_output "
1593 "args supplied.")) as c:
1594 output = self.run_python("print('will not be run')",
1595 capture_output=True, stderr=tf)
1596 self.assertIn('stderr', c.exception.args[0])
1597 self.assertIn('capture_output', c.exception.args[0])
1598
Gregory P. Smith580d2782019-09-11 04:23:05 -05001599 # This test _might_ wind up a bit fragile on loaded build+test machines
1600 # as it depends on the timing with wide enough margins for normal situations
1601 # but does assert that it happened "soon enough" to believe the right thing
1602 # happened.
1603 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1604 def test_run_with_shell_timeout_and_capture_output(self):
1605 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1606 before_secs = time.monotonic()
1607 try:
1608 subprocess.run('sleep 3', shell=True, timeout=0.1,
1609 capture_output=True) # New session unspecified.
1610 except subprocess.TimeoutExpired as exc:
1611 after_secs = time.monotonic()
1612 stacks = traceback.format_exc() # assertRaises doesn't give this.
1613 else:
1614 self.fail("TimeoutExpired not raised.")
1615 self.assertLess(after_secs - before_secs, 1.5,
1616 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1617 f"{stacks}```")
1618
Gregory P. Smith6e730002015-04-14 16:14:25 -07001619
Gregory P. Smith693aa802019-09-13 14:43:35 +01001620def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001621 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001622 if grp:
1623 try:
1624 grp.getgrnam(name_group)
1625 except KeyError:
1626 continue
1627 return name_group
1628 else:
1629 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1630
1631
Victor Stinner937ee9e2018-06-26 02:11:06 +02001632@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001633class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001634
Gregory P. Smith5591b022012-10-10 03:34:47 -07001635 def setUp(self):
1636 super().setUp()
1637 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1638
1639 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001640 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001641 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001642 except OSError as e:
1643 # This avoids hard coding the errno value or the OS perror()
1644 # string and instead capture the exception that we want to see
1645 # below for comparison.
1646 desired_exception = e
1647 else:
Martin Pantereb995702016-07-28 01:11:04 +00001648 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001649 self._nonexistent_dir)
1650 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001651
Gregory P. Smith5591b022012-10-10 03:34:47 -07001652 def test_exception_cwd(self):
1653 """Test error in the child raised in the parent for a bad cwd."""
1654 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001655 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001656 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001657 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001658 except OSError as e:
1659 # Test that the child process chdir failure actually makes
1660 # it up to the parent process as the correct exception.
1661 self.assertEqual(desired_exception.errno, e.errno)
1662 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001663 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001664 else:
1665 self.fail("Expected OSError: %s" % desired_exception)
1666
Gregory P. Smith5591b022012-10-10 03:34:47 -07001667 def test_exception_bad_executable(self):
1668 """Test error in the child raised in the parent for a bad executable."""
1669 desired_exception = self._get_chdir_exception()
1670 try:
1671 p = subprocess.Popen([sys.executable, "-c", ""],
1672 executable=self._nonexistent_dir)
1673 except OSError as e:
1674 # Test that the child process exec failure actually makes
1675 # it up to the parent process as the correct exception.
1676 self.assertEqual(desired_exception.errno, e.errno)
1677 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001678 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001679 else:
1680 self.fail("Expected OSError: %s" % desired_exception)
1681
1682 def test_exception_bad_args_0(self):
1683 """Test error in the child raised in the parent for a bad args[0]."""
1684 desired_exception = self._get_chdir_exception()
1685 try:
1686 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1687 except OSError as e:
1688 # Test that the child process exec failure actually makes
1689 # it up to the parent process as the correct exception.
1690 self.assertEqual(desired_exception.errno, e.errno)
1691 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001692 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001693 else:
1694 self.fail("Expected OSError: %s" % desired_exception)
1695
Ammar Askar3fc499b2017-09-06 02:41:30 -04001696 # We mock the __del__ method for Popen in the next two tests
1697 # because it does cleanup based on the pid returned by fork_exec
1698 # along with issuing a resource warning if it still exists. Since
1699 # we don't actually spawn a process in these tests we can forego
1700 # the destructor. An alternative would be to set _child_created to
1701 # False before the destructor is called but there is no easy way
1702 # to do that
1703 class PopenNoDestructor(subprocess.Popen):
1704 def __del__(self):
1705 pass
1706
1707 @mock.patch("subprocess._posixsubprocess.fork_exec")
1708 def test_exception_errpipe_normal(self, fork_exec):
1709 """Test error passing done through errpipe_write in the good case"""
1710 def proper_error(*args):
1711 errpipe_write = args[13]
1712 # Write the hex for the error code EISDIR: 'is a directory'
1713 err_code = '{:x}'.format(errno.EISDIR).encode()
1714 os.write(errpipe_write, b"OSError:" + err_code + b":")
1715 return 0
1716
1717 fork_exec.side_effect = proper_error
1718
Victor Stinner11045c92017-10-05 06:32:53 -07001719 with mock.patch("subprocess.os.waitpid",
1720 side_effect=ChildProcessError):
1721 with self.assertRaises(IsADirectoryError):
1722 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001723
1724 @mock.patch("subprocess._posixsubprocess.fork_exec")
1725 def test_exception_errpipe_bad_data(self, fork_exec):
1726 """Test error passing done through errpipe_write where its not
1727 in the expected format"""
1728 error_data = b"\xFF\x00\xDE\xAD"
1729 def bad_error(*args):
1730 errpipe_write = args[13]
1731 # Anything can be in the pipe, no assumptions should
1732 # be made about its encoding, so we'll write some
1733 # arbitrary hex bytes to test it out
1734 os.write(errpipe_write, error_data)
1735 return 0
1736
1737 fork_exec.side_effect = bad_error
1738
Victor Stinner11045c92017-10-05 06:32:53 -07001739 with mock.patch("subprocess.os.waitpid",
1740 side_effect=ChildProcessError):
1741 with self.assertRaises(subprocess.SubprocessError) as e:
1742 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001743
1744 self.assertIn(repr(error_data), str(e.exception))
1745
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001746 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1747 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001748 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001749 # Blindly assume that cat exists on systems with /proc/self/status...
1750 default_proc_status = subprocess.check_output(
1751 ['cat', '/proc/self/status'],
1752 restore_signals=False)
1753 for line in default_proc_status.splitlines():
1754 if line.startswith(b'SigIgn'):
1755 default_sig_ign_mask = line
1756 break
1757 else:
1758 self.skipTest("SigIgn not found in /proc/self/status.")
1759 restored_proc_status = subprocess.check_output(
1760 ['cat', '/proc/self/status'],
1761 restore_signals=True)
1762 for line in restored_proc_status.splitlines():
1763 if line.startswith(b'SigIgn'):
1764 restored_sig_ign_mask = line
1765 break
1766 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1767 msg="restore_signals=True should've unblocked "
1768 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001769
1770 def test_start_new_session(self):
1771 # For code coverage of calling setsid(). We don't care if we get an
1772 # EPERM error from it depending on the test execution environment, that
1773 # still indicates that it was called.
1774 try:
1775 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001776 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001777 start_new_session=True)
1778 except OSError as e:
1779 if e.errno != errno.EPERM:
1780 raise
1781 else:
Victor Stinner58840432019-06-14 19:31:43 +02001782 parent_sid = os.getsid(0)
1783 child_sid = int(output)
1784 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001785
Patrick McLean2b2ead72019-09-12 10:15:44 -07001786 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1787 def test_user(self):
1788 # For code coverage of the user parameter. We don't care if we get an
1789 # EPERM error from it depending on the test execution environment, that
1790 # still indicates that it was called.
1791
1792 uid = os.geteuid()
1793 test_users = [65534 if uid != 65534 else 65533, uid]
1794 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1795
1796 if pwd is not None:
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001797 try:
1798 pwd.getpwnam(name_uid)
1799 test_users.append(name_uid)
1800 except KeyError:
1801 # unknown user name
1802 name_uid = None
Patrick McLean2b2ead72019-09-12 10:15:44 -07001803
1804 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001805 # posix_spawn() may be used with close_fds=False
1806 for close_fds in (False, True):
1807 with self.subTest(user=user, close_fds=close_fds):
1808 try:
1809 output = subprocess.check_output(
1810 [sys.executable, "-c",
1811 "import os; print(os.getuid())"],
1812 user=user,
1813 close_fds=close_fds)
1814 except PermissionError: # (EACCES, EPERM)
1815 pass
1816 except OSError as e:
1817 if e.errno not in (errno.EACCES, errno.EPERM):
1818 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001819 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001820 if isinstance(user, str):
1821 user_uid = pwd.getpwnam(user).pw_uid
1822 else:
1823 user_uid = user
1824 child_user = int(output)
1825 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001826
1827 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001828 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001829
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001830 if pwd is None and name_uid is not None:
Patrick McLean2b2ead72019-09-12 10:15:44 -07001831 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001832 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001833
1834 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1835 def test_user_error(self):
1836 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001837 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001838
1839 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1840 def test_group(self):
1841 gid = os.getegid()
1842 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001843 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001844
1845 if grp is not None:
1846 group_list.append(name_group)
1847
1848 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001849 # posix_spawn() may be used with close_fds=False
1850 for close_fds in (False, True):
1851 with self.subTest(group=group, close_fds=close_fds):
1852 try:
1853 output = subprocess.check_output(
1854 [sys.executable, "-c",
1855 "import os; print(os.getgid())"],
1856 group=group,
1857 close_fds=close_fds)
1858 except PermissionError: # (EACCES, EPERM)
1859 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001860 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001861 if isinstance(group, str):
1862 group_gid = grp.getgrnam(group).gr_gid
1863 else:
1864 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001865
Victor Stinnerfaca8552019-09-25 15:52:49 +02001866 child_group = int(output)
1867 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001868
1869 # make sure we bomb on negative values
1870 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001871 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001872
1873 if grp is None:
1874 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001875 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001876
1877 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1878 def test_group_error(self):
1879 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001880 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001881
1882 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1883 def test_extra_groups(self):
1884 gid = os.getegid()
1885 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001886 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001887 perm_error = False
1888
1889 if grp is not None:
1890 group_list.append(name_group)
1891
1892 try:
1893 output = subprocess.check_output(
1894 [sys.executable, "-c",
1895 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1896 extra_groups=group_list)
1897 except OSError as ex:
1898 if ex.errno != errno.EPERM:
1899 raise
1900 perm_error = True
1901
1902 else:
1903 parent_groups = os.getgroups()
1904 child_groups = json.loads(output)
1905
1906 if grp is not None:
1907 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
1908 for g in group_list]
1909 else:
1910 desired_gids = group_list
1911
1912 if perm_error:
1913 self.assertEqual(set(child_groups), set(parent_groups))
1914 else:
1915 self.assertEqual(set(desired_gids), set(child_groups))
1916
1917 # make sure we bomb on negative values
1918 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001919 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001920
1921 if grp is None:
1922 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001923 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07001924 extra_groups=[name_group])
1925
1926 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
1927 def test_extra_groups_error(self):
1928 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001929 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001930
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001931 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
1932 'POSIX umask() is not available.')
1933 def test_umask(self):
1934 tmpdir = None
1935 try:
1936 tmpdir = tempfile.mkdtemp()
1937 name = os.path.join(tmpdir, "beans")
1938 # We set an unusual umask in the child so as a unique mode
1939 # for us to test the child's touched file for.
1940 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001941 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001942 umask=0o053)
1943 # Ignore execute permissions entirely in our test,
1944 # filesystems could be mounted to ignore or force that.
1945 st_mode = os.stat(name).st_mode & 0o666
1946 expected_mode = 0o624
1947 self.assertEqual(expected_mode, st_mode,
1948 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
1949 finally:
1950 if tmpdir is not None:
1951 shutil.rmtree(tmpdir)
1952
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001953 def test_run_abort(self):
1954 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001955 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001956 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001957 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001958 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001959 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001960
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001961 def test_CalledProcessError_str_signal(self):
1962 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1963 error_string = str(err)
1964 # We're relying on the repr() of the signal.Signals intenum to provide
1965 # the word signal, the signal name and the numeric value.
1966 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001967 # We're not being specific about the signal name as some signals have
1968 # multiple names and which name is revealed can vary.
1969 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001970 self.assertIn(str(signal.SIGABRT), error_string)
1971
1972 def test_CalledProcessError_str_unknown_signal(self):
1973 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1974 error_string = str(err)
1975 self.assertIn("unknown signal 9876543.", error_string)
1976
1977 def test_CalledProcessError_str_non_zero(self):
1978 err = subprocess.CalledProcessError(2, "fake cmd")
1979 error_string = str(err)
1980 self.assertIn("non-zero exit status 2.", error_string)
1981
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001982 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001983 # DISCLAIMER: Setting environment variables is *not* a good use
1984 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001985 p = subprocess.Popen([sys.executable, "-c",
1986 'import sys,os;'
1987 'sys.stdout.write(os.getenv("FRUIT"))'],
1988 stdout=subprocess.PIPE,
1989 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001990 with p:
1991 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001992
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001993 def test_preexec_exception(self):
1994 def raise_it():
1995 raise ValueError("What if two swallows carried a coconut?")
1996 try:
1997 p = subprocess.Popen([sys.executable, "-c", ""],
1998 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001999 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002000 self.assertTrue(
2001 subprocess._posixsubprocess,
2002 "Expected a ValueError from the preexec_fn")
2003 except ValueError as e:
2004 self.assertIn("coconut", e.args[0])
2005 else:
2006 self.fail("Exception raised by preexec_fn did not make it "
2007 "to the parent process.")
2008
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002009 class _TestExecuteChildPopen(subprocess.Popen):
2010 """Used to test behavior at the end of _execute_child."""
2011 def __init__(self, testcase, *args, **kwargs):
2012 self._testcase = testcase
2013 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002014
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002015 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08002016 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002017 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002018 finally:
2019 # Open a bunch of file descriptors and verify that
2020 # none of them are the same as the ones the Popen
2021 # instance is using for stdin/stdout/stderr.
2022 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2023 for _ in range(8)]
2024 try:
2025 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002026 self._testcase.assertNotIn(
2027 fd, (self.stdin.fileno(), self.stdout.fileno(),
2028 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002029 msg="At least one fd was closed early.")
2030 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002031 for fd in devzero_fds:
2032 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002033
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002034 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2035 def test_preexec_errpipe_does_not_double_close_pipes(self):
2036 """Issue16140: Don't double close pipes on preexec error."""
2037
2038 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002039 raise subprocess.SubprocessError(
2040 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002041
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002042 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002043 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002044 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002045 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2046 stderr=subprocess.PIPE, preexec_fn=raise_it)
2047
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002048 def test_preexec_gc_module_failure(self):
2049 # This tests the code that disables garbage collection if the child
2050 # process will execute any Python.
2051 def raise_runtime_error():
2052 raise RuntimeError("this shouldn't escape")
2053 enabled = gc.isenabled()
2054 orig_gc_disable = gc.disable
2055 orig_gc_isenabled = gc.isenabled
2056 try:
2057 gc.disable()
2058 self.assertFalse(gc.isenabled())
2059 subprocess.call([sys.executable, '-c', ''],
2060 preexec_fn=lambda: None)
2061 self.assertFalse(gc.isenabled(),
2062 "Popen enabled gc when it shouldn't.")
2063
2064 gc.enable()
2065 self.assertTrue(gc.isenabled())
2066 subprocess.call([sys.executable, '-c', ''],
2067 preexec_fn=lambda: None)
2068 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2069
2070 gc.disable = raise_runtime_error
2071 self.assertRaises(RuntimeError, subprocess.Popen,
2072 [sys.executable, '-c', ''],
2073 preexec_fn=lambda: None)
2074
2075 del gc.isenabled # force an AttributeError
2076 self.assertRaises(AttributeError, subprocess.Popen,
2077 [sys.executable, '-c', ''],
2078 preexec_fn=lambda: None)
2079 finally:
2080 gc.disable = orig_gc_disable
2081 gc.isenabled = orig_gc_isenabled
2082 if not enabled:
2083 gc.disable()
2084
Martin Panterf7fdbda2015-12-05 09:51:52 +00002085 @unittest.skipIf(
2086 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002087 def test_preexec_fork_failure(self):
2088 # The internal code did not preserve the previous exception when
2089 # re-enabling garbage collection
2090 try:
2091 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2092 except ImportError as err:
2093 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2094 limits = getrlimit(RLIMIT_NPROC)
2095 [_, hard] = limits
2096 setrlimit(RLIMIT_NPROC, (0, hard))
2097 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002098 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002099 subprocess.call([sys.executable, '-c', ''],
2100 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002101 except BlockingIOError:
2102 # Forking should raise EAGAIN, translated to BlockingIOError
2103 pass
2104 else:
2105 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002106
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002107 def test_args_string(self):
2108 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002109 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002110 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002111 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002112 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002113 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2114 sys.executable)
2115 os.chmod(fname, 0o700)
2116 p = subprocess.Popen(fname)
2117 p.wait()
2118 os.remove(fname)
2119 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002120
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002121 def test_invalid_args(self):
2122 # invalid arguments should raise ValueError
2123 self.assertRaises(ValueError, subprocess.call,
2124 [sys.executable, "-c",
2125 "import sys; sys.exit(47)"],
2126 startupinfo=47)
2127 self.assertRaises(ValueError, subprocess.call,
2128 [sys.executable, "-c",
2129 "import sys; sys.exit(47)"],
2130 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002131
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002132 def test_shell_sequence(self):
2133 # Run command through the shell (sequence)
2134 newenv = os.environ.copy()
2135 newenv["FRUIT"] = "apple"
2136 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2137 stdout=subprocess.PIPE,
2138 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002139 with p:
2140 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002141
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002142 def test_shell_string(self):
2143 # Run command through the shell (string)
2144 newenv = os.environ.copy()
2145 newenv["FRUIT"] = "apple"
2146 p = subprocess.Popen("echo $FRUIT", shell=1,
2147 stdout=subprocess.PIPE,
2148 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002149 with p:
2150 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002151
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002152 def test_call_string(self):
2153 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002154 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002155 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002156 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002157 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002158 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2159 sys.executable)
2160 os.chmod(fname, 0o700)
2161 rc = subprocess.call(fname)
2162 os.remove(fname)
2163 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002164
Stefan Krah9542cc62010-07-19 14:20:53 +00002165 def test_specific_shell(self):
2166 # Issue #9265: Incorrect name passed as arg[0].
2167 shells = []
2168 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2169 for name in ['bash', 'ksh']:
2170 sh = os.path.join(prefix, name)
2171 if os.path.isfile(sh):
2172 shells.append(sh)
2173 if not shells: # Will probably work for any shell but csh.
2174 self.skipTest("bash or ksh required for this test")
2175 sh = '/bin/sh'
2176 if os.path.isfile(sh) and not os.path.islink(sh):
2177 # Test will fail if /bin/sh is a symlink to csh.
2178 shells.append(sh)
2179 for sh in shells:
2180 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2181 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002182 with p:
2183 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002184
Florent Xicluna4886d242010-03-08 13:27:26 +00002185 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002186 # Do not inherit file handles from the parent.
2187 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002188 # Also set the SIGINT handler to the default to make sure it's not
2189 # being ignored (some tests rely on that.)
2190 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2191 try:
2192 p = subprocess.Popen([sys.executable, "-c", """if 1:
2193 import sys, time
2194 sys.stdout.write('x\\n')
2195 sys.stdout.flush()
2196 time.sleep(30)
2197 """],
2198 close_fds=True,
2199 stdin=subprocess.PIPE,
2200 stdout=subprocess.PIPE,
2201 stderr=subprocess.PIPE)
2202 finally:
2203 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002204 # Wait for the interpreter to be completely initialized before
2205 # sending any signal.
2206 p.stdout.read(1)
2207 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002208 return p
2209
Charles-François Natali53221e32013-01-12 16:52:20 +01002210 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2211 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002212 def _kill_dead_process(self, method, *args):
2213 # Do not inherit file handles from the parent.
2214 # It should fix failures on some platforms.
2215 p = subprocess.Popen([sys.executable, "-c", """if 1:
2216 import sys, time
2217 sys.stdout.write('x\\n')
2218 sys.stdout.flush()
2219 """],
2220 close_fds=True,
2221 stdin=subprocess.PIPE,
2222 stdout=subprocess.PIPE,
2223 stderr=subprocess.PIPE)
2224 # Wait for the interpreter to be completely initialized before
2225 # sending any signal.
2226 p.stdout.read(1)
2227 # The process should end after this
2228 time.sleep(1)
2229 # This shouldn't raise even though the child is now dead
2230 getattr(p, method)(*args)
2231 p.communicate()
2232
Florent Xicluna4886d242010-03-08 13:27:26 +00002233 def test_send_signal(self):
2234 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002235 _, stderr = p.communicate()
2236 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002237 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002238
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002239 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002240 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002241 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002242 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002243 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002244
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002245 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002246 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002247 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002248 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002249 self.assertEqual(p.wait(), -signal.SIGTERM)
2250
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002251 def test_send_signal_dead(self):
2252 # Sending a signal to a dead process
2253 self._kill_dead_process('send_signal', signal.SIGINT)
2254
2255 def test_kill_dead(self):
2256 # Killing a dead process
2257 self._kill_dead_process('kill')
2258
2259 def test_terminate_dead(self):
2260 # Terminating a dead process
2261 self._kill_dead_process('terminate')
2262
Victor Stinnerdaf45552013-08-28 00:53:59 +02002263 def _save_fds(self, save_fds):
2264 fds = []
2265 for fd in save_fds:
2266 inheritable = os.get_inheritable(fd)
2267 saved = os.dup(fd)
2268 fds.append((fd, saved, inheritable))
2269 return fds
2270
2271 def _restore_fds(self, fds):
2272 for fd, saved, inheritable in fds:
2273 os.dup2(saved, fd, inheritable=inheritable)
2274 os.close(saved)
2275
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002276 def check_close_std_fds(self, fds):
2277 # Issue #9905: test that subprocess pipes still work properly with
2278 # some standard fds closed
2279 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002280 saved_fds = self._save_fds(fds)
2281 for fd, saved, inheritable in saved_fds:
2282 if fd == 0:
2283 stdin = saved
2284 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002285 try:
2286 for fd in fds:
2287 os.close(fd)
2288 out, err = subprocess.Popen([sys.executable, "-c",
2289 'import sys;'
2290 'sys.stdout.write("apple");'
2291 'sys.stdout.flush();'
2292 'sys.stderr.write("orange")'],
2293 stdin=stdin,
2294 stdout=subprocess.PIPE,
2295 stderr=subprocess.PIPE).communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002296 self.assertEqual(out, b'apple')
2297 self.assertEqual(err, b'orange')
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002298 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002299 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002300
2301 def test_close_fd_0(self):
2302 self.check_close_std_fds([0])
2303
2304 def test_close_fd_1(self):
2305 self.check_close_std_fds([1])
2306
2307 def test_close_fd_2(self):
2308 self.check_close_std_fds([2])
2309
2310 def test_close_fds_0_1(self):
2311 self.check_close_std_fds([0, 1])
2312
2313 def test_close_fds_0_2(self):
2314 self.check_close_std_fds([0, 2])
2315
2316 def test_close_fds_1_2(self):
2317 self.check_close_std_fds([1, 2])
2318
2319 def test_close_fds_0_1_2(self):
2320 # Issue #10806: test that subprocess pipes still work properly with
2321 # all standard fds closed.
2322 self.check_close_std_fds([0, 1, 2])
2323
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002324 def test_small_errpipe_write_fd(self):
2325 """Issue #15798: Popen should work when stdio fds are available."""
2326 new_stdin = os.dup(0)
2327 new_stdout = os.dup(1)
2328 try:
2329 os.close(0)
2330 os.close(1)
2331
2332 # Side test: if errpipe_write fails to have its CLOEXEC
2333 # flag set this should cause the parent to think the exec
2334 # failed. Extremely unlikely: everyone supports CLOEXEC.
2335 subprocess.Popen([
2336 sys.executable, "-c",
2337 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2338 finally:
2339 # Restore original stdin and stdout
2340 os.dup2(new_stdin, 0)
2341 os.dup2(new_stdout, 1)
2342 os.close(new_stdin)
2343 os.close(new_stdout)
2344
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002345 def test_remapping_std_fds(self):
2346 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002347 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002348 try:
2349 temp_fds = [fd for fd, fname in temps]
2350
2351 # unlink the files -- we won't need to reopen them
2352 for fd, fname in temps:
2353 os.unlink(fname)
2354
2355 # write some data to what will become stdin, and rewind
2356 os.write(temp_fds[1], b"STDIN")
2357 os.lseek(temp_fds[1], 0, 0)
2358
2359 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002360 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002361 try:
2362 # duplicate the file objects over the standard fd's
2363 for fd, temp_fd in enumerate(temp_fds):
2364 os.dup2(temp_fd, fd)
2365
2366 # now use those files in the "wrong" order, so that subprocess
2367 # has to rearrange them in the child
2368 p = subprocess.Popen([sys.executable, "-c",
2369 'import sys; got = sys.stdin.read();'
2370 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2371 stdin=temp_fds[1],
2372 stdout=temp_fds[2],
2373 stderr=temp_fds[0])
2374 p.wait()
2375 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002376 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002377
2378 for fd in temp_fds:
2379 os.lseek(fd, 0, 0)
2380
2381 out = os.read(temp_fds[2], 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002382 err = os.read(temp_fds[0], 1024).strip()
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002383 self.assertEqual(out, b"got STDIN")
2384 self.assertEqual(err, b"err")
2385
2386 finally:
2387 for fd in temp_fds:
2388 os.close(fd)
2389
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002390 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2391 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002392 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002393 temp_fds = [fd for fd, fname in temps]
2394 try:
2395 # unlink the files -- we won't need to reopen them
2396 for fd, fname in temps:
2397 os.unlink(fname)
2398
2399 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002400 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002401 try:
2402 # duplicate the temp files over the standard fd's 0, 1, 2
2403 for fd, temp_fd in enumerate(temp_fds):
2404 os.dup2(temp_fd, fd)
2405
2406 # write some data to what will become stdin, and rewind
2407 os.write(stdin_no, b"STDIN")
2408 os.lseek(stdin_no, 0, 0)
2409
2410 # now use those files in the given order, so that subprocess
2411 # has to rearrange them in the child
2412 p = subprocess.Popen([sys.executable, "-c",
2413 'import sys; got = sys.stdin.read();'
2414 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2415 stdin=stdin_no,
2416 stdout=stdout_no,
2417 stderr=stderr_no)
2418 p.wait()
2419
2420 for fd in temp_fds:
2421 os.lseek(fd, 0, 0)
2422
2423 out = os.read(stdout_no, 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002424 err = os.read(stderr_no, 1024).strip()
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002425 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002426 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002427
2428 self.assertEqual(out, b"got STDIN")
2429 self.assertEqual(err, b"err")
2430
2431 finally:
2432 for fd in temp_fds:
2433 os.close(fd)
2434
2435 # When duping fds, if there arises a situation where one of the fds is
2436 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2437 # This tests all combinations of this.
2438 def test_swap_fds(self):
2439 self.check_swap_fds(0, 1, 2)
2440 self.check_swap_fds(0, 2, 1)
2441 self.check_swap_fds(1, 0, 2)
2442 self.check_swap_fds(1, 2, 0)
2443 self.check_swap_fds(2, 0, 1)
2444 self.check_swap_fds(2, 1, 0)
2445
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002446 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2447 saved_fds = self._save_fds(range(3))
2448 try:
2449 for from_fd in from_fds:
2450 with tempfile.TemporaryFile() as f:
2451 os.dup2(f.fileno(), from_fd)
2452
2453 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2454 os.close(fd_to_close)
2455
2456 arg_names = ['stdin', 'stdout', 'stderr']
2457 kwargs = {}
2458 for from_fd, to_fd in zip(from_fds, to_fds):
2459 kwargs[arg_names[to_fd]] = from_fd
2460
2461 code = textwrap.dedent(r'''
2462 import os, sys
2463 skipped_fd = int(sys.argv[1])
2464 for fd in range(3):
2465 if fd != skipped_fd:
2466 os.write(fd, str(fd).encode('ascii'))
2467 ''')
2468
2469 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2470
2471 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2472 **kwargs)
2473 self.assertEqual(rc, 0)
2474
2475 for from_fd, to_fd in zip(from_fds, to_fds):
2476 os.lseek(from_fd, 0, os.SEEK_SET)
2477 read_bytes = os.read(from_fd, 1024)
2478 read_fds = list(map(int, read_bytes.decode('ascii')))
2479 msg = textwrap.dedent(f"""
2480 When testing {from_fds} to {to_fds} redirection,
2481 parent descriptor {from_fd} got redirected
2482 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2483 """)
2484 self.assertEqual([to_fd], read_fds, msg)
2485 finally:
2486 self._restore_fds(saved_fds)
2487
2488 # Check that subprocess can remap std fds correctly even
2489 # if one of them is closed (#32844).
2490 def test_swap_std_fds_with_one_closed(self):
2491 for from_fds in itertools.combinations(range(3), 2):
2492 for to_fds in itertools.permutations(range(3), 2):
2493 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2494
Victor Stinner13bb71c2010-04-23 21:41:56 +00002495 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002496 def prepare():
2497 raise ValueError("surrogate:\uDCff")
2498
2499 try:
2500 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002501 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002502 preexec_fn=prepare)
2503 except ValueError as err:
2504 # Pure Python implementations keeps the message
2505 self.assertIsNone(subprocess._posixsubprocess)
2506 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002507 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002508 # _posixsubprocess uses a default message
2509 self.assertIsNotNone(subprocess._posixsubprocess)
2510 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2511 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002512 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002513
Victor Stinner13bb71c2010-04-23 21:41:56 +00002514 def test_undecodable_env(self):
2515 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002516 encoded_value = value.encode("ascii", "surrogateescape")
2517
Victor Stinner13bb71c2010-04-23 21:41:56 +00002518 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002519 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002520 env = os.environ.copy()
2521 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002522 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002523 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002524 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002525 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002526 stdout = subprocess.check_output(
2527 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002528 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002529 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002530 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002531
2532 # test bytes
2533 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002534 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002535 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002536 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002537 stdout = subprocess.check_output(
2538 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002539 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002540 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002541 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002542
Victor Stinnerb745a742010-05-18 17:17:23 +00002543 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002544 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2545 args = list(ZERO_RETURN_CMD[1:])
2546 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002547 program = os.fsencode(program)
2548
2549 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002550 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002551 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002552
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002553 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002554 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002555 exitcode = subprocess.call(cmd, shell=True)
2556 self.assertEqual(exitcode, 0)
2557
Victor Stinnerb745a742010-05-18 17:17:23 +00002558 # bytes program, unicode PATH
2559 env = os.environ.copy()
2560 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002561 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002562 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002563
2564 # bytes program, bytes PATH
2565 envb = os.environb.copy()
2566 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002567 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002568 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002569
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002570 def test_pipe_cloexec(self):
2571 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2572 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2573
2574 p1 = subprocess.Popen([sys.executable, sleeper],
2575 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2576 stderr=subprocess.PIPE, close_fds=False)
2577
2578 self.addCleanup(p1.communicate, b'')
2579
2580 p2 = subprocess.Popen([sys.executable, fd_status],
2581 stdout=subprocess.PIPE, close_fds=False)
2582
2583 output, error = p2.communicate()
2584 result_fds = set(map(int, output.split(b',')))
2585 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2586 p1.stderr.fileno()])
2587
2588 self.assertFalse(result_fds & unwanted_fds,
2589 "Expected no fds from %r to be open in child, "
2590 "found %r" %
2591 (unwanted_fds, result_fds & unwanted_fds))
2592
2593 def test_pipe_cloexec_real_tools(self):
2594 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2595 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2596
2597 subdata = b'zxcvbn'
2598 data = subdata * 4 + b'\n'
2599
2600 p1 = subprocess.Popen([sys.executable, qcat],
2601 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2602 close_fds=False)
2603
2604 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2605 stdin=p1.stdout, stdout=subprocess.PIPE,
2606 close_fds=False)
2607
2608 self.addCleanup(p1.wait)
2609 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002610 def kill_p1():
2611 try:
2612 p1.terminate()
2613 except ProcessLookupError:
2614 pass
2615 def kill_p2():
2616 try:
2617 p2.terminate()
2618 except ProcessLookupError:
2619 pass
2620 self.addCleanup(kill_p1)
2621 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002622
2623 p1.stdin.write(data)
2624 p1.stdin.close()
2625
2626 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2627
2628 self.assertTrue(readfiles, "The child hung")
2629 self.assertEqual(p2.stdout.read(), data)
2630
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002631 p1.stdout.close()
2632 p2.stdout.close()
2633
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002634 def test_close_fds(self):
2635 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2636
2637 fds = os.pipe()
2638 self.addCleanup(os.close, fds[0])
2639 self.addCleanup(os.close, fds[1])
2640
2641 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002642 # add a bunch more fds
2643 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002644 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002645 self.addCleanup(os.close, fd)
2646 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002647
Victor Stinnerdaf45552013-08-28 00:53:59 +02002648 for fd in open_fds:
2649 os.set_inheritable(fd, True)
2650
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002651 p = subprocess.Popen([sys.executable, fd_status],
2652 stdout=subprocess.PIPE, close_fds=False)
2653 output, ignored = p.communicate()
2654 remaining_fds = set(map(int, output.split(b',')))
2655
2656 self.assertEqual(remaining_fds & open_fds, open_fds,
2657 "Some fds were closed")
2658
2659 p = subprocess.Popen([sys.executable, fd_status],
2660 stdout=subprocess.PIPE, close_fds=True)
2661 output, ignored = p.communicate()
2662 remaining_fds = set(map(int, output.split(b',')))
2663
2664 self.assertFalse(remaining_fds & open_fds,
2665 "Some fds were left open")
2666 self.assertIn(1, remaining_fds, "Subprocess failed")
2667
Gregory P. Smith8facece2012-01-21 14:01:08 -08002668 # Keep some of the fd's we opened open in the subprocess.
2669 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2670 fds_to_keep = set(open_fds.pop() for _ in range(8))
2671 p = subprocess.Popen([sys.executable, fd_status],
2672 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002673 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002674 output, ignored = p.communicate()
2675 remaining_fds = set(map(int, output.split(b',')))
2676
izbyshev2d8f0632017-12-19 03:26:49 +07002677 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002678 "Some fds not in pass_fds were left open")
2679 self.assertIn(1, remaining_fds, "Subprocess failed")
2680
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002681
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002682 @unittest.skipIf(sys.platform.startswith("freebsd") and
2683 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2684 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002685 def test_close_fds_when_max_fd_is_lowered(self):
2686 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2687 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2688
Gregory P. Smith634aa682014-06-15 17:51:04 -07002689 # This launches the meat of the test in a child process to
2690 # avoid messing with the larger unittest processes maximum
2691 # number of file descriptors.
2692 # This process launches:
2693 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2694 # a bunch of high open fds above the new lower rlimit.
2695 # Those are reported via stdout before launching a new
2696 # process with close_fds=False to run the actual test:
2697 # +--> The TEST: This one launches a fd_status.py
2698 # subprocess with close_fds=True so we can find out if
2699 # any of the fds above the lowered rlimit are still open.
2700 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2701 '''
2702 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002703 open_fds = set()
2704 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002705 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002706 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002707 open_fds.add(fd)
2708
2709 # Leave a two pairs of low ones available for use by the
2710 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002711 # We also leave 10 more open as some Python buildbots run into
2712 # "too many open files" errors during the test if we do not.
2713 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002714 os.close(fd)
2715 open_fds.remove(fd)
2716
2717 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002718 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002719 os.set_inheritable(fd, True)
2720
2721 max_fd_open = max(open_fds)
2722
Gregory P. Smith634aa682014-06-15 17:51:04 -07002723 # Communicate the open_fds to the parent unittest.TestCase process.
2724 print(','.join(map(str, sorted(open_fds))))
2725 sys.stdout.flush()
2726
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002727 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2728 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002729 # 29 is lower than the highest fds we are leaving open.
2730 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002731 # Launch a new Python interpreter with our low fd rlim_cur that
2732 # inherits open fds above that limit. It then uses subprocess
2733 # with close_fds=True to get a report of open fds in the child.
2734 # An explicit list of fds to check is passed to fd_status.py as
2735 # letting fd_status rely on its default logic would miss the
2736 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002737 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002738 [sys.executable, '-c',
2739 textwrap.dedent("""
2740 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002741 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002742 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002743 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002744 """.format(max_fd=max_fd_open+1))],
2745 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002746 finally:
2747 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002748 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002749
2750 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002751 output_lines = output.splitlines()
2752 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002753 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002754 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2755 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002756
Gregory P. Smith634aa682014-06-15 17:51:04 -07002757 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002758 msg="Some fds were left open.")
2759
2760
Victor Stinner88701e22011-06-01 13:13:04 +02002761 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2762 # descriptor of a pipe closed in the parent process is valid in the
2763 # child process according to fstat(), but the mode of the file
2764 # descriptor is invalid, and read or write raise an error.
2765 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002766 def test_pass_fds(self):
2767 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2768
2769 open_fds = set()
2770
2771 for x in range(5):
2772 fds = os.pipe()
2773 self.addCleanup(os.close, fds[0])
2774 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002775 os.set_inheritable(fds[0], True)
2776 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002777 open_fds.update(fds)
2778
2779 for fd in open_fds:
2780 p = subprocess.Popen([sys.executable, fd_status],
2781 stdout=subprocess.PIPE, close_fds=True,
2782 pass_fds=(fd, ))
2783 output, ignored = p.communicate()
2784
2785 remaining_fds = set(map(int, output.split(b',')))
2786 to_be_closed = open_fds - {fd}
2787
2788 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2789 self.assertFalse(remaining_fds & to_be_closed,
2790 "fd to be closed passed")
2791
2792 # pass_fds overrides close_fds with a warning.
2793 with self.assertWarns(RuntimeWarning) as context:
2794 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002795 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002796 close_fds=False, pass_fds=(fd, )))
2797 self.assertIn('overriding close_fds', str(context.warning))
2798
Victor Stinnerdaf45552013-08-28 00:53:59 +02002799 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002800 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002801
2802 inheritable, non_inheritable = os.pipe()
2803 self.addCleanup(os.close, inheritable)
2804 self.addCleanup(os.close, non_inheritable)
2805 os.set_inheritable(inheritable, True)
2806 os.set_inheritable(non_inheritable, False)
2807 pass_fds = (inheritable, non_inheritable)
2808 args = [sys.executable, script]
2809 args += list(map(str, pass_fds))
2810
2811 p = subprocess.Popen(args,
2812 stdout=subprocess.PIPE, close_fds=True,
2813 pass_fds=pass_fds)
2814 output, ignored = p.communicate()
2815 fds = set(map(int, output.split(b',')))
2816
2817 # the inheritable file descriptor must be inherited, so its inheritable
2818 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002819 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002820
2821 # inheritable flag must not be changed in the parent process
2822 self.assertEqual(os.get_inheritable(inheritable), True)
2823 self.assertEqual(os.get_inheritable(non_inheritable), False)
2824
Gregory P. Smithce344102018-09-10 17:46:22 -07002825
2826 # bpo-32270: Ensure that descriptors specified in pass_fds
2827 # are inherited even if they are used in redirections.
2828 # Contributed by @izbyshev.
2829 def test_pass_fds_redirected(self):
2830 """Regression test for https://bugs.python.org/issue32270."""
2831 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2832 pass_fds = []
2833 for _ in range(2):
2834 fd = os.open(os.devnull, os.O_RDWR)
2835 self.addCleanup(os.close, fd)
2836 pass_fds.append(fd)
2837
2838 stdout_r, stdout_w = os.pipe()
2839 self.addCleanup(os.close, stdout_r)
2840 self.addCleanup(os.close, stdout_w)
2841 pass_fds.insert(1, stdout_w)
2842
2843 with subprocess.Popen([sys.executable, fd_status],
2844 stdin=pass_fds[0],
2845 stdout=pass_fds[1],
2846 stderr=pass_fds[2],
2847 close_fds=True,
2848 pass_fds=pass_fds):
2849 output = os.read(stdout_r, 1024)
2850 fds = {int(num) for num in output.split(b',')}
2851
2852 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2853
2854
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002855 def test_stdout_stdin_are_single_inout_fd(self):
2856 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002857 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002858 stdout=inout, stdin=inout)
2859 p.wait()
2860
2861 def test_stdout_stderr_are_single_inout_fd(self):
2862 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002863 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002864 stdout=inout, stderr=inout)
2865 p.wait()
2866
2867 def test_stderr_stdin_are_single_inout_fd(self):
2868 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002869 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002870 stderr=inout, stdin=inout)
2871 p.wait()
2872
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002873 def test_wait_when_sigchild_ignored(self):
2874 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2875 sigchild_ignore = support.findfile("sigchild_ignore.py",
2876 subdir="subprocessdata")
2877 p = subprocess.Popen([sys.executable, sigchild_ignore],
2878 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2879 stdout, stderr = p.communicate()
2880 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002881 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002882 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002883
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002884 def test_select_unbuffered(self):
2885 # Issue #11459: bufsize=0 should really set the pipes as
2886 # unbuffered (and therefore let select() work properly).
Hai Shi0c4f0f32020-06-30 21:46:31 +08002887 select = import_helper.import_module("select")
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002888 p = subprocess.Popen([sys.executable, "-c",
2889 'import sys;'
2890 'sys.stdout.write("apple")'],
2891 stdout=subprocess.PIPE,
2892 bufsize=0)
2893 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002894 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002895 try:
2896 self.assertEqual(f.read(4), b"appl")
2897 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2898 finally:
2899 p.wait()
2900
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002901 def test_zombie_fast_process_del(self):
2902 # Issue #12650: on Unix, if Popen.__del__() was called before the
2903 # process exited, it wouldn't be added to subprocess._active, and would
2904 # remain a zombie.
2905 # spawn a Popen, and delete its reference before it exits
2906 p = subprocess.Popen([sys.executable, "-c",
2907 'import sys, time;'
2908 'time.sleep(0.2)'],
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
Hai Shi0c4f0f32020-06-30 21:46:31 +08002915 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02002916 p = None
2917
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002918 if mswindows:
2919 # subprocess._active is not used on Windows and is set to None.
2920 self.assertIsNone(subprocess._active)
2921 else:
2922 # check that p is in the active processes list
2923 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002924
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002925 def test_leak_fast_process_del_killed(self):
2926 # Issue #12650: on Unix, if Popen.__del__() was called before the
2927 # process exited, and the process got killed by a signal, it would never
2928 # be removed from subprocess._active, which triggered a FD and memory
2929 # leak.
2930 # spawn a Popen, delete its reference and kill it
2931 p = subprocess.Popen([sys.executable, "-c",
2932 'import time;'
2933 'time.sleep(3)'],
2934 stdout=subprocess.PIPE,
2935 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002936 self.addCleanup(p.stdout.close)
2937 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002938 ident = id(p)
2939 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08002940 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02002941 p = None
2942
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002943 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002944 if mswindows:
2945 # subprocess._active is not used on Windows and is set to None.
2946 self.assertIsNone(subprocess._active)
2947 else:
2948 # check that p is in the active processes list
2949 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002950
2951 # let some time for the process to exit, and create a new Popen: this
2952 # should trigger the wait() of p
2953 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002954 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002955 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002956 stdout=subprocess.PIPE,
2957 stderr=subprocess.PIPE) as proc:
2958 pass
2959 # p should have been wait()ed on, and removed from the _active list
2960 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002961 if mswindows:
2962 # subprocess._active is not used on Windows and is set to None.
2963 self.assertIsNone(subprocess._active)
2964 else:
2965 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002966
Charles-François Natali249cdc32013-08-25 18:24:45 +02002967 def test_close_fds_after_preexec(self):
2968 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2969
2970 # this FD is used as dup2() target by preexec_fn, and should be closed
2971 # in the child process
2972 fd = os.dup(1)
2973 self.addCleanup(os.close, fd)
2974
2975 p = subprocess.Popen([sys.executable, fd_status],
2976 stdout=subprocess.PIPE, close_fds=True,
2977 preexec_fn=lambda: os.dup2(1, fd))
2978 output, ignored = p.communicate()
2979
2980 remaining_fds = set(map(int, output.split(b',')))
2981
2982 self.assertNotIn(fd, remaining_fds)
2983
Victor Stinner8f437aa2014-10-05 17:25:19 +02002984 @support.cpython_only
2985 def test_fork_exec(self):
2986 # Issue #22290: fork_exec() must not crash on memory allocation failure
2987 # or other errors
2988 import _posixsubprocess
2989 gc_enabled = gc.isenabled()
2990 try:
2991 # Use a preexec function and enable the garbage collector
2992 # to force fork_exec() to re-enable the garbage collector
2993 # on error.
2994 func = lambda: None
2995 gc.enable()
2996
Victor Stinner8f437aa2014-10-05 17:25:19 +02002997 for args, exe_list, cwd, env_list in (
2998 (123, [b"exe"], None, [b"env"]),
2999 ([b"arg"], 123, None, [b"env"]),
3000 ([b"arg"], [b"exe"], 123, [b"env"]),
3001 ([b"arg"], [b"exe"], None, 123),
3002 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07003003 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02003004 _posixsubprocess.fork_exec(
3005 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003006 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02003007 -1, -1, -1, -1,
3008 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003009 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003010 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003011 func)
3012 # Attempt to prevent
3013 # "TypeError: fork_exec() takes exactly N arguments (M given)"
3014 # from passing the test. More refactoring to have us start
3015 # with a valid *args list, confirm a good call with that works
3016 # before mutating it in various ways to ensure that bad calls
3017 # with individual arg type errors raise a typeerror would be
3018 # ideal. Saving that for a future PR...
3019 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02003020 finally:
3021 if not gc_enabled:
3022 gc.disable()
3023
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003024 @support.cpython_only
3025 def test_fork_exec_sorted_fd_sanity_check(self):
3026 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3027 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003028 class BadInt:
3029 first = True
3030 def __init__(self, value):
3031 self.value = value
3032 def __int__(self):
3033 if self.first:
3034 self.first = False
3035 return self.value
3036 raise ValueError
3037
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003038 gc_enabled = gc.isenabled()
3039 try:
3040 gc.enable()
3041
3042 for fds_to_keep in (
3043 (-1, 2, 3, 4, 5), # Negative number.
3044 ('str', 4), # Not an int.
3045 (18, 23, 42, 2**63), # Out of range.
3046 (5, 4), # Not sorted.
3047 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003048 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003049 ):
3050 with self.assertRaises(
3051 ValueError,
3052 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3053 _posixsubprocess.fork_exec(
3054 [b"false"], [b"false"],
3055 True, fds_to_keep, None, [b"env"],
3056 -1, -1, -1, -1,
3057 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003058 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003059 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003060 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003061 self.assertIn('fds_to_keep', str(c.exception))
3062 finally:
3063 if not gc_enabled:
3064 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003065
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003066 def test_communicate_BrokenPipeError_stdin_close(self):
3067 # By not setting stdout or stderr or a timeout we force the fast path
3068 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003069 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003070 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3071 mock_proc_stdin.close.side_effect = BrokenPipeError
3072 proc.communicate() # Should swallow BrokenPipeError from close.
3073 mock_proc_stdin.close.assert_called_with()
3074
3075 def test_communicate_BrokenPipeError_stdin_write(self):
3076 # By not setting stdout or stderr or a timeout we force the fast path
3077 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003078 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003079 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3080 mock_proc_stdin.write.side_effect = BrokenPipeError
3081 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3082 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3083 mock_proc_stdin.close.assert_called_once_with()
3084
3085 def test_communicate_BrokenPipeError_stdin_flush(self):
3086 # Setting stdin and stdout forces the ._communicate() code path.
3087 # python -h exits faster than python -c pass (but spams stdout).
3088 proc = subprocess.Popen([sys.executable, '-h'],
3089 stdin=subprocess.PIPE,
3090 stdout=subprocess.PIPE)
3091 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3092 open(os.devnull, 'wb') as dev_null:
3093 mock_proc_stdin.flush.side_effect = BrokenPipeError
3094 # because _communicate registers a selector using proc.stdin...
3095 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3096 # _communicate() should swallow BrokenPipeError from flush.
3097 proc.communicate(b'stuff')
3098 mock_proc_stdin.flush.assert_called_once_with()
3099
3100 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3101 # Setting stdin and stdout forces the ._communicate() code path.
3102 # python -h exits faster than python -c pass (but spams stdout).
3103 proc = subprocess.Popen([sys.executable, '-h'],
3104 stdin=subprocess.PIPE,
3105 stdout=subprocess.PIPE)
3106 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3107 mock_proc_stdin.close.side_effect = BrokenPipeError
3108 # _communicate() should swallow BrokenPipeError from close.
3109 proc.communicate(timeout=999)
3110 mock_proc_stdin.close.assert_called_once_with()
3111
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003112 @unittest.skipUnless(_testcapi is not None
3113 and hasattr(_testcapi, 'W_STOPCODE'),
3114 'need _testcapi.W_STOPCODE')
3115 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003116 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003117 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003118 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003119
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003120 # Wait until the real process completes to avoid zombie process
Victor Stinner278c1e12020-03-31 20:08:12 +02003121 support.wait_process(proc.pid, exitcode=0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003122
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003123 status = _testcapi.W_STOPCODE(3)
Victor Stinner278c1e12020-03-31 20:08:12 +02003124 with mock.patch('subprocess.os.waitpid', return_value=(proc.pid, status)):
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003125 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003126
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003127 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003128
Victor Stinnere85a3052020-01-15 17:38:55 +01003129 def test_send_signal_race(self):
3130 # bpo-38630: send_signal() must poll the process exit status to reduce
3131 # the risk of sending the signal to the wrong process.
3132 proc = subprocess.Popen(ZERO_RETURN_CMD)
3133
3134 # wait until the process completes without using the Popen APIs.
Victor Stinner278c1e12020-03-31 20:08:12 +02003135 support.wait_process(proc.pid, exitcode=0)
Victor Stinnere85a3052020-01-15 17:38:55 +01003136
3137 # returncode is still None but the process completed.
3138 self.assertIsNone(proc.returncode)
3139
3140 with mock.patch("os.kill") as mock_kill:
3141 proc.send_signal(signal.SIGTERM)
3142
3143 # send_signal() didn't call os.kill() since the process already
3144 # completed.
3145 mock_kill.assert_not_called()
3146
3147 # Don't check the returncode value: the test reads the exit status,
3148 # so Popen failed to read it and uses a default returncode instead.
3149 self.assertIsNotNone(proc.returncode)
3150
Alex Rebertd3ae95e2020-01-22 18:28:31 -05003151 def test_communicate_repeated_call_after_stdout_close(self):
3152 proc = subprocess.Popen([sys.executable, '-c',
3153 'import os, time; os.close(1), time.sleep(2)'],
3154 stdout=subprocess.PIPE)
3155 while True:
3156 try:
3157 proc.communicate(timeout=0.1)
3158 return
3159 except subprocess.TimeoutExpired:
3160 pass
3161
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003162
Victor Stinner937ee9e2018-06-26 02:11:06 +02003163@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003164class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003165
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003166 def test_startupinfo(self):
3167 # startupinfo argument
3168 # We uses hardcoded constants, because we do not want to
3169 # depend on win32all.
3170 STARTF_USESHOWWINDOW = 1
3171 SW_MAXIMIZE = 3
3172 startupinfo = subprocess.STARTUPINFO()
3173 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3174 startupinfo.wShowWindow = SW_MAXIMIZE
3175 # Since Python is a console process, it won't be affected
3176 # by wShowWindow, but the argument should be silently
3177 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003178 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003179 startupinfo=startupinfo)
3180
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303181 def test_startupinfo_keywords(self):
3182 # startupinfo argument
3183 # We use hardcoded constants, because we do not want to
3184 # depend on win32all.
3185 STARTF_USERSHOWWINDOW = 1
3186 SW_MAXIMIZE = 3
3187 startupinfo = subprocess.STARTUPINFO(
3188 dwFlags=STARTF_USERSHOWWINDOW,
3189 wShowWindow=SW_MAXIMIZE
3190 )
3191 # Since Python is a console process, it won't be affected
3192 # by wShowWindow, but the argument should be silently
3193 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003194 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303195 startupinfo=startupinfo)
3196
Victor Stinner483422f2018-07-05 22:54:17 +02003197 def test_startupinfo_copy(self):
3198 # bpo-34044: Popen must not modify input STARTUPINFO structure
3199 startupinfo = subprocess.STARTUPINFO()
3200 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3201 startupinfo.wShowWindow = subprocess.SW_HIDE
3202
3203 # Call Popen() twice with the same startupinfo object to make sure
3204 # that it's not modified
3205 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003206 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003207 with open(os.devnull, 'w') as null:
3208 proc = subprocess.Popen(cmd,
3209 stdout=null,
3210 stderr=subprocess.STDOUT,
3211 startupinfo=startupinfo)
3212 with proc:
3213 proc.communicate()
3214 self.assertEqual(proc.returncode, 0)
3215
3216 self.assertEqual(startupinfo.dwFlags,
3217 subprocess.STARTF_USESHOWWINDOW)
3218 self.assertIsNone(startupinfo.hStdInput)
3219 self.assertIsNone(startupinfo.hStdOutput)
3220 self.assertIsNone(startupinfo.hStdError)
3221 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3222 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3223
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003224 def test_creationflags(self):
3225 # creationflags argument
3226 CREATE_NEW_CONSOLE = 16
3227 sys.stderr.write(" a DOS box should flash briefly ...\n")
3228 subprocess.call(sys.executable +
3229 ' -c "import time; time.sleep(0.25)"',
3230 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003231
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003232 def test_invalid_args(self):
3233 # invalid arguments should raise ValueError
3234 self.assertRaises(ValueError, subprocess.call,
3235 [sys.executable, "-c",
3236 "import sys; sys.exit(47)"],
3237 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003238
Oren Milman0b3a87e2017-09-14 22:30:28 +03003239 @support.cpython_only
3240 def test_issue31471(self):
3241 # There shouldn't be an assertion failure in Popen() in case the env
3242 # argument has a bad keys() method.
3243 class BadEnv(dict):
3244 keys = None
3245 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003246 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003247
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003248 def test_close_fds(self):
3249 # close file descriptors
3250 rc = subprocess.call([sys.executable, "-c",
3251 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003252 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003253 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003254
Segev Finerb2a60832017-12-18 11:28:19 +02003255 def test_close_fds_with_stdio(self):
3256 import msvcrt
3257
3258 fds = os.pipe()
3259 self.addCleanup(os.close, fds[0])
3260 self.addCleanup(os.close, fds[1])
3261
3262 handles = []
3263 for fd in fds:
3264 os.set_inheritable(fd, True)
3265 handles.append(msvcrt.get_osfhandle(fd))
3266
3267 p = subprocess.Popen([sys.executable, "-c",
3268 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3269 stdout=subprocess.PIPE, close_fds=False)
3270 stdout, stderr = p.communicate()
3271 self.assertEqual(p.returncode, 0)
3272 int(stdout.strip()) # Check that stdout is an integer
3273
3274 p = subprocess.Popen([sys.executable, "-c",
3275 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3276 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3277 stdout, stderr = p.communicate()
3278 self.assertEqual(p.returncode, 1)
3279 self.assertIn(b"OSError", stderr)
3280
3281 # The same as the previous call, but with an empty handle_list
3282 handle_list = []
3283 startupinfo = subprocess.STARTUPINFO()
3284 startupinfo.lpAttributeList = {"handle_list": handle_list}
3285 p = subprocess.Popen([sys.executable, "-c",
3286 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3287 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3288 startupinfo=startupinfo, close_fds=True)
3289 stdout, stderr = p.communicate()
3290 self.assertEqual(p.returncode, 1)
3291 self.assertIn(b"OSError", stderr)
3292
3293 # Check for a warning due to using handle_list and close_fds=False
Hai Shi0c4f0f32020-06-30 21:46:31 +08003294 with warnings_helper.check_warnings((".*overriding close_fds",
3295 RuntimeWarning)):
Segev Finerb2a60832017-12-18 11:28:19 +02003296 startupinfo = subprocess.STARTUPINFO()
3297 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3298 p = subprocess.Popen([sys.executable, "-c",
3299 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3300 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3301 startupinfo=startupinfo, close_fds=False)
3302 stdout, stderr = p.communicate()
3303 self.assertEqual(p.returncode, 0)
3304
3305 def test_empty_attribute_list(self):
3306 startupinfo = subprocess.STARTUPINFO()
3307 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003308 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003309 startupinfo=startupinfo)
3310
3311 def test_empty_handle_list(self):
3312 startupinfo = subprocess.STARTUPINFO()
3313 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003314 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003315 startupinfo=startupinfo)
3316
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003317 def test_shell_sequence(self):
3318 # Run command through the shell (sequence)
3319 newenv = os.environ.copy()
3320 newenv["FRUIT"] = "physalis"
3321 p = subprocess.Popen(["set"], shell=1,
3322 stdout=subprocess.PIPE,
3323 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003324 with p:
3325 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003326
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003327 def test_shell_string(self):
3328 # Run command through the shell (string)
3329 newenv = os.environ.copy()
3330 newenv["FRUIT"] = "physalis"
3331 p = subprocess.Popen("set", shell=1,
3332 stdout=subprocess.PIPE,
3333 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003334 with p:
3335 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003336
Steve Dower050acae2016-09-06 20:16:17 -07003337 def test_shell_encodings(self):
3338 # Run command through the shell (string)
3339 for enc in ['ansi', 'oem']:
3340 newenv = os.environ.copy()
3341 newenv["FRUIT"] = "physalis"
3342 p = subprocess.Popen("set", shell=1,
3343 stdout=subprocess.PIPE,
3344 env=newenv,
3345 encoding=enc)
3346 with p:
3347 self.assertIn("physalis", p.stdout.read(), enc)
3348
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003349 def test_call_string(self):
3350 # call() function with string argument on Windows
3351 rc = subprocess.call(sys.executable +
3352 ' -c "import sys; sys.exit(47)"')
3353 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003354
Florent Xicluna4886d242010-03-08 13:27:26 +00003355 def _kill_process(self, method, *args):
3356 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003357 p = subprocess.Popen([sys.executable, "-c", """if 1:
3358 import sys, time
3359 sys.stdout.write('x\\n')
3360 sys.stdout.flush()
3361 time.sleep(30)
3362 """],
3363 stdin=subprocess.PIPE,
3364 stdout=subprocess.PIPE,
3365 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003366 with p:
3367 # Wait for the interpreter to be completely initialized before
3368 # sending any signal.
3369 p.stdout.read(1)
3370 getattr(p, method)(*args)
3371 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003372 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003373 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003374 self.assertNotEqual(returncode, 0)
3375
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003376 def _kill_dead_process(self, method, *args):
3377 p = subprocess.Popen([sys.executable, "-c", """if 1:
3378 import sys, time
3379 sys.stdout.write('x\\n')
3380 sys.stdout.flush()
3381 sys.exit(42)
3382 """],
3383 stdin=subprocess.PIPE,
3384 stdout=subprocess.PIPE,
3385 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003386 with p:
3387 # Wait for the interpreter to be completely initialized before
3388 # sending any signal.
3389 p.stdout.read(1)
3390 # The process should end after this
3391 time.sleep(1)
3392 # This shouldn't raise even though the child is now dead
3393 getattr(p, method)(*args)
3394 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003395 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003396 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003397 self.assertEqual(rc, 42)
3398
Florent Xicluna4886d242010-03-08 13:27:26 +00003399 def test_send_signal(self):
3400 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003401
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003402 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003403 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003404
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003405 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003406 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003407
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003408 def test_send_signal_dead(self):
3409 self._kill_dead_process('send_signal', signal.SIGTERM)
3410
3411 def test_kill_dead(self):
3412 self._kill_dead_process('kill')
3413
3414 def test_terminate_dead(self):
3415 self._kill_dead_process('terminate')
3416
Martin Panter23172bd2016-04-16 11:28:10 +00003417class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003418
3419 class RecordingPopen(subprocess.Popen):
3420 """A Popen that saves a reference to each instance for testing."""
3421 instances_created = []
3422
3423 def __init__(self, *args, **kwargs):
3424 super().__init__(*args, **kwargs)
3425 self.instances_created.append(self)
3426
3427 @mock.patch.object(subprocess.Popen, "_communicate")
3428 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3429 **kwargs):
3430 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3431
3432 This avoids the need to actually try and get test environments to send
3433 and receive signals reliably across platforms. The net effect of a ^C
3434 happening during a blocking subprocess execution which we want to clean
3435 up from is a KeyboardInterrupt coming out of communicate() or wait().
3436 """
3437
3438 mock__communicate.side_effect = KeyboardInterrupt
3439 try:
3440 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3441 # We patch out _wait() as no signal was involved so the
3442 # child process isn't actually going to exit rapidly.
3443 mock__wait.side_effect = KeyboardInterrupt
3444 with mock.patch.object(subprocess, "Popen",
3445 self.RecordingPopen):
3446 with self.assertRaises(KeyboardInterrupt):
3447 popener([sys.executable, "-c",
3448 "import time\ntime.sleep(9)\nimport sys\n"
3449 "sys.stderr.write('\\n!runaway child!\\n')"],
3450 stdout=subprocess.DEVNULL, **kwargs)
3451 for call in mock__wait.call_args_list[1:]:
3452 self.assertNotEqual(
3453 call, mock.call(timeout=None),
3454 "no open-ended wait() after the first allowed: "
3455 f"{mock__wait.call_args_list}")
3456 sigint_calls = []
3457 for call in mock__wait.call_args_list:
3458 if call == mock.call(timeout=0.25): # from Popen.__init__
3459 sigint_calls.append(call)
3460 self.assertLessEqual(mock__wait.call_count, 2,
3461 msg=mock__wait.call_args_list)
3462 self.assertEqual(len(sigint_calls), 1,
3463 msg=mock__wait.call_args_list)
3464 finally:
3465 # cleanup the forgotten (due to our mocks) child process
3466 process = self.RecordingPopen.instances_created.pop()
3467 process.kill()
3468 process.wait()
3469 self.assertEqual([], self.RecordingPopen.instances_created)
3470
3471 def test_call_keyboardinterrupt_no_kill(self):
3472 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3473
3474 def test_run_keyboardinterrupt_no_kill(self):
3475 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3476
3477 def test_context_manager_keyboardinterrupt_no_kill(self):
3478 def popen_via_context_manager(*args, **kwargs):
3479 with subprocess.Popen(*args, **kwargs) as unused_process:
3480 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3481 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3482
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003483 def test_getoutput(self):
3484 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3485 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3486 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003487
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003488 # we use mkdtemp in the next line to create an empty directory
3489 # under our exclusive control; from that, we can invent a pathname
3490 # that we _know_ won't exist. This is guaranteed to fail.
3491 dir = None
3492 try:
3493 dir = tempfile.mkdtemp()
3494 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003495 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003496 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003497 self.assertNotEqual(status, 0)
3498 finally:
3499 if dir is not None:
3500 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003501
Gregory P. Smithace55862015-04-07 15:57:54 -07003502 def test__all__(self):
3503 """Ensure that __all__ is populated properly."""
Patrick McLean2b2ead72019-09-12 10:15:44 -07003504 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003505 exported = set(subprocess.__all__)
3506 possible_exports = set()
3507 import types
3508 for name, value in subprocess.__dict__.items():
3509 if name.startswith('_'):
3510 continue
3511 if isinstance(value, (types.ModuleType,)):
3512 continue
3513 possible_exports.add(name)
3514 self.assertEqual(exported, possible_exports - intentionally_excluded)
3515
3516
Martin Panter23172bd2016-04-16 11:28:10 +00003517@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3518 "Test needs selectors.PollSelector")
3519class ProcessTestCaseNoPoll(ProcessTestCase):
3520 def setUp(self):
3521 self.orig_selector = subprocess._PopenSelector
3522 subprocess._PopenSelector = selectors.SelectSelector
3523 ProcessTestCase.setUp(self)
3524
3525 def tearDown(self):
3526 subprocess._PopenSelector = self.orig_selector
3527 ProcessTestCase.tearDown(self)
3528
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003529
Victor Stinner937ee9e2018-06-26 02:11:06 +02003530@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003531class CommandsWithSpaces (BaseTestCase):
3532
3533 def setUp(self):
3534 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003535 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003536 self.fname = fname.lower ()
3537 os.write(f, b"import sys;"
3538 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3539 )
3540 os.close(f)
3541
3542 def tearDown(self):
3543 os.remove(self.fname)
3544 super().tearDown()
3545
3546 def with_spaces(self, *args, **kwargs):
3547 kwargs['stdout'] = subprocess.PIPE
3548 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003549 with p:
3550 self.assertEqual(
3551 p.stdout.read ().decode("mbcs"),
3552 "2 [%r, 'ab cd']" % self.fname
3553 )
Tim Golden126c2962010-08-11 14:20:40 +00003554
3555 def test_shell_string_with_spaces(self):
3556 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003557 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3558 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003559
3560 def test_shell_sequence_with_spaces(self):
3561 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003562 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003563
3564 def test_noshell_string_with_spaces(self):
3565 # call() function with string argument with spaces on Windows
3566 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3567 "ab cd"))
3568
3569 def test_noshell_sequence_with_spaces(self):
3570 # call() function with sequence argument with spaces on Windows
3571 self.with_spaces([sys.executable, self.fname, "ab cd"])
3572
Brian Curtin79cdb662010-12-03 02:46:02 +00003573
Georg Brandla86b2622012-02-20 21:34:57 +01003574class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003575
3576 def test_pipe(self):
3577 with subprocess.Popen([sys.executable, "-c",
3578 "import sys;"
3579 "sys.stdout.write('stdout');"
3580 "sys.stderr.write('stderr');"],
3581 stdout=subprocess.PIPE,
3582 stderr=subprocess.PIPE) as proc:
3583 self.assertEqual(proc.stdout.read(), b"stdout")
Victor Stinner6cac1132019-12-08 08:38:16 +01003584 self.assertEqual(proc.stderr.read(), b"stderr")
Brian Curtin79cdb662010-12-03 02:46:02 +00003585
3586 self.assertTrue(proc.stdout.closed)
3587 self.assertTrue(proc.stderr.closed)
3588
3589 def test_returncode(self):
3590 with subprocess.Popen([sys.executable, "-c",
3591 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003592 pass
3593 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003594 self.assertEqual(proc.returncode, 100)
3595
3596 def test_communicate_stdin(self):
3597 with subprocess.Popen([sys.executable, "-c",
3598 "import sys;"
3599 "sys.exit(sys.stdin.read() == 'context')"],
3600 stdin=subprocess.PIPE) as proc:
3601 proc.communicate(b"context")
3602 self.assertEqual(proc.returncode, 1)
3603
3604 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003605 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003606 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003607 stdout=subprocess.PIPE,
3608 stderr=subprocess.PIPE) as proc:
3609 pass
3610
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003611 def test_broken_pipe_cleanup(self):
3612 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003613 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003614 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003615 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003616 proc = proc.__enter__()
3617 # Prepare to send enough data to overflow any OS pipe buffering and
3618 # guarantee a broken pipe error. Data is held in BufferedWriter
3619 # buffer until closed.
3620 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003621 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003622 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003623 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003624 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003625 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003626
Brian Curtin79cdb662010-12-03 02:46:02 +00003627
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003628if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003629 unittest.main()