blob: 5cc324b87894c627b4197ea558024ce1a21024ba [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00002from unittest import mock
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
6import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04007import io
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03008import itertools
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Gregory P. Smith580d2782019-09-11 04:23:05 -050013import traceback
Charles-François Natali3a4586a2013-11-08 19:56:59 +010014import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000015import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000016import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040017import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020018import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050019import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030020import textwrap
Patrick McLean2b2ead72019-09-12 10:15:44 -070021import json
Serhiy Storchakab21d1552018-03-02 11:53:51 +020022from test.support import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050023
24try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020025 import _testcapi
26except ImportError:
27 _testcapi = None
28
Patrick McLean2b2ead72019-09-12 10:15:44 -070029try:
30 import pwd
31except ImportError:
32 pwd = None
33try:
34 import grp
35except ImportError:
36 grp = None
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020037
Steve Dower22d06982016-09-06 19:38:15 -070038if support.PGO:
39 raise unittest.SkipTest("test is not helpful for PGO")
40
Victor Stinner937ee9e2018-06-26 02:11:06 +020041mswindows = (sys.platform == "win32")
42
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000043#
44# Depends on the following external programs: Python
45#
46
Victor Stinner937ee9e2018-06-26 02:11:06 +020047if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000048 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
49 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000050else:
51 SETBINARY = ''
52
Victor Stinner9a83f652017-08-21 23:51:31 +020053NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010054# Ignore errors that indicate the command was not found
55NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020056
Florent Xiclunab1e94e82010-02-27 22:12:37 +000057
Florent Xiclunac049d872010-03-27 22:47:23 +000058class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059 def setUp(self):
60 # Try to minimize the number of children we have so this test
61 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000062 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000063
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000064 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030065 if not mswindows:
66 # subprocess._active is not used on Windows and is set to None.
67 for inst in subprocess._active:
68 inst.wait()
69 subprocess._cleanup()
70 self.assertFalse(
71 subprocess._active, "subprocess._active not empty"
72 )
Victor Stinnercc42c122017-07-28 18:00:22 +020073 self.doCleanups()
74 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000075
Florent Xiclunab1e94e82010-02-27 22:12:37 +000076 def assertStderrEqual(self, stderr, expected, msg=None):
77 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
78 # shutdown time. That frustrates tests trying to check stderr produced
79 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000080 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040081 # strip_python_stderr also strips whitespace, so we do too.
82 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000083 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000084
Florent Xiclunac049d872010-03-27 22:47:23 +000085
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080086class PopenTestException(Exception):
87 pass
88
89
90class PopenExecuteChildRaises(subprocess.Popen):
91 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
92 _execute_child fails.
93 """
94 def _execute_child(self, *args, **kwargs):
95 raise PopenTestException("Forced Exception for Test")
96
97
Florent Xiclunac049d872010-03-27 22:47:23 +000098class ProcessTestCase(BaseTestCase):
99
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700100 def test_io_buffered_by_default(self):
101 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
102 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
103 stderr=subprocess.PIPE)
104 try:
105 self.assertIsInstance(p.stdin, io.BufferedIOBase)
106 self.assertIsInstance(p.stdout, io.BufferedIOBase)
107 self.assertIsInstance(p.stderr, io.BufferedIOBase)
108 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700109 p.stdin.close()
110 p.stdout.close()
111 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700112 p.wait()
113
114 def test_io_unbuffered_works(self):
115 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
116 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
117 stderr=subprocess.PIPE, bufsize=0)
118 try:
119 self.assertIsInstance(p.stdin, io.RawIOBase)
120 self.assertIsInstance(p.stdout, io.RawIOBase)
121 self.assertIsInstance(p.stderr, io.RawIOBase)
122 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700123 p.stdin.close()
124 p.stdout.close()
125 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700126 p.wait()
127
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000128 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000129 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000130 rc = subprocess.call([sys.executable, "-c",
131 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000132 self.assertEqual(rc, 47)
133
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400134 def test_call_timeout(self):
135 # call() function with timeout argument; we want to test that the child
136 # process gets killed when the timeout expires. If the child isn't
137 # killed, this call will deadlock since subprocess.call waits for the
138 # child.
139 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
140 [sys.executable, "-c", "while True: pass"],
141 timeout=0.1)
142
Peter Astrand454f7672005-01-01 09:36:35 +0000143 def test_check_call_zero(self):
144 # check_call() function with zero return code
145 rc = subprocess.check_call([sys.executable, "-c",
146 "import sys; sys.exit(0)"])
147 self.assertEqual(rc, 0)
148
149 def test_check_call_nonzero(self):
150 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000151 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000152 subprocess.check_call([sys.executable, "-c",
153 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000154 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000155
Georg Brandlf9734072008-12-07 15:30:06 +0000156 def test_check_output(self):
157 # check_output() function with zero return code
158 output = subprocess.check_output(
159 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000160 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000161
162 def test_check_output_nonzero(self):
163 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000164 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000165 subprocess.check_output(
166 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000167 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000168
169 def test_check_output_stderr(self):
170 # check_output() function stderr redirected to stdout
171 output = subprocess.check_output(
172 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
173 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000174 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000175
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300176 def test_check_output_stdin_arg(self):
177 # check_output() can be called with stdin set to a file
178 tf = tempfile.TemporaryFile()
179 self.addCleanup(tf.close)
180 tf.write(b'pear')
181 tf.seek(0)
182 output = subprocess.check_output(
183 [sys.executable, "-c",
184 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
185 stdin=tf)
186 self.assertIn(b'PEAR', output)
187
188 def test_check_output_input_arg(self):
189 # check_output() can be called with input set to a string
190 output = subprocess.check_output(
191 [sys.executable, "-c",
192 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
193 input=b'pear')
194 self.assertIn(b'PEAR', output)
195
Georg Brandlf9734072008-12-07 15:30:06 +0000196 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300197 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000198 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000199 output = subprocess.check_output(
200 [sys.executable, "-c", "print('will not be run')"],
201 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000202 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000203 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000204
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300205 def test_check_output_stdin_with_input_arg(self):
206 # check_output() refuses to accept 'stdin' with 'input'
207 tf = tempfile.TemporaryFile()
208 self.addCleanup(tf.close)
209 tf.write(b'pear')
210 tf.seek(0)
211 with self.assertRaises(ValueError) as c:
212 output = subprocess.check_output(
213 [sys.executable, "-c", "print('will not be run')"],
214 stdin=tf, input=b'hare')
215 self.fail("Expected ValueError when stdin and input args supplied.")
216 self.assertIn('stdin', c.exception.args[0])
217 self.assertIn('input', c.exception.args[0])
218
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400219 def test_check_output_timeout(self):
220 # check_output() function with timeout arg
221 with self.assertRaises(subprocess.TimeoutExpired) as c:
222 output = subprocess.check_output(
223 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200224 "import sys, time\n"
225 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400226 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200227 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400228 # Some heavily loaded buildbots (sparc Debian 3.x) require
229 # this much time to start and print.
230 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400231 self.fail("Expected TimeoutExpired.")
232 self.assertEqual(c.exception.output, b'BDFL')
233
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000234 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000235 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236 newenv = os.environ.copy()
237 newenv["FRUIT"] = "banana"
238 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000239 'import sys, os;'
240 'sys.exit(os.getenv("FRUIT")=="banana")'],
241 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 self.assertEqual(rc, 1)
243
Victor Stinner87b9bc32011-06-01 00:57:47 +0200244 def test_invalid_args(self):
245 # Popen() called with invalid arguments should raise TypeError
246 # but Popen.__del__ should not complain (issue #12085)
247 with support.captured_stderr() as s:
248 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
249 argcount = subprocess.Popen.__init__.__code__.co_argcount
250 too_many_args = [0] * (argcount + 1)
251 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
252 self.assertEqual(s.getvalue(), '')
253
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000254 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000255 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000256 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000257 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000258 self.addCleanup(p.stdout.close)
259 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000260 p.wait()
261 self.assertEqual(p.stdin, None)
262
263 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200264 # .stdout is None when not redirected, and the child's stdout will
265 # be inherited from the parent. In order to test this we run a
266 # subprocess in a subprocess:
267 # this_test
268 # \-- subprocess created by this test (parent)
269 # \-- subprocess created by the parent subprocess (child)
270 # The parent doesn't specify stdout, so the child will use the
271 # parent's stdout. This test checks that the message printed by the
272 # child goes to the parent stdout. The parent also checks that the
273 # child's stdout is None. See #11963.
274 code = ('import sys; from subprocess import Popen, PIPE;'
275 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
276 ' stdin=PIPE, stderr=PIPE);'
277 'p.wait(); assert p.stdout is None;')
278 p = subprocess.Popen([sys.executable, "-c", code],
279 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
280 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000281 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200282 out, err = p.communicate()
283 self.assertEqual(p.returncode, 0, err)
284 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285
286 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000287 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000288 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000289 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000290 self.addCleanup(p.stdout.close)
291 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000292 p.wait()
293 self.assertEqual(p.stderr, None)
294
Chris Jerdonek776cb192012-10-08 15:56:43 -0700295 def _assert_python(self, pre_args, **kwargs):
296 # We include sys.exit() to prevent the test runner from hanging
297 # whenever python is found.
298 args = pre_args + ["import sys; sys.exit(47)"]
299 p = subprocess.Popen(args, **kwargs)
300 p.wait()
301 self.assertEqual(47, p.returncode)
302
303 def test_executable(self):
304 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700305 #
306 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
307 # determine where its standard library is, so we need the directory
308 # of args[0] to be valid for the Popen() call to Python to succeed.
309 # See also issue #16170 and issue #7774.
310 doesnotexist = os.path.join(os.path.dirname(sys.executable),
311 "doesnotexist")
312 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700313
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300314 def test_bytes_executable(self):
315 doesnotexist = os.path.join(os.path.dirname(sys.executable),
316 "doesnotexist")
317 self._assert_python([doesnotexist, "-c"],
318 executable=os.fsencode(sys.executable))
319
320 def test_pathlike_executable(self):
321 doesnotexist = os.path.join(os.path.dirname(sys.executable),
322 "doesnotexist")
323 self._assert_python([doesnotexist, "-c"],
324 executable=FakePath(sys.executable))
325
Chris Jerdonek776cb192012-10-08 15:56:43 -0700326 def test_executable_takes_precedence(self):
327 # Check that the executable argument takes precedence over args[0].
328 #
329 # Verify first that the call succeeds without the executable arg.
330 pre_args = [sys.executable, "-c"]
331 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100332 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100333 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100334 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700335
Victor Stinner937ee9e2018-06-26 02:11:06 +0200336 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700337 def test_executable_replaces_shell(self):
338 # Check that the executable argument replaces the default shell
339 # when shell=True.
340 self._assert_python([], executable=sys.executable, shell=True)
341
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300342 @unittest.skipIf(mswindows, "executable argument replaces shell")
343 def test_bytes_executable_replaces_shell(self):
344 self._assert_python([], executable=os.fsencode(sys.executable),
345 shell=True)
346
347 @unittest.skipIf(mswindows, "executable argument replaces shell")
348 def test_pathlike_executable_replaces_shell(self):
349 self._assert_python([], executable=FakePath(sys.executable),
350 shell=True)
351
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700352 # For use in the test_cwd* tests below.
353 def _normalize_cwd(self, cwd):
354 # Normalize an expected cwd (for Tru64 support).
355 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
356 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300357 with support.change_cwd(cwd):
358 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700359
360 # For use in the test_cwd* tests below.
361 def _split_python_path(self):
362 # Return normalized (python_dir, python_base).
363 python_path = os.path.realpath(sys.executable)
364 return os.path.split(python_path)
365
366 # For use in the test_cwd* tests below.
367 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
368 # Invoke Python via Popen, and assert that (1) the call succeeds,
369 # and that (2) the current working directory of the child process
370 # matches *expected_cwd*.
371 p = subprocess.Popen([python_arg, "-c",
372 "import os, sys; "
373 "sys.stdout.write(os.getcwd()); "
374 "sys.exit(47)"],
375 stdout=subprocess.PIPE,
376 **kwargs)
377 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000378 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700379 self.assertEqual(47, p.returncode)
380 normcase = os.path.normcase
381 self.assertEqual(normcase(expected_cwd),
382 normcase(p.stdout.read().decode("utf-8")))
383
384 def test_cwd(self):
385 # Check that cwd changes the cwd for the child process.
386 temp_dir = tempfile.gettempdir()
387 temp_dir = self._normalize_cwd(temp_dir)
388 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
389
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300390 def test_cwd_with_bytes(self):
391 temp_dir = tempfile.gettempdir()
392 temp_dir = self._normalize_cwd(temp_dir)
393 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
394
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530395 def test_cwd_with_pathlike(self):
396 temp_dir = tempfile.gettempdir()
397 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200398 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530399
Victor Stinner937ee9e2018-06-26 02:11:06 +0200400 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700401 def test_cwd_with_relative_arg(self):
402 # Check that Popen looks for args[0] relative to cwd if args[0]
403 # is relative.
404 python_dir, python_base = self._split_python_path()
405 rel_python = os.path.join(os.curdir, python_base)
406 with support.temp_cwd() as wrong_dir:
407 # Before calling with the correct cwd, confirm that the call fails
408 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700409 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700410 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700411 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700412 [rel_python], cwd=wrong_dir)
413 python_dir = self._normalize_cwd(python_dir)
414 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
415
Victor Stinner937ee9e2018-06-26 02:11:06 +0200416 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700417 def test_cwd_with_relative_executable(self):
418 # Check that Popen looks for executable relative to cwd if executable
419 # is relative (and that executable takes precedence over args[0]).
420 python_dir, python_base = self._split_python_path()
421 rel_python = os.path.join(os.curdir, python_base)
422 doesntexist = "somethingyoudonthave"
423 with support.temp_cwd() as wrong_dir:
424 # Before calling with the correct cwd, confirm that the call fails
425 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700426 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700427 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700428 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700429 [doesntexist], executable=rel_python,
430 cwd=wrong_dir)
431 python_dir = self._normalize_cwd(python_dir)
432 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
433 cwd=python_dir)
434
435 def test_cwd_with_absolute_arg(self):
436 # Check that Popen can find the executable when the cwd is wrong
437 # if args[0] is an absolute path.
438 python_dir, python_base = self._split_python_path()
439 abs_python = os.path.join(python_dir, python_base)
440 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300441 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700442 # Before calling with an absolute path, confirm that using a
443 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700444 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700445 [rel_python], cwd=wrong_dir)
446 wrong_dir = self._normalize_cwd(wrong_dir)
447 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
448
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100449 @unittest.skipIf(sys.base_prefix != sys.prefix,
450 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000451 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700452 python_dir, python_base = self._split_python_path()
453 python_dir = self._normalize_cwd(python_dir)
454 self._assert_cwd(python_dir, "somethingyoudonthave",
455 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000456
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100457 @unittest.skipIf(sys.base_prefix != sys.prefix,
458 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000459 @unittest.skipIf(sysconfig.is_python_build(),
460 "need an installed Python. See #7774")
461 def test_executable_without_cwd(self):
462 # For a normal installation, it should work without 'cwd'
463 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700464 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
465 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466
467 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000468 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000469 p = subprocess.Popen([sys.executable, "-c",
470 'import sys; sys.exit(sys.stdin.read() == "pear")'],
471 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000472 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000473 p.stdin.close()
474 p.wait()
475 self.assertEqual(p.returncode, 1)
476
477 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000478 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000479 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000480 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000482 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483 os.lseek(d, 0, 0)
484 p = subprocess.Popen([sys.executable, "-c",
485 'import sys; sys.exit(sys.stdin.read() == "pear")'],
486 stdin=d)
487 p.wait()
488 self.assertEqual(p.returncode, 1)
489
490 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000491 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000493 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000494 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495 tf.seek(0)
496 p = subprocess.Popen([sys.executable, "-c",
497 'import sys; sys.exit(sys.stdin.read() == "pear")'],
498 stdin=tf)
499 p.wait()
500 self.assertEqual(p.returncode, 1)
501
502 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000503 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504 p = subprocess.Popen([sys.executable, "-c",
505 'import sys; sys.stdout.write("orange")'],
506 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200507 with p:
508 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000509
510 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000511 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000512 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000513 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514 d = tf.fileno()
515 p = subprocess.Popen([sys.executable, "-c",
516 'import sys; sys.stdout.write("orange")'],
517 stdout=d)
518 p.wait()
519 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000520 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000521
522 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000523 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000524 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000525 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526 p = subprocess.Popen([sys.executable, "-c",
527 'import sys; sys.stdout.write("orange")'],
528 stdout=tf)
529 p.wait()
530 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000531 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532
533 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000534 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000535 p = subprocess.Popen([sys.executable, "-c",
536 'import sys; sys.stderr.write("strawberry")'],
537 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200538 with p:
539 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540
541 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000542 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000543 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000544 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 d = tf.fileno()
546 p = subprocess.Popen([sys.executable, "-c",
547 'import sys; sys.stderr.write("strawberry")'],
548 stderr=d)
549 p.wait()
550 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000551 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000552
553 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000554 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000555 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000556 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000557 p = subprocess.Popen([sys.executable, "-c",
558 'import sys; sys.stderr.write("strawberry")'],
559 stderr=tf)
560 p.wait()
561 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000562 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563
Martin Panterc7635892016-05-13 01:54:44 +0000564 def test_stderr_redirect_with_no_stdout_redirect(self):
565 # test stderr=STDOUT while stdout=None (not set)
566
567 # - grandchild prints to stderr
568 # - child redirects grandchild's stderr to its stdout
569 # - the parent should get grandchild's stderr in child's stdout
570 p = subprocess.Popen([sys.executable, "-c",
571 'import sys, subprocess;'
572 'rc = subprocess.call([sys.executable, "-c",'
573 ' "import sys;"'
574 ' "sys.stderr.write(\'42\')"],'
575 ' stderr=subprocess.STDOUT);'
576 'sys.exit(rc)'],
577 stdout=subprocess.PIPE,
578 stderr=subprocess.PIPE)
579 stdout, stderr = p.communicate()
580 #NOTE: stdout should get stderr from grandchild
581 self.assertStderrEqual(stdout, b'42')
582 self.assertStderrEqual(stderr, b'') # should be empty
583 self.assertEqual(p.returncode, 0)
584
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000585 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000586 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000587 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000588 'import sys;'
589 'sys.stdout.write("apple");'
590 'sys.stdout.flush();'
591 'sys.stderr.write("orange")'],
592 stdout=subprocess.PIPE,
593 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200594 with p:
595 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596
597 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000598 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000599 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000600 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000602 'import sys;'
603 'sys.stdout.write("apple");'
604 'sys.stdout.flush();'
605 'sys.stderr.write("orange")'],
606 stdout=tf,
607 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000608 p.wait()
609 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000610 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000611
Thomas Wouters89f507f2006-12-13 04:49:30 +0000612 def test_stdout_filedes_of_stdout(self):
613 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200614 # To avoid printing the text on stdout, we do something similar to
615 # test_stdout_none (see above). The parent subprocess calls the child
616 # subprocess passing stdout=1, and this test uses stdout=PIPE in
617 # order to capture and check the output of the parent. See #11963.
618 code = ('import sys, subprocess; '
619 'rc = subprocess.call([sys.executable, "-c", '
620 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
621 'b\'test with stdout=1\'))"], stdout=1); '
622 'assert rc == 18')
623 p = subprocess.Popen([sys.executable, "-c", code],
624 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
625 self.addCleanup(p.stdout.close)
626 self.addCleanup(p.stderr.close)
627 out, err = p.communicate()
628 self.assertEqual(p.returncode, 0, err)
629 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000630
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200631 def test_stdout_devnull(self):
632 p = subprocess.Popen([sys.executable, "-c",
633 'for i in range(10240):'
634 'print("x" * 1024)'],
635 stdout=subprocess.DEVNULL)
636 p.wait()
637 self.assertEqual(p.stdout, None)
638
639 def test_stderr_devnull(self):
640 p = subprocess.Popen([sys.executable, "-c",
641 'import sys\n'
642 'for i in range(10240):'
643 'sys.stderr.write("x" * 1024)'],
644 stderr=subprocess.DEVNULL)
645 p.wait()
646 self.assertEqual(p.stderr, None)
647
648 def test_stdin_devnull(self):
649 p = subprocess.Popen([sys.executable, "-c",
650 'import sys;'
651 'sys.stdin.read(1)'],
652 stdin=subprocess.DEVNULL)
653 p.wait()
654 self.assertEqual(p.stdin, None)
655
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000656 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000657 newenv = os.environ.copy()
658 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200659 with subprocess.Popen([sys.executable, "-c",
660 'import sys,os;'
661 'sys.stdout.write(os.getenv("FRUIT"))'],
662 stdout=subprocess.PIPE,
663 env=newenv) as p:
664 stdout, stderr = p.communicate()
665 self.assertEqual(stdout, b"orange")
666
Victor Stinner62d51182011-06-23 01:02:25 +0200667 # Windows requires at least the SYSTEMROOT environment variable to start
668 # Python
669 @unittest.skipIf(sys.platform == 'win32',
670 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700671 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
672 'The Python shared library cannot be loaded '
673 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200674 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700675 """Verify that env={} is as empty as possible."""
676
Gregory P. Smith85aba232017-05-30 16:21:47 -0700677 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700678 """Determine if an environment variable is under our control."""
679 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
680 # on adding even when the environment in exec is empty.
681 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700682 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400683 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000684 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
685 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700686
Victor Stinnerf1512a22011-06-21 17:18:38 +0200687 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700688 'import os; print(list(os.environ.keys()))'],
689 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200690 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700691 child_env_names = eval(stdout.strip())
692 self.assertIsInstance(child_env_names, list)
693 child_env_names = [k for k in child_env_names
694 if not is_env_var_to_ignore(k)]
695 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000696
Serhiy Storchakad174d242017-06-23 19:39:27 +0300697 def test_invalid_cmd(self):
698 # null character in the command name
699 cmd = sys.executable + '\0'
700 with self.assertRaises(ValueError):
701 subprocess.Popen([cmd, "-c", "pass"])
702
703 # null character in the command argument
704 with self.assertRaises(ValueError):
705 subprocess.Popen([sys.executable, "-c", "pass#\0"])
706
707 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300708 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300709 newenv = os.environ.copy()
710 newenv["FRUIT\0VEGETABLE"] = "cabbage"
711 with self.assertRaises(ValueError):
712 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
713
Ville Skyttä49b27342017-08-03 09:00:59 +0300714 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300715 newenv = os.environ.copy()
716 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
717 with self.assertRaises(ValueError):
718 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
719
Ville Skyttä49b27342017-08-03 09:00:59 +0300720 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300721 newenv = os.environ.copy()
722 newenv["FRUIT=ORANGE"] = "lemon"
723 with self.assertRaises(ValueError):
724 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
725
Ville Skyttä49b27342017-08-03 09:00:59 +0300726 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300727 newenv = os.environ.copy()
728 newenv["FRUIT"] = "orange=lemon"
729 with subprocess.Popen([sys.executable, "-c",
730 'import sys, os;'
731 'sys.stdout.write(os.getenv("FRUIT"))'],
732 stdout=subprocess.PIPE,
733 env=newenv) as p:
734 stdout, stderr = p.communicate()
735 self.assertEqual(stdout, b"orange=lemon")
736
Peter Astrandcbac93c2005-03-03 20:24:28 +0000737 def test_communicate_stdin(self):
738 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000739 'import sys;'
740 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000741 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000742 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000743 self.assertEqual(p.returncode, 1)
744
745 def test_communicate_stdout(self):
746 p = subprocess.Popen([sys.executable, "-c",
747 'import sys; sys.stdout.write("pineapple")'],
748 stdout=subprocess.PIPE)
749 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000750 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000751 self.assertEqual(stderr, None)
752
753 def test_communicate_stderr(self):
754 p = subprocess.Popen([sys.executable, "-c",
755 'import sys; sys.stderr.write("pineapple")'],
756 stderr=subprocess.PIPE)
757 (stdout, stderr) = p.communicate()
758 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000759 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000760
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000761 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000762 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000763 'import sys,os;'
764 'sys.stderr.write("pineapple");'
765 'sys.stdout.write(sys.stdin.read())'],
766 stdin=subprocess.PIPE,
767 stdout=subprocess.PIPE,
768 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000769 self.addCleanup(p.stdout.close)
770 self.addCleanup(p.stderr.close)
771 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000772 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000773 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000774 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000775
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400776 def test_communicate_timeout(self):
777 p = subprocess.Popen([sys.executable, "-c",
778 'import sys,os,time;'
779 'sys.stderr.write("pineapple\\n");'
780 'time.sleep(1);'
781 'sys.stderr.write("pear\\n");'
782 'sys.stdout.write(sys.stdin.read())'],
783 universal_newlines=True,
784 stdin=subprocess.PIPE,
785 stdout=subprocess.PIPE,
786 stderr=subprocess.PIPE)
787 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
788 timeout=0.3)
789 # Make sure we can keep waiting for it, and that we get the whole output
790 # after it completes.
791 (stdout, stderr) = p.communicate()
792 self.assertEqual(stdout, "banana")
793 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
794
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700795 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200796 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400797 p = subprocess.Popen([sys.executable, "-c",
798 'import sys,os,time;'
799 'sys.stdout.write("a" * (64 * 1024));'
800 'time.sleep(0.2);'
801 'sys.stdout.write("a" * (64 * 1024));'
802 'time.sleep(0.2);'
803 'sys.stdout.write("a" * (64 * 1024));'
804 'time.sleep(0.2);'
805 'sys.stdout.write("a" * (64 * 1024));'],
806 stdout=subprocess.PIPE)
807 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
808 (stdout, _) = p.communicate()
809 self.assertEqual(len(stdout), 4 * 64 * 1024)
810
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000811 # Test for the fd leak reported in http://bugs.python.org/issue2791.
812 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000813 for stdin_pipe in (False, True):
814 for stdout_pipe in (False, True):
815 for stderr_pipe in (False, True):
816 options = {}
817 if stdin_pipe:
818 options['stdin'] = subprocess.PIPE
819 if stdout_pipe:
820 options['stdout'] = subprocess.PIPE
821 if stderr_pipe:
822 options['stderr'] = subprocess.PIPE
823 if not options:
824 continue
825 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
826 p.communicate()
827 if p.stdin is not None:
828 self.assertTrue(p.stdin.closed)
829 if p.stdout is not None:
830 self.assertTrue(p.stdout.closed)
831 if p.stderr is not None:
832 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000833
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000834 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000835 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000836 p = subprocess.Popen([sys.executable, "-c",
837 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000838 (stdout, stderr) = p.communicate()
839 self.assertEqual(stdout, None)
840 self.assertEqual(stderr, None)
841
842 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000843 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000844 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000845 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000846 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 os.close(x)
848 os.close(y)
849 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000850 'import sys,os;'
851 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200852 'sys.stderr.write("x" * %d);'
853 'sys.stdout.write(sys.stdin.read())' %
854 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000855 stdin=subprocess.PIPE,
856 stdout=subprocess.PIPE,
857 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000858 self.addCleanup(p.stdout.close)
859 self.addCleanup(p.stderr.close)
860 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200861 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000862 (stdout, stderr) = p.communicate(string_to_write)
863 self.assertEqual(stdout, string_to_write)
864
865 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000866 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000867 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000868 'import sys,os;'
869 'sys.stdout.write(sys.stdin.read())'],
870 stdin=subprocess.PIPE,
871 stdout=subprocess.PIPE,
872 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000873 self.addCleanup(p.stdout.close)
874 self.addCleanup(p.stderr.close)
875 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000876 p.stdin.write(b"banana")
877 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000878 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000879 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000880
andyclegg7fed7bd2017-10-23 03:01:19 +0100881 def test_universal_newlines_and_text(self):
882 args = [
883 sys.executable, "-c",
884 'import sys,os;' + SETBINARY +
885 'buf = sys.stdout.buffer;'
886 'buf.write(sys.stdin.readline().encode());'
887 'buf.flush();'
888 'buf.write(b"line2\\n");'
889 'buf.flush();'
890 'buf.write(sys.stdin.read().encode());'
891 'buf.flush();'
892 'buf.write(b"line4\\n");'
893 'buf.flush();'
894 'buf.write(b"line5\\r\\n");'
895 'buf.flush();'
896 'buf.write(b"line6\\r");'
897 'buf.flush();'
898 'buf.write(b"\\nline7");'
899 'buf.flush();'
900 'buf.write(b"\\nline8");']
901
902 for extra_kwarg in ('universal_newlines', 'text'):
903 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
904 'stdout': subprocess.PIPE,
905 extra_kwarg: True})
906 with p:
907 p.stdin.write("line1\n")
908 p.stdin.flush()
909 self.assertEqual(p.stdout.readline(), "line1\n")
910 p.stdin.write("line3\n")
911 p.stdin.close()
912 self.addCleanup(p.stdout.close)
913 self.assertEqual(p.stdout.readline(),
914 "line2\n")
915 self.assertEqual(p.stdout.read(6),
916 "line3\n")
917 self.assertEqual(p.stdout.read(),
918 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919
920 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000921 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000922 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000923 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200924 'buf = sys.stdout.buffer;'
925 'buf.write(b"line2\\n");'
926 'buf.flush();'
927 'buf.write(b"line4\\n");'
928 'buf.flush();'
929 'buf.write(b"line5\\r\\n");'
930 'buf.flush();'
931 'buf.write(b"line6\\r");'
932 'buf.flush();'
933 'buf.write(b"\\nline7");'
934 'buf.flush();'
935 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200936 stderr=subprocess.PIPE,
937 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000938 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000939 self.addCleanup(p.stdout.close)
940 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000941 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200942 self.assertEqual(stdout,
943 "line2\nline4\nline5\nline6\nline7\nline8")
944
945 def test_universal_newlines_communicate_stdin(self):
946 # universal newlines through communicate(), with only stdin
947 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300948 'import sys,os;' + SETBINARY + textwrap.dedent('''
949 s = sys.stdin.readline()
950 assert s == "line1\\n", repr(s)
951 s = sys.stdin.read()
952 assert s == "line3\\n", repr(s)
953 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200954 stdin=subprocess.PIPE,
955 universal_newlines=1)
956 (stdout, stderr) = p.communicate("line1\nline3\n")
957 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000958
Andrew Svetlovf3765072012-08-14 18:35:17 +0300959 def test_universal_newlines_communicate_input_none(self):
960 # Test communicate(input=None) with universal newlines.
961 #
962 # We set stdout to PIPE because, as of this writing, a different
963 # code path is tested when the number of pipes is zero or one.
964 p = subprocess.Popen([sys.executable, "-c", "pass"],
965 stdin=subprocess.PIPE,
966 stdout=subprocess.PIPE,
967 universal_newlines=True)
968 p.communicate()
969 self.assertEqual(p.returncode, 0)
970
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300971 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300972 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300973 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300974 'import sys,os;' + SETBINARY + textwrap.dedent('''
975 s = sys.stdin.buffer.readline()
976 sys.stdout.buffer.write(s)
977 sys.stdout.buffer.write(b"line2\\r")
978 sys.stderr.buffer.write(b"eline2\\n")
979 s = sys.stdin.buffer.read()
980 sys.stdout.buffer.write(s)
981 sys.stdout.buffer.write(b"line4\\n")
982 sys.stdout.buffer.write(b"line5\\r\\n")
983 sys.stderr.buffer.write(b"eline6\\r")
984 sys.stderr.buffer.write(b"eline7\\r\\nz")
985 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300986 stdin=subprocess.PIPE,
987 stderr=subprocess.PIPE,
988 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300989 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300990 self.addCleanup(p.stdout.close)
991 self.addCleanup(p.stderr.close)
992 (stdout, stderr) = p.communicate("line1\nline3\n")
993 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300994 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300995 # Python debug build push something like "[42442 refs]\n"
996 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300997 # Don't use assertStderrEqual because it strips CR and LF from output.
998 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300999
Andrew Svetlov82860712012-08-19 22:13:41 +03001000 def test_universal_newlines_communicate_encodings(self):
1001 # Check that universal newlines mode works for various encodings,
1002 # in particular for encodings in the UTF-16 and UTF-32 families.
1003 # See issue #15595.
1004 #
1005 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1006 # without, and UTF-16 and UTF-32.
1007 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001008 code = ("import sys; "
1009 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1010 encoding)
1011 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001012 # We set stdin to be non-None because, as of this writing,
1013 # a different code path is used when the number of pipes is
1014 # zero or one.
1015 popen = subprocess.Popen(args,
1016 stdin=subprocess.PIPE,
1017 stdout=subprocess.PIPE,
1018 encoding=encoding)
1019 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001020 self.assertEqual(stdout, '1\n2\n3\n4')
1021
Steve Dower050acae2016-09-06 20:16:17 -07001022 def test_communicate_errors(self):
1023 for errors, expected in [
1024 ('ignore', ''),
1025 ('replace', '\ufffd\ufffd'),
1026 ('surrogateescape', '\udc80\udc80'),
1027 ('backslashreplace', '\\x80\\x80'),
1028 ]:
1029 code = ("import sys; "
1030 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1031 args = [sys.executable, '-c', code]
1032 # We set stdin to be non-None because, as of this writing,
1033 # a different code path is used when the number of pipes is
1034 # zero or one.
1035 popen = subprocess.Popen(args,
1036 stdin=subprocess.PIPE,
1037 stdout=subprocess.PIPE,
1038 encoding='utf-8',
1039 errors=errors)
1040 stdout, stderr = popen.communicate(input='')
1041 self.assertEqual(stdout, '[{}]'.format(expected))
1042
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001043 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001044 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001045 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001046 max_handles = 1026 # too much for most UNIX systems
1047 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001048 max_handles = 2050 # too much for (at least some) Windows setups
1049 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001050 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001051 try:
1052 for i in range(max_handles):
1053 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001054 tmpfile = os.path.join(tmpdir, support.TESTFN)
1055 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001056 except OSError as e:
1057 if e.errno != errno.EMFILE:
1058 raise
1059 break
1060 else:
1061 self.skipTest("failed to reach the file descriptor limit "
1062 "(tried %d)" % max_handles)
1063 # Close a couple of them (should be enough for a subprocess)
1064 for i in range(10):
1065 os.close(handles.pop())
1066 # Loop creating some subprocesses. If one of them leaks some fds,
1067 # the next loop iteration will fail by reaching the max fd limit.
1068 for i in range(15):
1069 p = subprocess.Popen([sys.executable, "-c",
1070 "import sys;"
1071 "sys.stdout.write(sys.stdin.read())"],
1072 stdin=subprocess.PIPE,
1073 stdout=subprocess.PIPE,
1074 stderr=subprocess.PIPE)
1075 data = p.communicate(b"lime")[0]
1076 self.assertEqual(data, b"lime")
1077 finally:
1078 for h in handles:
1079 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001080 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001081
1082 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001083 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1084 '"a b c" d e')
1085 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1086 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001087 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1088 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001089 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1090 'a\\\\\\b "de fg" h')
1091 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1092 'a\\\\\\"b c d')
1093 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1094 '"a\\\\b c" d e')
1095 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1096 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001097 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1098 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001099
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001100 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001101 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001102 "import os; os.read(0, 1)"],
1103 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001104 self.addCleanup(p.stdin.close)
1105 self.assertIsNone(p.poll())
1106 os.write(p.stdin.fileno(), b'A')
1107 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001108 # Subsequent invocations should just return the returncode
1109 self.assertEqual(p.poll(), 0)
1110
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001111 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001112 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001113 self.assertEqual(p.wait(), 0)
1114 # Subsequent invocations should just return the returncode
1115 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001116
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001117 def test_wait_timeout(self):
1118 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001119 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001120 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001121 p.wait(timeout=0.0001)
1122 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001123 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1124 # time to start.
1125 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001126
Peter Astrand738131d2004-11-30 21:04:45 +00001127 def test_invalid_bufsize(self):
1128 # an invalid type of the bufsize argument should raise
1129 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001130 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001131 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001132
Guido van Rossum46a05a72007-06-07 21:56:45 +00001133 def test_bufsize_is_none(self):
1134 # bufsize=None should be the same as bufsize=0.
1135 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1136 self.assertEqual(p.wait(), 0)
1137 # Again with keyword arg
1138 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1139 self.assertEqual(p.wait(), 0)
1140
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001141 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1142 # subprocess may deadlock with bufsize=1, see issue #21332
1143 with subprocess.Popen([sys.executable, "-c", "import sys;"
1144 "sys.stdout.write(sys.stdin.readline());"
1145 "sys.stdout.flush()"],
1146 stdin=subprocess.PIPE,
1147 stdout=subprocess.PIPE,
1148 stderr=subprocess.DEVNULL,
1149 bufsize=1,
1150 universal_newlines=universal_newlines) as p:
1151 p.stdin.write(line) # expect that it flushes the line in text mode
1152 os.close(p.stdin.fileno()) # close it without flushing the buffer
1153 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001154 with support.SuppressCrashReport():
1155 try:
1156 p.stdin.close()
1157 except OSError:
1158 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001159 p.stdin = None
1160 self.assertEqual(p.returncode, 0)
1161 self.assertEqual(read_line, expected)
1162
1163 def test_bufsize_equal_one_text_mode(self):
1164 # line is flushed in text mode with bufsize=1.
1165 # we should get the full line in return
1166 line = "line\n"
1167 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1168
1169 def test_bufsize_equal_one_binary_mode(self):
1170 # line is not flushed in binary mode with bufsize=1.
1171 # we should get empty response
1172 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001173 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1174 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001175
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001176 def test_leaking_fds_on_error(self):
1177 # see bug #5179: Popen leaks file descriptors to PIPEs if
1178 # the child fails to execute; this will eventually exhaust
1179 # the maximum number of open fds. 1024 seems a very common
1180 # value for that limit, but Windows has 2048, so we loop
1181 # 1024 times (each call leaked two fds).
1182 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001183 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001184 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001185 stdout=subprocess.PIPE,
1186 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001187
Victor Stinner9a83f652017-08-21 23:51:31 +02001188 def test_nonexisting_with_pipes(self):
1189 # bpo-30121: Popen with pipes must close properly pipes on error.
1190 # Previously, os.close() was called with a Windows handle which is not
1191 # a valid file descriptor.
1192 #
1193 # Run the test in a subprocess to control how the CRT reports errors
1194 # and to get stderr content.
1195 try:
1196 import msvcrt
1197 msvcrt.CrtSetReportMode
1198 except (AttributeError, ImportError):
1199 self.skipTest("need msvcrt.CrtSetReportMode")
1200
1201 code = textwrap.dedent(f"""
1202 import msvcrt
1203 import subprocess
1204
1205 cmd = {NONEXISTING_CMD!r}
1206
1207 for report_type in [msvcrt.CRT_WARN,
1208 msvcrt.CRT_ERROR,
1209 msvcrt.CRT_ASSERT]:
1210 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1211 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1212
1213 try:
Zachary Ware55376462018-02-19 14:02:38 -06001214 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001215 stdout=subprocess.PIPE,
1216 stderr=subprocess.PIPE)
1217 except OSError:
1218 pass
1219 """)
1220 cmd = [sys.executable, "-c", code]
1221 proc = subprocess.Popen(cmd,
1222 stderr=subprocess.PIPE,
1223 universal_newlines=True)
1224 with proc:
1225 stderr = proc.communicate()[1]
1226 self.assertEqual(stderr, "")
1227 self.assertEqual(proc.returncode, 0)
1228
Antoine Pitroua8392712013-08-30 23:38:13 +02001229 def test_double_close_on_error(self):
1230 # Issue #18851
1231 fds = []
1232 def open_fds():
1233 for i in range(20):
1234 fds.extend(os.pipe())
1235 time.sleep(0.001)
1236 t = threading.Thread(target=open_fds)
1237 t.start()
1238 try:
1239 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001240 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001241 stdin=subprocess.PIPE,
1242 stdout=subprocess.PIPE,
1243 stderr=subprocess.PIPE)
1244 finally:
1245 t.join()
1246 exc = None
1247 for fd in fds:
1248 # If a double close occurred, some of those fds will
1249 # already have been closed by mistake, and os.close()
1250 # here will raise.
1251 try:
1252 os.close(fd)
1253 except OSError as e:
1254 exc = e
1255 if exc is not None:
1256 raise exc
1257
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001258 def test_threadsafe_wait(self):
1259 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1260 proc = subprocess.Popen([sys.executable, '-c',
1261 'import time; time.sleep(12)'])
1262 self.assertEqual(proc.returncode, None)
1263 results = []
1264
1265 def kill_proc_timer_thread():
1266 results.append(('thread-start-poll-result', proc.poll()))
1267 # terminate it from the thread and wait for the result.
1268 proc.kill()
1269 proc.wait()
1270 results.append(('thread-after-kill-and-wait', proc.returncode))
1271 # this wait should be a no-op given the above.
1272 proc.wait()
1273 results.append(('thread-after-second-wait', proc.returncode))
1274
1275 # This is a timing sensitive test, the failure mode is
1276 # triggered when both the main thread and this thread are in
1277 # the wait() call at once. The delay here is to allow the
1278 # main thread to most likely be blocked in its wait() call.
1279 t = threading.Timer(0.2, kill_proc_timer_thread)
1280 t.start()
1281
Victor Stinner937ee9e2018-06-26 02:11:06 +02001282 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001283 expected_errorcode = 1
1284 else:
1285 # Should be -9 because of the proc.kill() from the thread.
1286 expected_errorcode = -9
1287
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001288 # Wait for the process to finish; the thread should kill it
1289 # long before it finishes on its own. Supplying a timeout
1290 # triggers a different code path for better coverage.
1291 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001292 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001293 msg="unexpected result in wait from main thread")
1294
1295 # This should be a no-op with no change in returncode.
1296 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001297 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001298 msg="unexpected result in second main wait.")
1299
1300 t.join()
1301 # Ensure that all of the thread results are as expected.
1302 # When a race condition occurs in wait(), the returncode could
1303 # be set by the wrong thread that doesn't actually have it
1304 # leading to an incorrect value.
1305 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001306 ('thread-after-kill-and-wait', expected_errorcode),
1307 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001308 results)
1309
Victor Stinnerb3693582010-05-21 20:13:12 +00001310 def test_issue8780(self):
1311 # Ensure that stdout is inherited from the parent
1312 # if stdout=PIPE is not used
1313 code = ';'.join((
1314 'import subprocess, sys',
1315 'retcode = subprocess.call('
1316 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1317 'assert retcode == 0'))
1318 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001319 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001320
Tim Goldenaf5ac392010-08-06 13:03:56 +00001321 def test_handles_closed_on_exception(self):
1322 # If CreateProcess exits with an error, ensure the
1323 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001324 ifhandle, ifname = tempfile.mkstemp()
1325 ofhandle, ofname = tempfile.mkstemp()
1326 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001327 try:
1328 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1329 stderr=efhandle)
1330 except OSError:
1331 os.close(ifhandle)
1332 os.remove(ifname)
1333 os.close(ofhandle)
1334 os.remove(ofname)
1335 os.close(efhandle)
1336 os.remove(efname)
1337 self.assertFalse(os.path.exists(ifname))
1338 self.assertFalse(os.path.exists(ofname))
1339 self.assertFalse(os.path.exists(efname))
1340
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001341 def test_communicate_epipe(self):
1342 # Issue 10963: communicate() should hide EPIPE
1343 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1344 stdin=subprocess.PIPE,
1345 stdout=subprocess.PIPE,
1346 stderr=subprocess.PIPE)
1347 self.addCleanup(p.stdout.close)
1348 self.addCleanup(p.stderr.close)
1349 self.addCleanup(p.stdin.close)
1350 p.communicate(b"x" * 2**20)
1351
1352 def test_communicate_epipe_only_stdin(self):
1353 # Issue 10963: communicate() should hide EPIPE
1354 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1355 stdin=subprocess.PIPE)
1356 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001357 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001358 p.communicate(b"x" * 2**20)
1359
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001360 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1361 "Requires signal.SIGUSR1")
1362 @unittest.skipUnless(hasattr(os, 'kill'),
1363 "Requires os.kill")
1364 @unittest.skipUnless(hasattr(os, 'getppid'),
1365 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001366 def test_communicate_eintr(self):
1367 # Issue #12493: communicate() should handle EINTR
1368 def handler(signum, frame):
1369 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001370 old_handler = signal.signal(signal.SIGUSR1, handler)
1371 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001372
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001373 args = [sys.executable, "-c",
1374 'import os, signal;'
1375 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001376 for stream in ('stdout', 'stderr'):
1377 kw = {stream: subprocess.PIPE}
1378 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001379 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001380 process.communicate()
1381
Tim Peterse718f612004-10-12 21:51:32 +00001382
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001383 # This test is Linux-ish specific for simplicity to at least have
1384 # some coverage. It is not a platform specific bug.
1385 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1386 "Linux specific")
1387 def test_failed_child_execute_fd_leak(self):
1388 """Test for the fork() failure fd leak reported in issue16327."""
1389 fd_directory = '/proc/%d/fd' % os.getpid()
1390 fds_before_popen = os.listdir(fd_directory)
1391 with self.assertRaises(PopenTestException):
1392 PopenExecuteChildRaises(
1393 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1394 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1395
1396 # NOTE: This test doesn't verify that the real _execute_child
1397 # does not close the file descriptors itself on the way out
1398 # during an exception. Code inspection has confirmed that.
1399
1400 fds_after_exception = os.listdir(fd_directory)
1401 self.assertEqual(fds_before_popen, fds_after_exception)
1402
Victor Stinner937ee9e2018-06-26 02:11:06 +02001403 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001404 def test_file_not_found_includes_filename(self):
1405 with self.assertRaises(FileNotFoundError) as c:
1406 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1407 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1408
Victor Stinner937ee9e2018-06-26 02:11:06 +02001409 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001410 def test_file_not_found_with_bad_cwd(self):
1411 with self.assertRaises(FileNotFoundError) as c:
1412 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1413 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1414
Gregory P. Smith6e730002015-04-14 16:14:25 -07001415
1416class RunFuncTestCase(BaseTestCase):
1417 def run_python(self, code, **kwargs):
1418 """Run Python code in a subprocess using subprocess.run"""
1419 argv = [sys.executable, "-c", code]
1420 return subprocess.run(argv, **kwargs)
1421
1422 def test_returncode(self):
1423 # call() function with sequence argument
1424 cp = self.run_python("import sys; sys.exit(47)")
1425 self.assertEqual(cp.returncode, 47)
1426 with self.assertRaises(subprocess.CalledProcessError):
1427 cp.check_returncode()
1428
1429 def test_check(self):
1430 with self.assertRaises(subprocess.CalledProcessError) as c:
1431 self.run_python("import sys; sys.exit(47)", check=True)
1432 self.assertEqual(c.exception.returncode, 47)
1433
1434 def test_check_zero(self):
1435 # check_returncode shouldn't raise when returncode is zero
1436 cp = self.run_python("import sys; sys.exit(0)", check=True)
1437 self.assertEqual(cp.returncode, 0)
1438
1439 def test_timeout(self):
1440 # run() function with timeout argument; we want to test that the child
1441 # process gets killed when the timeout expires. If the child isn't
1442 # killed, this call will deadlock since subprocess.run waits for the
1443 # child.
1444 with self.assertRaises(subprocess.TimeoutExpired):
1445 self.run_python("while True: pass", timeout=0.0001)
1446
1447 def test_capture_stdout(self):
1448 # capture stdout with zero return code
1449 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1450 self.assertIn(b'BDFL', cp.stdout)
1451
1452 def test_capture_stderr(self):
1453 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1454 stderr=subprocess.PIPE)
1455 self.assertIn(b'BDFL', cp.stderr)
1456
1457 def test_check_output_stdin_arg(self):
1458 # run() can be called with stdin set to a file
1459 tf = tempfile.TemporaryFile()
1460 self.addCleanup(tf.close)
1461 tf.write(b'pear')
1462 tf.seek(0)
1463 cp = self.run_python(
1464 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1465 stdin=tf, stdout=subprocess.PIPE)
1466 self.assertIn(b'PEAR', cp.stdout)
1467
1468 def test_check_output_input_arg(self):
1469 # check_output() can be called with input set to a string
1470 cp = self.run_python(
1471 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1472 input=b'pear', stdout=subprocess.PIPE)
1473 self.assertIn(b'PEAR', cp.stdout)
1474
1475 def test_check_output_stdin_with_input_arg(self):
1476 # run() refuses to accept 'stdin' with 'input'
1477 tf = tempfile.TemporaryFile()
1478 self.addCleanup(tf.close)
1479 tf.write(b'pear')
1480 tf.seek(0)
1481 with self.assertRaises(ValueError,
1482 msg="Expected ValueError when stdin and input args supplied.") as c:
1483 output = self.run_python("print('will not be run')",
1484 stdin=tf, input=b'hare')
1485 self.assertIn('stdin', c.exception.args[0])
1486 self.assertIn('input', c.exception.args[0])
1487
1488 def test_check_output_timeout(self):
1489 with self.assertRaises(subprocess.TimeoutExpired) as c:
1490 cp = self.run_python((
1491 "import sys, time\n"
1492 "sys.stdout.write('BDFL')\n"
1493 "sys.stdout.flush()\n"
1494 "time.sleep(3600)"),
1495 # Some heavily loaded buildbots (sparc Debian 3.x) require
1496 # this much time to start and print.
1497 timeout=3, stdout=subprocess.PIPE)
1498 self.assertEqual(c.exception.output, b'BDFL')
1499 # output is aliased to stdout
1500 self.assertEqual(c.exception.stdout, b'BDFL')
1501
1502 def test_run_kwargs(self):
1503 newenv = os.environ.copy()
1504 newenv["FRUIT"] = "banana"
1505 cp = self.run_python(('import sys, os;'
1506 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1507 env=newenv)
1508 self.assertEqual(cp.returncode, 33)
1509
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001510 def test_run_with_pathlike_path(self):
1511 # bpo-31961: test run(pathlike_object)
1512 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001513 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001514 prog = 'tree.com' if mswindows else 'ls'
1515 path = shutil.which(prog)
1516 if path is None:
1517 self.skipTest(f'{prog} required for this test')
1518 path = FakePath(path)
1519 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1520 self.assertEqual(res.returncode, 0)
1521 with self.assertRaises(TypeError):
1522 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1523
1524 def test_run_with_bytes_path_and_arguments(self):
1525 # bpo-31961: test run([bytes_object, b'additional arguments'])
1526 path = os.fsencode(sys.executable)
1527 args = [path, '-c', b'import sys; sys.exit(57)']
1528 res = subprocess.run(args)
1529 self.assertEqual(res.returncode, 57)
1530
1531 def test_run_with_pathlike_path_and_arguments(self):
1532 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1533 path = FakePath(sys.executable)
1534 args = [path, '-c', 'import sys; sys.exit(57)']
1535 res = subprocess.run(args)
1536 self.assertEqual(res.returncode, 57)
1537
Bo Baylesce0f33d2018-01-30 00:40:39 -06001538 def test_capture_output(self):
1539 cp = self.run_python(("import sys;"
1540 "sys.stdout.write('BDFL'); "
1541 "sys.stderr.write('FLUFL')"),
1542 capture_output=True)
1543 self.assertIn(b'BDFL', cp.stdout)
1544 self.assertIn(b'FLUFL', cp.stderr)
1545
1546 def test_stdout_with_capture_output_arg(self):
1547 # run() refuses to accept 'stdout' with 'capture_output'
1548 tf = tempfile.TemporaryFile()
1549 self.addCleanup(tf.close)
1550 with self.assertRaises(ValueError,
1551 msg=("Expected ValueError when stdout and capture_output "
1552 "args supplied.")) as c:
1553 output = self.run_python("print('will not be run')",
1554 capture_output=True, stdout=tf)
1555 self.assertIn('stdout', c.exception.args[0])
1556 self.assertIn('capture_output', c.exception.args[0])
1557
1558 def test_stderr_with_capture_output_arg(self):
1559 # run() refuses to accept 'stderr' with 'capture_output'
1560 tf = tempfile.TemporaryFile()
1561 self.addCleanup(tf.close)
1562 with self.assertRaises(ValueError,
1563 msg=("Expected ValueError when stderr and capture_output "
1564 "args supplied.")) as c:
1565 output = self.run_python("print('will not be run')",
1566 capture_output=True, stderr=tf)
1567 self.assertIn('stderr', c.exception.args[0])
1568 self.assertIn('capture_output', c.exception.args[0])
1569
Gregory P. Smith580d2782019-09-11 04:23:05 -05001570 # This test _might_ wind up a bit fragile on loaded build+test machines
1571 # as it depends on the timing with wide enough margins for normal situations
1572 # but does assert that it happened "soon enough" to believe the right thing
1573 # happened.
1574 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1575 def test_run_with_shell_timeout_and_capture_output(self):
1576 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1577 before_secs = time.monotonic()
1578 try:
1579 subprocess.run('sleep 3', shell=True, timeout=0.1,
1580 capture_output=True) # New session unspecified.
1581 except subprocess.TimeoutExpired as exc:
1582 after_secs = time.monotonic()
1583 stacks = traceback.format_exc() # assertRaises doesn't give this.
1584 else:
1585 self.fail("TimeoutExpired not raised.")
1586 self.assertLess(after_secs - before_secs, 1.5,
1587 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1588 f"{stacks}```")
1589
Gregory P. Smith6e730002015-04-14 16:14:25 -07001590
Gregory P. Smith693aa802019-09-13 14:43:35 +01001591def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001592 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001593 if grp:
1594 try:
1595 grp.getgrnam(name_group)
1596 except KeyError:
1597 continue
1598 return name_group
1599 else:
1600 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1601
1602
Victor Stinner937ee9e2018-06-26 02:11:06 +02001603@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001604class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001605
Gregory P. Smith5591b022012-10-10 03:34:47 -07001606 def setUp(self):
1607 super().setUp()
1608 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1609
1610 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001611 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001612 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001613 except OSError as e:
1614 # This avoids hard coding the errno value or the OS perror()
1615 # string and instead capture the exception that we want to see
1616 # below for comparison.
1617 desired_exception = e
1618 else:
Martin Pantereb995702016-07-28 01:11:04 +00001619 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001620 self._nonexistent_dir)
1621 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001622
Gregory P. Smith5591b022012-10-10 03:34:47 -07001623 def test_exception_cwd(self):
1624 """Test error in the child raised in the parent for a bad cwd."""
1625 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001626 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001627 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001628 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001629 except OSError as e:
1630 # Test that the child process chdir failure actually makes
1631 # it up to the parent process as the correct exception.
1632 self.assertEqual(desired_exception.errno, e.errno)
1633 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001634 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001635 else:
1636 self.fail("Expected OSError: %s" % desired_exception)
1637
Gregory P. Smith5591b022012-10-10 03:34:47 -07001638 def test_exception_bad_executable(self):
1639 """Test error in the child raised in the parent for a bad executable."""
1640 desired_exception = self._get_chdir_exception()
1641 try:
1642 p = subprocess.Popen([sys.executable, "-c", ""],
1643 executable=self._nonexistent_dir)
1644 except OSError as e:
1645 # Test that the child process exec failure actually makes
1646 # it up to the parent process as the correct exception.
1647 self.assertEqual(desired_exception.errno, e.errno)
1648 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001649 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001650 else:
1651 self.fail("Expected OSError: %s" % desired_exception)
1652
1653 def test_exception_bad_args_0(self):
1654 """Test error in the child raised in the parent for a bad args[0]."""
1655 desired_exception = self._get_chdir_exception()
1656 try:
1657 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1658 except OSError as e:
1659 # Test that the child process exec 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. Smith5591b022012-10-10 03:34:47 -07001664 else:
1665 self.fail("Expected OSError: %s" % desired_exception)
1666
Ammar Askar3fc499b2017-09-06 02:41:30 -04001667 # We mock the __del__ method for Popen in the next two tests
1668 # because it does cleanup based on the pid returned by fork_exec
1669 # along with issuing a resource warning if it still exists. Since
1670 # we don't actually spawn a process in these tests we can forego
1671 # the destructor. An alternative would be to set _child_created to
1672 # False before the destructor is called but there is no easy way
1673 # to do that
1674 class PopenNoDestructor(subprocess.Popen):
1675 def __del__(self):
1676 pass
1677
1678 @mock.patch("subprocess._posixsubprocess.fork_exec")
1679 def test_exception_errpipe_normal(self, fork_exec):
1680 """Test error passing done through errpipe_write in the good case"""
1681 def proper_error(*args):
1682 errpipe_write = args[13]
1683 # Write the hex for the error code EISDIR: 'is a directory'
1684 err_code = '{:x}'.format(errno.EISDIR).encode()
1685 os.write(errpipe_write, b"OSError:" + err_code + b":")
1686 return 0
1687
1688 fork_exec.side_effect = proper_error
1689
Victor Stinner11045c92017-10-05 06:32:53 -07001690 with mock.patch("subprocess.os.waitpid",
1691 side_effect=ChildProcessError):
1692 with self.assertRaises(IsADirectoryError):
1693 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001694
1695 @mock.patch("subprocess._posixsubprocess.fork_exec")
1696 def test_exception_errpipe_bad_data(self, fork_exec):
1697 """Test error passing done through errpipe_write where its not
1698 in the expected format"""
1699 error_data = b"\xFF\x00\xDE\xAD"
1700 def bad_error(*args):
1701 errpipe_write = args[13]
1702 # Anything can be in the pipe, no assumptions should
1703 # be made about its encoding, so we'll write some
1704 # arbitrary hex bytes to test it out
1705 os.write(errpipe_write, error_data)
1706 return 0
1707
1708 fork_exec.side_effect = bad_error
1709
Victor Stinner11045c92017-10-05 06:32:53 -07001710 with mock.patch("subprocess.os.waitpid",
1711 side_effect=ChildProcessError):
1712 with self.assertRaises(subprocess.SubprocessError) as e:
1713 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001714
1715 self.assertIn(repr(error_data), str(e.exception))
1716
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001717 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1718 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001719 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001720 # Blindly assume that cat exists on systems with /proc/self/status...
1721 default_proc_status = subprocess.check_output(
1722 ['cat', '/proc/self/status'],
1723 restore_signals=False)
1724 for line in default_proc_status.splitlines():
1725 if line.startswith(b'SigIgn'):
1726 default_sig_ign_mask = line
1727 break
1728 else:
1729 self.skipTest("SigIgn not found in /proc/self/status.")
1730 restored_proc_status = subprocess.check_output(
1731 ['cat', '/proc/self/status'],
1732 restore_signals=True)
1733 for line in restored_proc_status.splitlines():
1734 if line.startswith(b'SigIgn'):
1735 restored_sig_ign_mask = line
1736 break
1737 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1738 msg="restore_signals=True should've unblocked "
1739 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001740
1741 def test_start_new_session(self):
1742 # For code coverage of calling setsid(). We don't care if we get an
1743 # EPERM error from it depending on the test execution environment, that
1744 # still indicates that it was called.
1745 try:
1746 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001747 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001748 start_new_session=True)
1749 except OSError as e:
1750 if e.errno != errno.EPERM:
1751 raise
1752 else:
Victor Stinner58840432019-06-14 19:31:43 +02001753 parent_sid = os.getsid(0)
1754 child_sid = int(output)
1755 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001756
Patrick McLean2b2ead72019-09-12 10:15:44 -07001757 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1758 def test_user(self):
1759 # For code coverage of the user parameter. We don't care if we get an
1760 # EPERM error from it depending on the test execution environment, that
1761 # still indicates that it was called.
1762
1763 uid = os.geteuid()
1764 test_users = [65534 if uid != 65534 else 65533, uid]
1765 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1766
1767 if pwd is not None:
1768 test_users.append(name_uid)
1769
1770 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001771 # posix_spawn() may be used with close_fds=False
1772 for close_fds in (False, True):
1773 with self.subTest(user=user, close_fds=close_fds):
1774 try:
1775 output = subprocess.check_output(
1776 [sys.executable, "-c",
1777 "import os; print(os.getuid())"],
1778 user=user,
1779 close_fds=close_fds)
1780 except PermissionError: # (EACCES, EPERM)
1781 pass
1782 except OSError as e:
1783 if e.errno not in (errno.EACCES, errno.EPERM):
1784 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001785 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001786 if isinstance(user, str):
1787 user_uid = pwd.getpwnam(user).pw_uid
1788 else:
1789 user_uid = user
1790 child_user = int(output)
1791 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001792
1793 with self.assertRaises(ValueError):
1794 subprocess.check_call([sys.executable, "-c", "pass"], user=-1)
1795
1796 if pwd is None:
1797 with self.assertRaises(ValueError):
1798 subprocess.check_call([sys.executable, "-c", "pass"], user=name_uid)
1799
1800 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1801 def test_user_error(self):
1802 with self.assertRaises(ValueError):
1803 subprocess.check_call([sys.executable, "-c", "pass"], user=65535)
1804
1805 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1806 def test_group(self):
1807 gid = os.getegid()
1808 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001809 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001810
1811 if grp is not None:
1812 group_list.append(name_group)
1813
1814 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001815 # posix_spawn() may be used with close_fds=False
1816 for close_fds in (False, True):
1817 with self.subTest(group=group, close_fds=close_fds):
1818 try:
1819 output = subprocess.check_output(
1820 [sys.executable, "-c",
1821 "import os; print(os.getgid())"],
1822 group=group,
1823 close_fds=close_fds)
1824 except PermissionError: # (EACCES, EPERM)
1825 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001826 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001827 if isinstance(group, str):
1828 group_gid = grp.getgrnam(group).gr_gid
1829 else:
1830 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001831
Victor Stinnerfaca8552019-09-25 15:52:49 +02001832 child_group = int(output)
1833 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001834
1835 # make sure we bomb on negative values
1836 with self.assertRaises(ValueError):
1837 subprocess.check_call([sys.executable, "-c", "pass"], group=-1)
1838
1839 if grp is None:
1840 with self.assertRaises(ValueError):
1841 subprocess.check_call([sys.executable, "-c", "pass"], group=name_group)
1842
1843 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1844 def test_group_error(self):
1845 with self.assertRaises(ValueError):
1846 subprocess.check_call([sys.executable, "-c", "pass"], group=65535)
1847
1848 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1849 def test_extra_groups(self):
1850 gid = os.getegid()
1851 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001852 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001853 perm_error = False
1854
1855 if grp is not None:
1856 group_list.append(name_group)
1857
1858 try:
1859 output = subprocess.check_output(
1860 [sys.executable, "-c",
1861 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1862 extra_groups=group_list)
1863 except OSError as ex:
1864 if ex.errno != errno.EPERM:
1865 raise
1866 perm_error = True
1867
1868 else:
1869 parent_groups = os.getgroups()
1870 child_groups = json.loads(output)
1871
1872 if grp is not None:
1873 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
1874 for g in group_list]
1875 else:
1876 desired_gids = group_list
1877
1878 if perm_error:
1879 self.assertEqual(set(child_groups), set(parent_groups))
1880 else:
1881 self.assertEqual(set(desired_gids), set(child_groups))
1882
1883 # make sure we bomb on negative values
1884 with self.assertRaises(ValueError):
1885 subprocess.check_call([sys.executable, "-c", "pass"], extra_groups=[-1])
1886
1887 if grp is None:
1888 with self.assertRaises(ValueError):
1889 subprocess.check_call([sys.executable, "-c", "pass"],
1890 extra_groups=[name_group])
1891
1892 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
1893 def test_extra_groups_error(self):
1894 with self.assertRaises(ValueError):
1895 subprocess.check_call([sys.executable, "-c", "pass"], extra_groups=[])
1896
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001897 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
1898 'POSIX umask() is not available.')
1899 def test_umask(self):
1900 tmpdir = None
1901 try:
1902 tmpdir = tempfile.mkdtemp()
1903 name = os.path.join(tmpdir, "beans")
1904 # We set an unusual umask in the child so as a unique mode
1905 # for us to test the child's touched file for.
1906 subprocess.check_call(
1907 [sys.executable, "-c", f"open({name!r}, 'w')"], # touch
1908 umask=0o053)
1909 # Ignore execute permissions entirely in our test,
1910 # filesystems could be mounted to ignore or force that.
1911 st_mode = os.stat(name).st_mode & 0o666
1912 expected_mode = 0o624
1913 self.assertEqual(expected_mode, st_mode,
1914 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
1915 finally:
1916 if tmpdir is not None:
1917 shutil.rmtree(tmpdir)
1918
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001919 def test_run_abort(self):
1920 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001921 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001922 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001923 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001924 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001925 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001926
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001927 def test_CalledProcessError_str_signal(self):
1928 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1929 error_string = str(err)
1930 # We're relying on the repr() of the signal.Signals intenum to provide
1931 # the word signal, the signal name and the numeric value.
1932 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001933 # We're not being specific about the signal name as some signals have
1934 # multiple names and which name is revealed can vary.
1935 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001936 self.assertIn(str(signal.SIGABRT), error_string)
1937
1938 def test_CalledProcessError_str_unknown_signal(self):
1939 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1940 error_string = str(err)
1941 self.assertIn("unknown signal 9876543.", error_string)
1942
1943 def test_CalledProcessError_str_non_zero(self):
1944 err = subprocess.CalledProcessError(2, "fake cmd")
1945 error_string = str(err)
1946 self.assertIn("non-zero exit status 2.", error_string)
1947
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001948 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001949 # DISCLAIMER: Setting environment variables is *not* a good use
1950 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001951 p = subprocess.Popen([sys.executable, "-c",
1952 'import sys,os;'
1953 'sys.stdout.write(os.getenv("FRUIT"))'],
1954 stdout=subprocess.PIPE,
1955 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001956 with p:
1957 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001958
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001959 def test_preexec_exception(self):
1960 def raise_it():
1961 raise ValueError("What if two swallows carried a coconut?")
1962 try:
1963 p = subprocess.Popen([sys.executable, "-c", ""],
1964 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001965 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001966 self.assertTrue(
1967 subprocess._posixsubprocess,
1968 "Expected a ValueError from the preexec_fn")
1969 except ValueError as e:
1970 self.assertIn("coconut", e.args[0])
1971 else:
1972 self.fail("Exception raised by preexec_fn did not make it "
1973 "to the parent process.")
1974
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001975 class _TestExecuteChildPopen(subprocess.Popen):
1976 """Used to test behavior at the end of _execute_child."""
1977 def __init__(self, testcase, *args, **kwargs):
1978 self._testcase = testcase
1979 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001980
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001981 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001982 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001983 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001984 finally:
1985 # Open a bunch of file descriptors and verify that
1986 # none of them are the same as the ones the Popen
1987 # instance is using for stdin/stdout/stderr.
1988 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1989 for _ in range(8)]
1990 try:
1991 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001992 self._testcase.assertNotIn(
1993 fd, (self.stdin.fileno(), self.stdout.fileno(),
1994 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001995 msg="At least one fd was closed early.")
1996 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001997 for fd in devzero_fds:
1998 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001999
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002000 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2001 def test_preexec_errpipe_does_not_double_close_pipes(self):
2002 """Issue16140: Don't double close pipes on preexec error."""
2003
2004 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002005 raise subprocess.SubprocessError(
2006 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002007
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002008 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002009 self._TestExecuteChildPopen(
2010 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08002011 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2012 stderr=subprocess.PIPE, preexec_fn=raise_it)
2013
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002014 def test_preexec_gc_module_failure(self):
2015 # This tests the code that disables garbage collection if the child
2016 # process will execute any Python.
2017 def raise_runtime_error():
2018 raise RuntimeError("this shouldn't escape")
2019 enabled = gc.isenabled()
2020 orig_gc_disable = gc.disable
2021 orig_gc_isenabled = gc.isenabled
2022 try:
2023 gc.disable()
2024 self.assertFalse(gc.isenabled())
2025 subprocess.call([sys.executable, '-c', ''],
2026 preexec_fn=lambda: None)
2027 self.assertFalse(gc.isenabled(),
2028 "Popen enabled gc when it shouldn't.")
2029
2030 gc.enable()
2031 self.assertTrue(gc.isenabled())
2032 subprocess.call([sys.executable, '-c', ''],
2033 preexec_fn=lambda: None)
2034 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2035
2036 gc.disable = raise_runtime_error
2037 self.assertRaises(RuntimeError, subprocess.Popen,
2038 [sys.executable, '-c', ''],
2039 preexec_fn=lambda: None)
2040
2041 del gc.isenabled # force an AttributeError
2042 self.assertRaises(AttributeError, subprocess.Popen,
2043 [sys.executable, '-c', ''],
2044 preexec_fn=lambda: None)
2045 finally:
2046 gc.disable = orig_gc_disable
2047 gc.isenabled = orig_gc_isenabled
2048 if not enabled:
2049 gc.disable()
2050
Martin Panterf7fdbda2015-12-05 09:51:52 +00002051 @unittest.skipIf(
2052 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002053 def test_preexec_fork_failure(self):
2054 # The internal code did not preserve the previous exception when
2055 # re-enabling garbage collection
2056 try:
2057 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2058 except ImportError as err:
2059 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2060 limits = getrlimit(RLIMIT_NPROC)
2061 [_, hard] = limits
2062 setrlimit(RLIMIT_NPROC, (0, hard))
2063 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002064 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002065 subprocess.call([sys.executable, '-c', ''],
2066 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002067 except BlockingIOError:
2068 # Forking should raise EAGAIN, translated to BlockingIOError
2069 pass
2070 else:
2071 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002072
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002073 def test_args_string(self):
2074 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002075 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002076 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002077 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002078 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002079 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2080 sys.executable)
2081 os.chmod(fname, 0o700)
2082 p = subprocess.Popen(fname)
2083 p.wait()
2084 os.remove(fname)
2085 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002086
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002087 def test_invalid_args(self):
2088 # invalid arguments should raise ValueError
2089 self.assertRaises(ValueError, subprocess.call,
2090 [sys.executable, "-c",
2091 "import sys; sys.exit(47)"],
2092 startupinfo=47)
2093 self.assertRaises(ValueError, subprocess.call,
2094 [sys.executable, "-c",
2095 "import sys; sys.exit(47)"],
2096 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002097
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002098 def test_shell_sequence(self):
2099 # Run command through the shell (sequence)
2100 newenv = os.environ.copy()
2101 newenv["FRUIT"] = "apple"
2102 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2103 stdout=subprocess.PIPE,
2104 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002105 with p:
2106 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002107
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002108 def test_shell_string(self):
2109 # Run command through the shell (string)
2110 newenv = os.environ.copy()
2111 newenv["FRUIT"] = "apple"
2112 p = subprocess.Popen("echo $FRUIT", shell=1,
2113 stdout=subprocess.PIPE,
2114 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002115 with p:
2116 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002117
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002118 def test_call_string(self):
2119 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002120 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002121 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002122 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002123 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002124 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2125 sys.executable)
2126 os.chmod(fname, 0o700)
2127 rc = subprocess.call(fname)
2128 os.remove(fname)
2129 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002130
Stefan Krah9542cc62010-07-19 14:20:53 +00002131 def test_specific_shell(self):
2132 # Issue #9265: Incorrect name passed as arg[0].
2133 shells = []
2134 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2135 for name in ['bash', 'ksh']:
2136 sh = os.path.join(prefix, name)
2137 if os.path.isfile(sh):
2138 shells.append(sh)
2139 if not shells: # Will probably work for any shell but csh.
2140 self.skipTest("bash or ksh required for this test")
2141 sh = '/bin/sh'
2142 if os.path.isfile(sh) and not os.path.islink(sh):
2143 # Test will fail if /bin/sh is a symlink to csh.
2144 shells.append(sh)
2145 for sh in shells:
2146 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2147 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002148 with p:
2149 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002150
Florent Xicluna4886d242010-03-08 13:27:26 +00002151 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002152 # Do not inherit file handles from the parent.
2153 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002154 # Also set the SIGINT handler to the default to make sure it's not
2155 # being ignored (some tests rely on that.)
2156 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2157 try:
2158 p = subprocess.Popen([sys.executable, "-c", """if 1:
2159 import sys, time
2160 sys.stdout.write('x\\n')
2161 sys.stdout.flush()
2162 time.sleep(30)
2163 """],
2164 close_fds=True,
2165 stdin=subprocess.PIPE,
2166 stdout=subprocess.PIPE,
2167 stderr=subprocess.PIPE)
2168 finally:
2169 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002170 # Wait for the interpreter to be completely initialized before
2171 # sending any signal.
2172 p.stdout.read(1)
2173 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002174 return p
2175
Charles-François Natali53221e32013-01-12 16:52:20 +01002176 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2177 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002178 def _kill_dead_process(self, method, *args):
2179 # Do not inherit file handles from the parent.
2180 # It should fix failures on some platforms.
2181 p = subprocess.Popen([sys.executable, "-c", """if 1:
2182 import sys, time
2183 sys.stdout.write('x\\n')
2184 sys.stdout.flush()
2185 """],
2186 close_fds=True,
2187 stdin=subprocess.PIPE,
2188 stdout=subprocess.PIPE,
2189 stderr=subprocess.PIPE)
2190 # Wait for the interpreter to be completely initialized before
2191 # sending any signal.
2192 p.stdout.read(1)
2193 # The process should end after this
2194 time.sleep(1)
2195 # This shouldn't raise even though the child is now dead
2196 getattr(p, method)(*args)
2197 p.communicate()
2198
Florent Xicluna4886d242010-03-08 13:27:26 +00002199 def test_send_signal(self):
2200 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002201 _, stderr = p.communicate()
2202 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002203 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002204
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002205 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002206 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002207 _, stderr = p.communicate()
2208 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002209 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002210
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002211 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002212 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002213 _, stderr = p.communicate()
2214 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002215 self.assertEqual(p.wait(), -signal.SIGTERM)
2216
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002217 def test_send_signal_dead(self):
2218 # Sending a signal to a dead process
2219 self._kill_dead_process('send_signal', signal.SIGINT)
2220
2221 def test_kill_dead(self):
2222 # Killing a dead process
2223 self._kill_dead_process('kill')
2224
2225 def test_terminate_dead(self):
2226 # Terminating a dead process
2227 self._kill_dead_process('terminate')
2228
Victor Stinnerdaf45552013-08-28 00:53:59 +02002229 def _save_fds(self, save_fds):
2230 fds = []
2231 for fd in save_fds:
2232 inheritable = os.get_inheritable(fd)
2233 saved = os.dup(fd)
2234 fds.append((fd, saved, inheritable))
2235 return fds
2236
2237 def _restore_fds(self, fds):
2238 for fd, saved, inheritable in fds:
2239 os.dup2(saved, fd, inheritable=inheritable)
2240 os.close(saved)
2241
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002242 def check_close_std_fds(self, fds):
2243 # Issue #9905: test that subprocess pipes still work properly with
2244 # some standard fds closed
2245 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002246 saved_fds = self._save_fds(fds)
2247 for fd, saved, inheritable in saved_fds:
2248 if fd == 0:
2249 stdin = saved
2250 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002251 try:
2252 for fd in fds:
2253 os.close(fd)
2254 out, err = subprocess.Popen([sys.executable, "-c",
2255 'import sys;'
2256 'sys.stdout.write("apple");'
2257 'sys.stdout.flush();'
2258 'sys.stderr.write("orange")'],
2259 stdin=stdin,
2260 stdout=subprocess.PIPE,
2261 stderr=subprocess.PIPE).communicate()
2262 err = support.strip_python_stderr(err)
2263 self.assertEqual((out, err), (b'apple', b'orange'))
2264 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002265 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002266
2267 def test_close_fd_0(self):
2268 self.check_close_std_fds([0])
2269
2270 def test_close_fd_1(self):
2271 self.check_close_std_fds([1])
2272
2273 def test_close_fd_2(self):
2274 self.check_close_std_fds([2])
2275
2276 def test_close_fds_0_1(self):
2277 self.check_close_std_fds([0, 1])
2278
2279 def test_close_fds_0_2(self):
2280 self.check_close_std_fds([0, 2])
2281
2282 def test_close_fds_1_2(self):
2283 self.check_close_std_fds([1, 2])
2284
2285 def test_close_fds_0_1_2(self):
2286 # Issue #10806: test that subprocess pipes still work properly with
2287 # all standard fds closed.
2288 self.check_close_std_fds([0, 1, 2])
2289
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002290 def test_small_errpipe_write_fd(self):
2291 """Issue #15798: Popen should work when stdio fds are available."""
2292 new_stdin = os.dup(0)
2293 new_stdout = os.dup(1)
2294 try:
2295 os.close(0)
2296 os.close(1)
2297
2298 # Side test: if errpipe_write fails to have its CLOEXEC
2299 # flag set this should cause the parent to think the exec
2300 # failed. Extremely unlikely: everyone supports CLOEXEC.
2301 subprocess.Popen([
2302 sys.executable, "-c",
2303 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2304 finally:
2305 # Restore original stdin and stdout
2306 os.dup2(new_stdin, 0)
2307 os.dup2(new_stdout, 1)
2308 os.close(new_stdin)
2309 os.close(new_stdout)
2310
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002311 def test_remapping_std_fds(self):
2312 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002313 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002314 try:
2315 temp_fds = [fd for fd, fname in temps]
2316
2317 # unlink the files -- we won't need to reopen them
2318 for fd, fname in temps:
2319 os.unlink(fname)
2320
2321 # write some data to what will become stdin, and rewind
2322 os.write(temp_fds[1], b"STDIN")
2323 os.lseek(temp_fds[1], 0, 0)
2324
2325 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002326 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002327 try:
2328 # duplicate the file objects over the standard fd's
2329 for fd, temp_fd in enumerate(temp_fds):
2330 os.dup2(temp_fd, fd)
2331
2332 # now use those files in the "wrong" order, so that subprocess
2333 # has to rearrange them in the child
2334 p = subprocess.Popen([sys.executable, "-c",
2335 'import sys; got = sys.stdin.read();'
2336 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2337 stdin=temp_fds[1],
2338 stdout=temp_fds[2],
2339 stderr=temp_fds[0])
2340 p.wait()
2341 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002342 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002343
2344 for fd in temp_fds:
2345 os.lseek(fd, 0, 0)
2346
2347 out = os.read(temp_fds[2], 1024)
2348 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2349 self.assertEqual(out, b"got STDIN")
2350 self.assertEqual(err, b"err")
2351
2352 finally:
2353 for fd in temp_fds:
2354 os.close(fd)
2355
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002356 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2357 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002358 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002359 temp_fds = [fd for fd, fname in temps]
2360 try:
2361 # unlink the files -- we won't need to reopen them
2362 for fd, fname in temps:
2363 os.unlink(fname)
2364
2365 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002366 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002367 try:
2368 # duplicate the temp files over the standard fd's 0, 1, 2
2369 for fd, temp_fd in enumerate(temp_fds):
2370 os.dup2(temp_fd, fd)
2371
2372 # write some data to what will become stdin, and rewind
2373 os.write(stdin_no, b"STDIN")
2374 os.lseek(stdin_no, 0, 0)
2375
2376 # now use those files in the given order, so that subprocess
2377 # has to rearrange them in the child
2378 p = subprocess.Popen([sys.executable, "-c",
2379 'import sys; got = sys.stdin.read();'
2380 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2381 stdin=stdin_no,
2382 stdout=stdout_no,
2383 stderr=stderr_no)
2384 p.wait()
2385
2386 for fd in temp_fds:
2387 os.lseek(fd, 0, 0)
2388
2389 out = os.read(stdout_no, 1024)
2390 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2391 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002392 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002393
2394 self.assertEqual(out, b"got STDIN")
2395 self.assertEqual(err, b"err")
2396
2397 finally:
2398 for fd in temp_fds:
2399 os.close(fd)
2400
2401 # When duping fds, if there arises a situation where one of the fds is
2402 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2403 # This tests all combinations of this.
2404 def test_swap_fds(self):
2405 self.check_swap_fds(0, 1, 2)
2406 self.check_swap_fds(0, 2, 1)
2407 self.check_swap_fds(1, 0, 2)
2408 self.check_swap_fds(1, 2, 0)
2409 self.check_swap_fds(2, 0, 1)
2410 self.check_swap_fds(2, 1, 0)
2411
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002412 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2413 saved_fds = self._save_fds(range(3))
2414 try:
2415 for from_fd in from_fds:
2416 with tempfile.TemporaryFile() as f:
2417 os.dup2(f.fileno(), from_fd)
2418
2419 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2420 os.close(fd_to_close)
2421
2422 arg_names = ['stdin', 'stdout', 'stderr']
2423 kwargs = {}
2424 for from_fd, to_fd in zip(from_fds, to_fds):
2425 kwargs[arg_names[to_fd]] = from_fd
2426
2427 code = textwrap.dedent(r'''
2428 import os, sys
2429 skipped_fd = int(sys.argv[1])
2430 for fd in range(3):
2431 if fd != skipped_fd:
2432 os.write(fd, str(fd).encode('ascii'))
2433 ''')
2434
2435 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2436
2437 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2438 **kwargs)
2439 self.assertEqual(rc, 0)
2440
2441 for from_fd, to_fd in zip(from_fds, to_fds):
2442 os.lseek(from_fd, 0, os.SEEK_SET)
2443 read_bytes = os.read(from_fd, 1024)
2444 read_fds = list(map(int, read_bytes.decode('ascii')))
2445 msg = textwrap.dedent(f"""
2446 When testing {from_fds} to {to_fds} redirection,
2447 parent descriptor {from_fd} got redirected
2448 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2449 """)
2450 self.assertEqual([to_fd], read_fds, msg)
2451 finally:
2452 self._restore_fds(saved_fds)
2453
2454 # Check that subprocess can remap std fds correctly even
2455 # if one of them is closed (#32844).
2456 def test_swap_std_fds_with_one_closed(self):
2457 for from_fds in itertools.combinations(range(3), 2):
2458 for to_fds in itertools.permutations(range(3), 2):
2459 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2460
Victor Stinner13bb71c2010-04-23 21:41:56 +00002461 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002462 def prepare():
2463 raise ValueError("surrogate:\uDCff")
2464
2465 try:
2466 subprocess.call(
2467 [sys.executable, "-c", "pass"],
2468 preexec_fn=prepare)
2469 except ValueError as err:
2470 # Pure Python implementations keeps the message
2471 self.assertIsNone(subprocess._posixsubprocess)
2472 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002473 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002474 # _posixsubprocess uses a default message
2475 self.assertIsNotNone(subprocess._posixsubprocess)
2476 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2477 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002478 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002479
Victor Stinner13bb71c2010-04-23 21:41:56 +00002480 def test_undecodable_env(self):
2481 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002482 encoded_value = value.encode("ascii", "surrogateescape")
2483
Victor Stinner13bb71c2010-04-23 21:41:56 +00002484 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002485 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002486 env = os.environ.copy()
2487 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002488 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002489 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002490 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002491 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002492 stdout = subprocess.check_output(
2493 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002494 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002495 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002496 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002497
2498 # test bytes
2499 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002500 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002501 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002502 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002503 stdout = subprocess.check_output(
2504 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002505 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002506 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002507 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002508
Victor Stinnerb745a742010-05-18 17:17:23 +00002509 def test_bytes_program(self):
2510 abs_program = os.fsencode(sys.executable)
2511 path, program = os.path.split(sys.executable)
2512 program = os.fsencode(program)
2513
2514 # absolute bytes path
2515 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002516 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002517
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002518 # absolute bytes path as a string
2519 cmd = b"'" + abs_program + b"' -c pass"
2520 exitcode = subprocess.call(cmd, shell=True)
2521 self.assertEqual(exitcode, 0)
2522
Victor Stinnerb745a742010-05-18 17:17:23 +00002523 # bytes program, unicode PATH
2524 env = os.environ.copy()
2525 env["PATH"] = path
2526 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002527 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002528
2529 # bytes program, bytes PATH
2530 envb = os.environb.copy()
2531 envb[b"PATH"] = os.fsencode(path)
2532 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002533 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002534
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002535 def test_pipe_cloexec(self):
2536 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2537 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2538
2539 p1 = subprocess.Popen([sys.executable, sleeper],
2540 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2541 stderr=subprocess.PIPE, close_fds=False)
2542
2543 self.addCleanup(p1.communicate, b'')
2544
2545 p2 = subprocess.Popen([sys.executable, fd_status],
2546 stdout=subprocess.PIPE, close_fds=False)
2547
2548 output, error = p2.communicate()
2549 result_fds = set(map(int, output.split(b',')))
2550 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2551 p1.stderr.fileno()])
2552
2553 self.assertFalse(result_fds & unwanted_fds,
2554 "Expected no fds from %r to be open in child, "
2555 "found %r" %
2556 (unwanted_fds, result_fds & unwanted_fds))
2557
2558 def test_pipe_cloexec_real_tools(self):
2559 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2560 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2561
2562 subdata = b'zxcvbn'
2563 data = subdata * 4 + b'\n'
2564
2565 p1 = subprocess.Popen([sys.executable, qcat],
2566 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2567 close_fds=False)
2568
2569 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2570 stdin=p1.stdout, stdout=subprocess.PIPE,
2571 close_fds=False)
2572
2573 self.addCleanup(p1.wait)
2574 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002575 def kill_p1():
2576 try:
2577 p1.terminate()
2578 except ProcessLookupError:
2579 pass
2580 def kill_p2():
2581 try:
2582 p2.terminate()
2583 except ProcessLookupError:
2584 pass
2585 self.addCleanup(kill_p1)
2586 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002587
2588 p1.stdin.write(data)
2589 p1.stdin.close()
2590
2591 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2592
2593 self.assertTrue(readfiles, "The child hung")
2594 self.assertEqual(p2.stdout.read(), data)
2595
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002596 p1.stdout.close()
2597 p2.stdout.close()
2598
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002599 def test_close_fds(self):
2600 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2601
2602 fds = os.pipe()
2603 self.addCleanup(os.close, fds[0])
2604 self.addCleanup(os.close, fds[1])
2605
2606 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002607 # add a bunch more fds
2608 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002609 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002610 self.addCleanup(os.close, fd)
2611 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002612
Victor Stinnerdaf45552013-08-28 00:53:59 +02002613 for fd in open_fds:
2614 os.set_inheritable(fd, True)
2615
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002616 p = subprocess.Popen([sys.executable, fd_status],
2617 stdout=subprocess.PIPE, close_fds=False)
2618 output, ignored = p.communicate()
2619 remaining_fds = set(map(int, output.split(b',')))
2620
2621 self.assertEqual(remaining_fds & open_fds, open_fds,
2622 "Some fds were closed")
2623
2624 p = subprocess.Popen([sys.executable, fd_status],
2625 stdout=subprocess.PIPE, close_fds=True)
2626 output, ignored = p.communicate()
2627 remaining_fds = set(map(int, output.split(b',')))
2628
2629 self.assertFalse(remaining_fds & open_fds,
2630 "Some fds were left open")
2631 self.assertIn(1, remaining_fds, "Subprocess failed")
2632
Gregory P. Smith8facece2012-01-21 14:01:08 -08002633 # Keep some of the fd's we opened open in the subprocess.
2634 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2635 fds_to_keep = set(open_fds.pop() for _ in range(8))
2636 p = subprocess.Popen([sys.executable, fd_status],
2637 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002638 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002639 output, ignored = p.communicate()
2640 remaining_fds = set(map(int, output.split(b',')))
2641
izbyshev2d8f0632017-12-19 03:26:49 +07002642 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002643 "Some fds not in pass_fds were left open")
2644 self.assertIn(1, remaining_fds, "Subprocess failed")
2645
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002646
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002647 @unittest.skipIf(sys.platform.startswith("freebsd") and
2648 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2649 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002650 def test_close_fds_when_max_fd_is_lowered(self):
2651 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2652 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2653
Gregory P. Smith634aa682014-06-15 17:51:04 -07002654 # This launches the meat of the test in a child process to
2655 # avoid messing with the larger unittest processes maximum
2656 # number of file descriptors.
2657 # This process launches:
2658 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2659 # a bunch of high open fds above the new lower rlimit.
2660 # Those are reported via stdout before launching a new
2661 # process with close_fds=False to run the actual test:
2662 # +--> The TEST: This one launches a fd_status.py
2663 # subprocess with close_fds=True so we can find out if
2664 # any of the fds above the lowered rlimit are still open.
2665 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2666 '''
2667 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002668 open_fds = set()
2669 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002670 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002671 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002672 open_fds.add(fd)
2673
2674 # Leave a two pairs of low ones available for use by the
2675 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002676 # We also leave 10 more open as some Python buildbots run into
2677 # "too many open files" errors during the test if we do not.
2678 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002679 os.close(fd)
2680 open_fds.remove(fd)
2681
2682 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002683 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002684 os.set_inheritable(fd, True)
2685
2686 max_fd_open = max(open_fds)
2687
Gregory P. Smith634aa682014-06-15 17:51:04 -07002688 # Communicate the open_fds to the parent unittest.TestCase process.
2689 print(','.join(map(str, sorted(open_fds))))
2690 sys.stdout.flush()
2691
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002692 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2693 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002694 # 29 is lower than the highest fds we are leaving open.
2695 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002696 # Launch a new Python interpreter with our low fd rlim_cur that
2697 # inherits open fds above that limit. It then uses subprocess
2698 # with close_fds=True to get a report of open fds in the child.
2699 # An explicit list of fds to check is passed to fd_status.py as
2700 # letting fd_status rely on its default logic would miss the
2701 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002702 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002703 [sys.executable, '-c',
2704 textwrap.dedent("""
2705 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002706 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002707 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002708 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002709 """.format(max_fd=max_fd_open+1))],
2710 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002711 finally:
2712 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002713 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002714
2715 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002716 output_lines = output.splitlines()
2717 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002718 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002719 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2720 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002721
Gregory P. Smith634aa682014-06-15 17:51:04 -07002722 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002723 msg="Some fds were left open.")
2724
2725
Victor Stinner88701e22011-06-01 13:13:04 +02002726 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2727 # descriptor of a pipe closed in the parent process is valid in the
2728 # child process according to fstat(), but the mode of the file
2729 # descriptor is invalid, and read or write raise an error.
2730 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002731 def test_pass_fds(self):
2732 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2733
2734 open_fds = set()
2735
2736 for x in range(5):
2737 fds = os.pipe()
2738 self.addCleanup(os.close, fds[0])
2739 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002740 os.set_inheritable(fds[0], True)
2741 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002742 open_fds.update(fds)
2743
2744 for fd in open_fds:
2745 p = subprocess.Popen([sys.executable, fd_status],
2746 stdout=subprocess.PIPE, close_fds=True,
2747 pass_fds=(fd, ))
2748 output, ignored = p.communicate()
2749
2750 remaining_fds = set(map(int, output.split(b',')))
2751 to_be_closed = open_fds - {fd}
2752
2753 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2754 self.assertFalse(remaining_fds & to_be_closed,
2755 "fd to be closed passed")
2756
2757 # pass_fds overrides close_fds with a warning.
2758 with self.assertWarns(RuntimeWarning) as context:
2759 self.assertFalse(subprocess.call(
2760 [sys.executable, "-c", "import sys; sys.exit(0)"],
2761 close_fds=False, pass_fds=(fd, )))
2762 self.assertIn('overriding close_fds', str(context.warning))
2763
Victor Stinnerdaf45552013-08-28 00:53:59 +02002764 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002765 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002766
2767 inheritable, non_inheritable = os.pipe()
2768 self.addCleanup(os.close, inheritable)
2769 self.addCleanup(os.close, non_inheritable)
2770 os.set_inheritable(inheritable, True)
2771 os.set_inheritable(non_inheritable, False)
2772 pass_fds = (inheritable, non_inheritable)
2773 args = [sys.executable, script]
2774 args += list(map(str, pass_fds))
2775
2776 p = subprocess.Popen(args,
2777 stdout=subprocess.PIPE, close_fds=True,
2778 pass_fds=pass_fds)
2779 output, ignored = p.communicate()
2780 fds = set(map(int, output.split(b',')))
2781
2782 # the inheritable file descriptor must be inherited, so its inheritable
2783 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002784 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002785
2786 # inheritable flag must not be changed in the parent process
2787 self.assertEqual(os.get_inheritable(inheritable), True)
2788 self.assertEqual(os.get_inheritable(non_inheritable), False)
2789
Gregory P. Smithce344102018-09-10 17:46:22 -07002790
2791 # bpo-32270: Ensure that descriptors specified in pass_fds
2792 # are inherited even if they are used in redirections.
2793 # Contributed by @izbyshev.
2794 def test_pass_fds_redirected(self):
2795 """Regression test for https://bugs.python.org/issue32270."""
2796 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2797 pass_fds = []
2798 for _ in range(2):
2799 fd = os.open(os.devnull, os.O_RDWR)
2800 self.addCleanup(os.close, fd)
2801 pass_fds.append(fd)
2802
2803 stdout_r, stdout_w = os.pipe()
2804 self.addCleanup(os.close, stdout_r)
2805 self.addCleanup(os.close, stdout_w)
2806 pass_fds.insert(1, stdout_w)
2807
2808 with subprocess.Popen([sys.executable, fd_status],
2809 stdin=pass_fds[0],
2810 stdout=pass_fds[1],
2811 stderr=pass_fds[2],
2812 close_fds=True,
2813 pass_fds=pass_fds):
2814 output = os.read(stdout_r, 1024)
2815 fds = {int(num) for num in output.split(b',')}
2816
2817 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2818
2819
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002820 def test_stdout_stdin_are_single_inout_fd(self):
2821 with io.open(os.devnull, "r+") as inout:
2822 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2823 stdout=inout, stdin=inout)
2824 p.wait()
2825
2826 def test_stdout_stderr_are_single_inout_fd(self):
2827 with io.open(os.devnull, "r+") as inout:
2828 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2829 stdout=inout, stderr=inout)
2830 p.wait()
2831
2832 def test_stderr_stdin_are_single_inout_fd(self):
2833 with io.open(os.devnull, "r+") as inout:
2834 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2835 stderr=inout, stdin=inout)
2836 p.wait()
2837
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002838 def test_wait_when_sigchild_ignored(self):
2839 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2840 sigchild_ignore = support.findfile("sigchild_ignore.py",
2841 subdir="subprocessdata")
2842 p = subprocess.Popen([sys.executable, sigchild_ignore],
2843 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2844 stdout, stderr = p.communicate()
2845 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002846 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002847 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002848
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002849 def test_select_unbuffered(self):
2850 # Issue #11459: bufsize=0 should really set the pipes as
2851 # unbuffered (and therefore let select() work properly).
2852 select = support.import_module("select")
2853 p = subprocess.Popen([sys.executable, "-c",
2854 'import sys;'
2855 'sys.stdout.write("apple")'],
2856 stdout=subprocess.PIPE,
2857 bufsize=0)
2858 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002859 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002860 try:
2861 self.assertEqual(f.read(4), b"appl")
2862 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2863 finally:
2864 p.wait()
2865
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002866 def test_zombie_fast_process_del(self):
2867 # Issue #12650: on Unix, if Popen.__del__() was called before the
2868 # process exited, it wouldn't be added to subprocess._active, and would
2869 # remain a zombie.
2870 # spawn a Popen, and delete its reference before it exits
2871 p = subprocess.Popen([sys.executable, "-c",
2872 'import sys, time;'
2873 'time.sleep(0.2)'],
2874 stdout=subprocess.PIPE,
2875 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002876 self.addCleanup(p.stdout.close)
2877 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002878 ident = id(p)
2879 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002880 with support.check_warnings(('', ResourceWarning)):
2881 p = None
2882
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002883 if mswindows:
2884 # subprocess._active is not used on Windows and is set to None.
2885 self.assertIsNone(subprocess._active)
2886 else:
2887 # check that p is in the active processes list
2888 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002889
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002890 def test_leak_fast_process_del_killed(self):
2891 # Issue #12650: on Unix, if Popen.__del__() was called before the
2892 # process exited, and the process got killed by a signal, it would never
2893 # be removed from subprocess._active, which triggered a FD and memory
2894 # leak.
2895 # spawn a Popen, delete its reference and kill it
2896 p = subprocess.Popen([sys.executable, "-c",
2897 'import time;'
2898 'time.sleep(3)'],
2899 stdout=subprocess.PIPE,
2900 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002901 self.addCleanup(p.stdout.close)
2902 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002903 ident = id(p)
2904 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002905 with support.check_warnings(('', ResourceWarning)):
2906 p = None
2907
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002908 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002909 if mswindows:
2910 # subprocess._active is not used on Windows and is set to None.
2911 self.assertIsNone(subprocess._active)
2912 else:
2913 # check that p is in the active processes list
2914 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002915
2916 # let some time for the process to exit, and create a new Popen: this
2917 # should trigger the wait() of p
2918 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002919 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002920 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002921 stdout=subprocess.PIPE,
2922 stderr=subprocess.PIPE) as proc:
2923 pass
2924 # p should have been wait()ed on, and removed from the _active list
2925 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002926 if mswindows:
2927 # subprocess._active is not used on Windows and is set to None.
2928 self.assertIsNone(subprocess._active)
2929 else:
2930 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002931
Charles-François Natali249cdc32013-08-25 18:24:45 +02002932 def test_close_fds_after_preexec(self):
2933 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2934
2935 # this FD is used as dup2() target by preexec_fn, and should be closed
2936 # in the child process
2937 fd = os.dup(1)
2938 self.addCleanup(os.close, fd)
2939
2940 p = subprocess.Popen([sys.executable, fd_status],
2941 stdout=subprocess.PIPE, close_fds=True,
2942 preexec_fn=lambda: os.dup2(1, fd))
2943 output, ignored = p.communicate()
2944
2945 remaining_fds = set(map(int, output.split(b',')))
2946
2947 self.assertNotIn(fd, remaining_fds)
2948
Victor Stinner8f437aa2014-10-05 17:25:19 +02002949 @support.cpython_only
2950 def test_fork_exec(self):
2951 # Issue #22290: fork_exec() must not crash on memory allocation failure
2952 # or other errors
2953 import _posixsubprocess
2954 gc_enabled = gc.isenabled()
2955 try:
2956 # Use a preexec function and enable the garbage collector
2957 # to force fork_exec() to re-enable the garbage collector
2958 # on error.
2959 func = lambda: None
2960 gc.enable()
2961
Victor Stinner8f437aa2014-10-05 17:25:19 +02002962 for args, exe_list, cwd, env_list in (
2963 (123, [b"exe"], None, [b"env"]),
2964 ([b"arg"], 123, None, [b"env"]),
2965 ([b"arg"], [b"exe"], 123, [b"env"]),
2966 ([b"arg"], [b"exe"], None, 123),
2967 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07002968 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02002969 _posixsubprocess.fork_exec(
2970 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002971 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002972 -1, -1, -1, -1,
2973 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07002974 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07002975 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07002976 func)
2977 # Attempt to prevent
2978 # "TypeError: fork_exec() takes exactly N arguments (M given)"
2979 # from passing the test. More refactoring to have us start
2980 # with a valid *args list, confirm a good call with that works
2981 # before mutating it in various ways to ensure that bad calls
2982 # with individual arg type errors raise a typeerror would be
2983 # ideal. Saving that for a future PR...
2984 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02002985 finally:
2986 if not gc_enabled:
2987 gc.disable()
2988
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002989 @support.cpython_only
2990 def test_fork_exec_sorted_fd_sanity_check(self):
2991 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2992 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002993 class BadInt:
2994 first = True
2995 def __init__(self, value):
2996 self.value = value
2997 def __int__(self):
2998 if self.first:
2999 self.first = False
3000 return self.value
3001 raise ValueError
3002
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003003 gc_enabled = gc.isenabled()
3004 try:
3005 gc.enable()
3006
3007 for fds_to_keep in (
3008 (-1, 2, 3, 4, 5), # Negative number.
3009 ('str', 4), # Not an int.
3010 (18, 23, 42, 2**63), # Out of range.
3011 (5, 4), # Not sorted.
3012 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003013 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003014 ):
3015 with self.assertRaises(
3016 ValueError,
3017 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3018 _posixsubprocess.fork_exec(
3019 [b"false"], [b"false"],
3020 True, fds_to_keep, None, [b"env"],
3021 -1, -1, -1, -1,
3022 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003023 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003024 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003025 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003026 self.assertIn('fds_to_keep', str(c.exception))
3027 finally:
3028 if not gc_enabled:
3029 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003030
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003031 def test_communicate_BrokenPipeError_stdin_close(self):
3032 # By not setting stdout or stderr or a timeout we force the fast path
3033 # that just calls _stdin_write() internally due to our mock.
3034 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
3035 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3036 mock_proc_stdin.close.side_effect = BrokenPipeError
3037 proc.communicate() # Should swallow BrokenPipeError from close.
3038 mock_proc_stdin.close.assert_called_with()
3039
3040 def test_communicate_BrokenPipeError_stdin_write(self):
3041 # By not setting stdout or stderr or a timeout we force the fast path
3042 # that just calls _stdin_write() internally due to our mock.
3043 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
3044 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3045 mock_proc_stdin.write.side_effect = BrokenPipeError
3046 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3047 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3048 mock_proc_stdin.close.assert_called_once_with()
3049
3050 def test_communicate_BrokenPipeError_stdin_flush(self):
3051 # Setting stdin and stdout forces the ._communicate() code path.
3052 # python -h exits faster than python -c pass (but spams stdout).
3053 proc = subprocess.Popen([sys.executable, '-h'],
3054 stdin=subprocess.PIPE,
3055 stdout=subprocess.PIPE)
3056 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3057 open(os.devnull, 'wb') as dev_null:
3058 mock_proc_stdin.flush.side_effect = BrokenPipeError
3059 # because _communicate registers a selector using proc.stdin...
3060 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3061 # _communicate() should swallow BrokenPipeError from flush.
3062 proc.communicate(b'stuff')
3063 mock_proc_stdin.flush.assert_called_once_with()
3064
3065 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3066 # Setting stdin and stdout forces the ._communicate() code path.
3067 # python -h exits faster than python -c pass (but spams stdout).
3068 proc = subprocess.Popen([sys.executable, '-h'],
3069 stdin=subprocess.PIPE,
3070 stdout=subprocess.PIPE)
3071 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3072 mock_proc_stdin.close.side_effect = BrokenPipeError
3073 # _communicate() should swallow BrokenPipeError from close.
3074 proc.communicate(timeout=999)
3075 mock_proc_stdin.close.assert_called_once_with()
3076
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003077 @unittest.skipUnless(_testcapi is not None
3078 and hasattr(_testcapi, 'W_STOPCODE'),
3079 'need _testcapi.W_STOPCODE')
3080 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003081 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003082 args = [sys.executable, '-c', 'pass']
3083 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003084
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003085 # Wait until the real process completes to avoid zombie process
3086 pid = proc.pid
3087 pid, status = os.waitpid(pid, 0)
3088 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003089
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003090 status = _testcapi.W_STOPCODE(3)
3091 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
3092 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003093
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003094 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003095
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003096
Victor Stinner937ee9e2018-06-26 02:11:06 +02003097@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003098class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003099
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003100 def test_startupinfo(self):
3101 # startupinfo argument
3102 # We uses hardcoded constants, because we do not want to
3103 # depend on win32all.
3104 STARTF_USESHOWWINDOW = 1
3105 SW_MAXIMIZE = 3
3106 startupinfo = subprocess.STARTUPINFO()
3107 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3108 startupinfo.wShowWindow = SW_MAXIMIZE
3109 # Since Python is a console process, it won't be affected
3110 # by wShowWindow, but the argument should be silently
3111 # ignored
3112 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003113 startupinfo=startupinfo)
3114
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303115 def test_startupinfo_keywords(self):
3116 # startupinfo argument
3117 # We use hardcoded constants, because we do not want to
3118 # depend on win32all.
3119 STARTF_USERSHOWWINDOW = 1
3120 SW_MAXIMIZE = 3
3121 startupinfo = subprocess.STARTUPINFO(
3122 dwFlags=STARTF_USERSHOWWINDOW,
3123 wShowWindow=SW_MAXIMIZE
3124 )
3125 # Since Python is a console process, it won't be affected
3126 # by wShowWindow, but the argument should be silently
3127 # ignored
3128 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3129 startupinfo=startupinfo)
3130
Victor Stinner483422f2018-07-05 22:54:17 +02003131 def test_startupinfo_copy(self):
3132 # bpo-34044: Popen must not modify input STARTUPINFO structure
3133 startupinfo = subprocess.STARTUPINFO()
3134 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3135 startupinfo.wShowWindow = subprocess.SW_HIDE
3136
3137 # Call Popen() twice with the same startupinfo object to make sure
3138 # that it's not modified
3139 for _ in range(2):
3140 cmd = [sys.executable, "-c", "pass"]
3141 with open(os.devnull, 'w') as null:
3142 proc = subprocess.Popen(cmd,
3143 stdout=null,
3144 stderr=subprocess.STDOUT,
3145 startupinfo=startupinfo)
3146 with proc:
3147 proc.communicate()
3148 self.assertEqual(proc.returncode, 0)
3149
3150 self.assertEqual(startupinfo.dwFlags,
3151 subprocess.STARTF_USESHOWWINDOW)
3152 self.assertIsNone(startupinfo.hStdInput)
3153 self.assertIsNone(startupinfo.hStdOutput)
3154 self.assertIsNone(startupinfo.hStdError)
3155 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3156 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3157
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003158 def test_creationflags(self):
3159 # creationflags argument
3160 CREATE_NEW_CONSOLE = 16
3161 sys.stderr.write(" a DOS box should flash briefly ...\n")
3162 subprocess.call(sys.executable +
3163 ' -c "import time; time.sleep(0.25)"',
3164 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003165
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003166 def test_invalid_args(self):
3167 # invalid arguments should raise ValueError
3168 self.assertRaises(ValueError, subprocess.call,
3169 [sys.executable, "-c",
3170 "import sys; sys.exit(47)"],
3171 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003172
Oren Milman0b3a87e2017-09-14 22:30:28 +03003173 @support.cpython_only
3174 def test_issue31471(self):
3175 # There shouldn't be an assertion failure in Popen() in case the env
3176 # argument has a bad keys() method.
3177 class BadEnv(dict):
3178 keys = None
3179 with self.assertRaises(TypeError):
3180 subprocess.Popen([sys.executable, "-c", "pass"], env=BadEnv())
3181
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003182 def test_close_fds(self):
3183 # close file descriptors
3184 rc = subprocess.call([sys.executable, "-c",
3185 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003186 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003187 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003188
Segev Finerb2a60832017-12-18 11:28:19 +02003189 def test_close_fds_with_stdio(self):
3190 import msvcrt
3191
3192 fds = os.pipe()
3193 self.addCleanup(os.close, fds[0])
3194 self.addCleanup(os.close, fds[1])
3195
3196 handles = []
3197 for fd in fds:
3198 os.set_inheritable(fd, True)
3199 handles.append(msvcrt.get_osfhandle(fd))
3200
3201 p = subprocess.Popen([sys.executable, "-c",
3202 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3203 stdout=subprocess.PIPE, close_fds=False)
3204 stdout, stderr = p.communicate()
3205 self.assertEqual(p.returncode, 0)
3206 int(stdout.strip()) # Check that stdout is an integer
3207
3208 p = subprocess.Popen([sys.executable, "-c",
3209 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3210 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3211 stdout, stderr = p.communicate()
3212 self.assertEqual(p.returncode, 1)
3213 self.assertIn(b"OSError", stderr)
3214
3215 # The same as the previous call, but with an empty handle_list
3216 handle_list = []
3217 startupinfo = subprocess.STARTUPINFO()
3218 startupinfo.lpAttributeList = {"handle_list": handle_list}
3219 p = subprocess.Popen([sys.executable, "-c",
3220 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3221 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3222 startupinfo=startupinfo, close_fds=True)
3223 stdout, stderr = p.communicate()
3224 self.assertEqual(p.returncode, 1)
3225 self.assertIn(b"OSError", stderr)
3226
3227 # Check for a warning due to using handle_list and close_fds=False
3228 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3229 startupinfo = subprocess.STARTUPINFO()
3230 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3231 p = subprocess.Popen([sys.executable, "-c",
3232 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3233 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3234 startupinfo=startupinfo, close_fds=False)
3235 stdout, stderr = p.communicate()
3236 self.assertEqual(p.returncode, 0)
3237
3238 def test_empty_attribute_list(self):
3239 startupinfo = subprocess.STARTUPINFO()
3240 startupinfo.lpAttributeList = {}
3241 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3242 startupinfo=startupinfo)
3243
3244 def test_empty_handle_list(self):
3245 startupinfo = subprocess.STARTUPINFO()
3246 startupinfo.lpAttributeList = {"handle_list": []}
3247 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3248 startupinfo=startupinfo)
3249
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003250 def test_shell_sequence(self):
3251 # Run command through the shell (sequence)
3252 newenv = os.environ.copy()
3253 newenv["FRUIT"] = "physalis"
3254 p = subprocess.Popen(["set"], shell=1,
3255 stdout=subprocess.PIPE,
3256 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003257 with p:
3258 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003259
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003260 def test_shell_string(self):
3261 # Run command through the shell (string)
3262 newenv = os.environ.copy()
3263 newenv["FRUIT"] = "physalis"
3264 p = subprocess.Popen("set", shell=1,
3265 stdout=subprocess.PIPE,
3266 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003267 with p:
3268 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003269
Steve Dower050acae2016-09-06 20:16:17 -07003270 def test_shell_encodings(self):
3271 # Run command through the shell (string)
3272 for enc in ['ansi', 'oem']:
3273 newenv = os.environ.copy()
3274 newenv["FRUIT"] = "physalis"
3275 p = subprocess.Popen("set", shell=1,
3276 stdout=subprocess.PIPE,
3277 env=newenv,
3278 encoding=enc)
3279 with p:
3280 self.assertIn("physalis", p.stdout.read(), enc)
3281
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003282 def test_call_string(self):
3283 # call() function with string argument on Windows
3284 rc = subprocess.call(sys.executable +
3285 ' -c "import sys; sys.exit(47)"')
3286 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003287
Florent Xicluna4886d242010-03-08 13:27:26 +00003288 def _kill_process(self, method, *args):
3289 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003290 p = subprocess.Popen([sys.executable, "-c", """if 1:
3291 import sys, time
3292 sys.stdout.write('x\\n')
3293 sys.stdout.flush()
3294 time.sleep(30)
3295 """],
3296 stdin=subprocess.PIPE,
3297 stdout=subprocess.PIPE,
3298 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003299 with p:
3300 # Wait for the interpreter to be completely initialized before
3301 # sending any signal.
3302 p.stdout.read(1)
3303 getattr(p, method)(*args)
3304 _, stderr = p.communicate()
3305 self.assertStderrEqual(stderr, b'')
3306 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003307 self.assertNotEqual(returncode, 0)
3308
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003309 def _kill_dead_process(self, method, *args):
3310 p = subprocess.Popen([sys.executable, "-c", """if 1:
3311 import sys, time
3312 sys.stdout.write('x\\n')
3313 sys.stdout.flush()
3314 sys.exit(42)
3315 """],
3316 stdin=subprocess.PIPE,
3317 stdout=subprocess.PIPE,
3318 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003319 with p:
3320 # Wait for the interpreter to be completely initialized before
3321 # sending any signal.
3322 p.stdout.read(1)
3323 # The process should end after this
3324 time.sleep(1)
3325 # This shouldn't raise even though the child is now dead
3326 getattr(p, method)(*args)
3327 _, stderr = p.communicate()
3328 self.assertStderrEqual(stderr, b'')
3329 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003330 self.assertEqual(rc, 42)
3331
Florent Xicluna4886d242010-03-08 13:27:26 +00003332 def test_send_signal(self):
3333 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003334
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003335 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003336 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003337
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003338 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003339 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003340
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003341 def test_send_signal_dead(self):
3342 self._kill_dead_process('send_signal', signal.SIGTERM)
3343
3344 def test_kill_dead(self):
3345 self._kill_dead_process('kill')
3346
3347 def test_terminate_dead(self):
3348 self._kill_dead_process('terminate')
3349
Martin Panter23172bd2016-04-16 11:28:10 +00003350class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003351
3352 class RecordingPopen(subprocess.Popen):
3353 """A Popen that saves a reference to each instance for testing."""
3354 instances_created = []
3355
3356 def __init__(self, *args, **kwargs):
3357 super().__init__(*args, **kwargs)
3358 self.instances_created.append(self)
3359
3360 @mock.patch.object(subprocess.Popen, "_communicate")
3361 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3362 **kwargs):
3363 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3364
3365 This avoids the need to actually try and get test environments to send
3366 and receive signals reliably across platforms. The net effect of a ^C
3367 happening during a blocking subprocess execution which we want to clean
3368 up from is a KeyboardInterrupt coming out of communicate() or wait().
3369 """
3370
3371 mock__communicate.side_effect = KeyboardInterrupt
3372 try:
3373 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3374 # We patch out _wait() as no signal was involved so the
3375 # child process isn't actually going to exit rapidly.
3376 mock__wait.side_effect = KeyboardInterrupt
3377 with mock.patch.object(subprocess, "Popen",
3378 self.RecordingPopen):
3379 with self.assertRaises(KeyboardInterrupt):
3380 popener([sys.executable, "-c",
3381 "import time\ntime.sleep(9)\nimport sys\n"
3382 "sys.stderr.write('\\n!runaway child!\\n')"],
3383 stdout=subprocess.DEVNULL, **kwargs)
3384 for call in mock__wait.call_args_list[1:]:
3385 self.assertNotEqual(
3386 call, mock.call(timeout=None),
3387 "no open-ended wait() after the first allowed: "
3388 f"{mock__wait.call_args_list}")
3389 sigint_calls = []
3390 for call in mock__wait.call_args_list:
3391 if call == mock.call(timeout=0.25): # from Popen.__init__
3392 sigint_calls.append(call)
3393 self.assertLessEqual(mock__wait.call_count, 2,
3394 msg=mock__wait.call_args_list)
3395 self.assertEqual(len(sigint_calls), 1,
3396 msg=mock__wait.call_args_list)
3397 finally:
3398 # cleanup the forgotten (due to our mocks) child process
3399 process = self.RecordingPopen.instances_created.pop()
3400 process.kill()
3401 process.wait()
3402 self.assertEqual([], self.RecordingPopen.instances_created)
3403
3404 def test_call_keyboardinterrupt_no_kill(self):
3405 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3406
3407 def test_run_keyboardinterrupt_no_kill(self):
3408 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3409
3410 def test_context_manager_keyboardinterrupt_no_kill(self):
3411 def popen_via_context_manager(*args, **kwargs):
3412 with subprocess.Popen(*args, **kwargs) as unused_process:
3413 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3414 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3415
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003416 def test_getoutput(self):
3417 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3418 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3419 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003420
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003421 # we use mkdtemp in the next line to create an empty directory
3422 # under our exclusive control; from that, we can invent a pathname
3423 # that we _know_ won't exist. This is guaranteed to fail.
3424 dir = None
3425 try:
3426 dir = tempfile.mkdtemp()
3427 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003428 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003429 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003430 self.assertNotEqual(status, 0)
3431 finally:
3432 if dir is not None:
3433 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003434
Gregory P. Smithace55862015-04-07 15:57:54 -07003435 def test__all__(self):
3436 """Ensure that __all__ is populated properly."""
Patrick McLean2b2ead72019-09-12 10:15:44 -07003437 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003438 exported = set(subprocess.__all__)
3439 possible_exports = set()
3440 import types
3441 for name, value in subprocess.__dict__.items():
3442 if name.startswith('_'):
3443 continue
3444 if isinstance(value, (types.ModuleType,)):
3445 continue
3446 possible_exports.add(name)
3447 self.assertEqual(exported, possible_exports - intentionally_excluded)
3448
3449
Martin Panter23172bd2016-04-16 11:28:10 +00003450@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3451 "Test needs selectors.PollSelector")
3452class ProcessTestCaseNoPoll(ProcessTestCase):
3453 def setUp(self):
3454 self.orig_selector = subprocess._PopenSelector
3455 subprocess._PopenSelector = selectors.SelectSelector
3456 ProcessTestCase.setUp(self)
3457
3458 def tearDown(self):
3459 subprocess._PopenSelector = self.orig_selector
3460 ProcessTestCase.tearDown(self)
3461
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003462
Victor Stinner937ee9e2018-06-26 02:11:06 +02003463@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003464class CommandsWithSpaces (BaseTestCase):
3465
3466 def setUp(self):
3467 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003468 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003469 self.fname = fname.lower ()
3470 os.write(f, b"import sys;"
3471 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3472 )
3473 os.close(f)
3474
3475 def tearDown(self):
3476 os.remove(self.fname)
3477 super().tearDown()
3478
3479 def with_spaces(self, *args, **kwargs):
3480 kwargs['stdout'] = subprocess.PIPE
3481 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003482 with p:
3483 self.assertEqual(
3484 p.stdout.read ().decode("mbcs"),
3485 "2 [%r, 'ab cd']" % self.fname
3486 )
Tim Golden126c2962010-08-11 14:20:40 +00003487
3488 def test_shell_string_with_spaces(self):
3489 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003490 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3491 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003492
3493 def test_shell_sequence_with_spaces(self):
3494 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003495 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003496
3497 def test_noshell_string_with_spaces(self):
3498 # call() function with string argument with spaces on Windows
3499 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3500 "ab cd"))
3501
3502 def test_noshell_sequence_with_spaces(self):
3503 # call() function with sequence argument with spaces on Windows
3504 self.with_spaces([sys.executable, self.fname, "ab cd"])
3505
Brian Curtin79cdb662010-12-03 02:46:02 +00003506
Georg Brandla86b2622012-02-20 21:34:57 +01003507class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003508
3509 def test_pipe(self):
3510 with subprocess.Popen([sys.executable, "-c",
3511 "import sys;"
3512 "sys.stdout.write('stdout');"
3513 "sys.stderr.write('stderr');"],
3514 stdout=subprocess.PIPE,
3515 stderr=subprocess.PIPE) as proc:
3516 self.assertEqual(proc.stdout.read(), b"stdout")
3517 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3518
3519 self.assertTrue(proc.stdout.closed)
3520 self.assertTrue(proc.stderr.closed)
3521
3522 def test_returncode(self):
3523 with subprocess.Popen([sys.executable, "-c",
3524 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003525 pass
3526 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003527 self.assertEqual(proc.returncode, 100)
3528
3529 def test_communicate_stdin(self):
3530 with subprocess.Popen([sys.executable, "-c",
3531 "import sys;"
3532 "sys.exit(sys.stdin.read() == 'context')"],
3533 stdin=subprocess.PIPE) as proc:
3534 proc.communicate(b"context")
3535 self.assertEqual(proc.returncode, 1)
3536
3537 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003538 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003539 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003540 stdout=subprocess.PIPE,
3541 stderr=subprocess.PIPE) as proc:
3542 pass
3543
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003544 def test_broken_pipe_cleanup(self):
3545 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003546 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01003547 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003548 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003549 proc = proc.__enter__()
3550 # Prepare to send enough data to overflow any OS pipe buffering and
3551 # guarantee a broken pipe error. Data is held in BufferedWriter
3552 # buffer until closed.
3553 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003554 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003555 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003556 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003557 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003558 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003559
Brian Curtin79cdb662010-12-03 02:46:02 +00003560
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003561if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003562 unittest.main()