blob: 22516402da0e894363a33031436280de9c2b02da [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
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001897 def test_run_abort(self):
1898 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001899 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001900 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001901 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001902 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001903 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001904
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001905 def test_CalledProcessError_str_signal(self):
1906 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1907 error_string = str(err)
1908 # We're relying on the repr() of the signal.Signals intenum to provide
1909 # the word signal, the signal name and the numeric value.
1910 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001911 # We're not being specific about the signal name as some signals have
1912 # multiple names and which name is revealed can vary.
1913 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001914 self.assertIn(str(signal.SIGABRT), error_string)
1915
1916 def test_CalledProcessError_str_unknown_signal(self):
1917 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1918 error_string = str(err)
1919 self.assertIn("unknown signal 9876543.", error_string)
1920
1921 def test_CalledProcessError_str_non_zero(self):
1922 err = subprocess.CalledProcessError(2, "fake cmd")
1923 error_string = str(err)
1924 self.assertIn("non-zero exit status 2.", error_string)
1925
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001926 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001927 # DISCLAIMER: Setting environment variables is *not* a good use
1928 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001929 p = subprocess.Popen([sys.executable, "-c",
1930 'import sys,os;'
1931 'sys.stdout.write(os.getenv("FRUIT"))'],
1932 stdout=subprocess.PIPE,
1933 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001934 with p:
1935 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001936
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001937 def test_preexec_exception(self):
1938 def raise_it():
1939 raise ValueError("What if two swallows carried a coconut?")
1940 try:
1941 p = subprocess.Popen([sys.executable, "-c", ""],
1942 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001943 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001944 self.assertTrue(
1945 subprocess._posixsubprocess,
1946 "Expected a ValueError from the preexec_fn")
1947 except ValueError as e:
1948 self.assertIn("coconut", e.args[0])
1949 else:
1950 self.fail("Exception raised by preexec_fn did not make it "
1951 "to the parent process.")
1952
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001953 class _TestExecuteChildPopen(subprocess.Popen):
1954 """Used to test behavior at the end of _execute_child."""
1955 def __init__(self, testcase, *args, **kwargs):
1956 self._testcase = testcase
1957 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001958
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001959 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001960 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001961 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001962 finally:
1963 # Open a bunch of file descriptors and verify that
1964 # none of them are the same as the ones the Popen
1965 # instance is using for stdin/stdout/stderr.
1966 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1967 for _ in range(8)]
1968 try:
1969 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001970 self._testcase.assertNotIn(
1971 fd, (self.stdin.fileno(), self.stdout.fileno(),
1972 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001973 msg="At least one fd was closed early.")
1974 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001975 for fd in devzero_fds:
1976 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001977
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001978 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1979 def test_preexec_errpipe_does_not_double_close_pipes(self):
1980 """Issue16140: Don't double close pipes on preexec error."""
1981
1982 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001983 raise subprocess.SubprocessError(
1984 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001985
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001986 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001987 self._TestExecuteChildPopen(
1988 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001989 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1990 stderr=subprocess.PIPE, preexec_fn=raise_it)
1991
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001992 def test_preexec_gc_module_failure(self):
1993 # This tests the code that disables garbage collection if the child
1994 # process will execute any Python.
1995 def raise_runtime_error():
1996 raise RuntimeError("this shouldn't escape")
1997 enabled = gc.isenabled()
1998 orig_gc_disable = gc.disable
1999 orig_gc_isenabled = gc.isenabled
2000 try:
2001 gc.disable()
2002 self.assertFalse(gc.isenabled())
2003 subprocess.call([sys.executable, '-c', ''],
2004 preexec_fn=lambda: None)
2005 self.assertFalse(gc.isenabled(),
2006 "Popen enabled gc when it shouldn't.")
2007
2008 gc.enable()
2009 self.assertTrue(gc.isenabled())
2010 subprocess.call([sys.executable, '-c', ''],
2011 preexec_fn=lambda: None)
2012 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2013
2014 gc.disable = raise_runtime_error
2015 self.assertRaises(RuntimeError, subprocess.Popen,
2016 [sys.executable, '-c', ''],
2017 preexec_fn=lambda: None)
2018
2019 del gc.isenabled # force an AttributeError
2020 self.assertRaises(AttributeError, subprocess.Popen,
2021 [sys.executable, '-c', ''],
2022 preexec_fn=lambda: None)
2023 finally:
2024 gc.disable = orig_gc_disable
2025 gc.isenabled = orig_gc_isenabled
2026 if not enabled:
2027 gc.disable()
2028
Martin Panterf7fdbda2015-12-05 09:51:52 +00002029 @unittest.skipIf(
2030 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002031 def test_preexec_fork_failure(self):
2032 # The internal code did not preserve the previous exception when
2033 # re-enabling garbage collection
2034 try:
2035 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2036 except ImportError as err:
2037 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2038 limits = getrlimit(RLIMIT_NPROC)
2039 [_, hard] = limits
2040 setrlimit(RLIMIT_NPROC, (0, hard))
2041 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002042 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002043 subprocess.call([sys.executable, '-c', ''],
2044 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002045 except BlockingIOError:
2046 # Forking should raise EAGAIN, translated to BlockingIOError
2047 pass
2048 else:
2049 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002050
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002051 def test_args_string(self):
2052 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002053 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002054 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002055 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002056 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002057 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2058 sys.executable)
2059 os.chmod(fname, 0o700)
2060 p = subprocess.Popen(fname)
2061 p.wait()
2062 os.remove(fname)
2063 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002064
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002065 def test_invalid_args(self):
2066 # invalid arguments should raise ValueError
2067 self.assertRaises(ValueError, subprocess.call,
2068 [sys.executable, "-c",
2069 "import sys; sys.exit(47)"],
2070 startupinfo=47)
2071 self.assertRaises(ValueError, subprocess.call,
2072 [sys.executable, "-c",
2073 "import sys; sys.exit(47)"],
2074 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002075
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002076 def test_shell_sequence(self):
2077 # Run command through the shell (sequence)
2078 newenv = os.environ.copy()
2079 newenv["FRUIT"] = "apple"
2080 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2081 stdout=subprocess.PIPE,
2082 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002083 with p:
2084 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002085
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002086 def test_shell_string(self):
2087 # Run command through the shell (string)
2088 newenv = os.environ.copy()
2089 newenv["FRUIT"] = "apple"
2090 p = subprocess.Popen("echo $FRUIT", shell=1,
2091 stdout=subprocess.PIPE,
2092 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002093 with p:
2094 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002095
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002096 def test_call_string(self):
2097 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002098 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002099 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002100 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002101 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002102 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2103 sys.executable)
2104 os.chmod(fname, 0o700)
2105 rc = subprocess.call(fname)
2106 os.remove(fname)
2107 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002108
Stefan Krah9542cc62010-07-19 14:20:53 +00002109 def test_specific_shell(self):
2110 # Issue #9265: Incorrect name passed as arg[0].
2111 shells = []
2112 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2113 for name in ['bash', 'ksh']:
2114 sh = os.path.join(prefix, name)
2115 if os.path.isfile(sh):
2116 shells.append(sh)
2117 if not shells: # Will probably work for any shell but csh.
2118 self.skipTest("bash or ksh required for this test")
2119 sh = '/bin/sh'
2120 if os.path.isfile(sh) and not os.path.islink(sh):
2121 # Test will fail if /bin/sh is a symlink to csh.
2122 shells.append(sh)
2123 for sh in shells:
2124 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2125 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002126 with p:
2127 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002128
Florent Xicluna4886d242010-03-08 13:27:26 +00002129 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002130 # Do not inherit file handles from the parent.
2131 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002132 # Also set the SIGINT handler to the default to make sure it's not
2133 # being ignored (some tests rely on that.)
2134 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2135 try:
2136 p = subprocess.Popen([sys.executable, "-c", """if 1:
2137 import sys, time
2138 sys.stdout.write('x\\n')
2139 sys.stdout.flush()
2140 time.sleep(30)
2141 """],
2142 close_fds=True,
2143 stdin=subprocess.PIPE,
2144 stdout=subprocess.PIPE,
2145 stderr=subprocess.PIPE)
2146 finally:
2147 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002148 # Wait for the interpreter to be completely initialized before
2149 # sending any signal.
2150 p.stdout.read(1)
2151 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002152 return p
2153
Charles-François Natali53221e32013-01-12 16:52:20 +01002154 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2155 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002156 def _kill_dead_process(self, method, *args):
2157 # Do not inherit file handles from the parent.
2158 # It should fix failures on some platforms.
2159 p = subprocess.Popen([sys.executable, "-c", """if 1:
2160 import sys, time
2161 sys.stdout.write('x\\n')
2162 sys.stdout.flush()
2163 """],
2164 close_fds=True,
2165 stdin=subprocess.PIPE,
2166 stdout=subprocess.PIPE,
2167 stderr=subprocess.PIPE)
2168 # Wait for the interpreter to be completely initialized before
2169 # sending any signal.
2170 p.stdout.read(1)
2171 # The process should end after this
2172 time.sleep(1)
2173 # This shouldn't raise even though the child is now dead
2174 getattr(p, method)(*args)
2175 p.communicate()
2176
Florent Xicluna4886d242010-03-08 13:27:26 +00002177 def test_send_signal(self):
2178 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002179 _, stderr = p.communicate()
2180 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002181 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002182
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002183 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002184 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002185 _, stderr = p.communicate()
2186 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002187 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002188
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002189 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002190 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002191 _, stderr = p.communicate()
2192 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002193 self.assertEqual(p.wait(), -signal.SIGTERM)
2194
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002195 def test_send_signal_dead(self):
2196 # Sending a signal to a dead process
2197 self._kill_dead_process('send_signal', signal.SIGINT)
2198
2199 def test_kill_dead(self):
2200 # Killing a dead process
2201 self._kill_dead_process('kill')
2202
2203 def test_terminate_dead(self):
2204 # Terminating a dead process
2205 self._kill_dead_process('terminate')
2206
Victor Stinnerdaf45552013-08-28 00:53:59 +02002207 def _save_fds(self, save_fds):
2208 fds = []
2209 for fd in save_fds:
2210 inheritable = os.get_inheritable(fd)
2211 saved = os.dup(fd)
2212 fds.append((fd, saved, inheritable))
2213 return fds
2214
2215 def _restore_fds(self, fds):
2216 for fd, saved, inheritable in fds:
2217 os.dup2(saved, fd, inheritable=inheritable)
2218 os.close(saved)
2219
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002220 def check_close_std_fds(self, fds):
2221 # Issue #9905: test that subprocess pipes still work properly with
2222 # some standard fds closed
2223 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002224 saved_fds = self._save_fds(fds)
2225 for fd, saved, inheritable in saved_fds:
2226 if fd == 0:
2227 stdin = saved
2228 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002229 try:
2230 for fd in fds:
2231 os.close(fd)
2232 out, err = subprocess.Popen([sys.executable, "-c",
2233 'import sys;'
2234 'sys.stdout.write("apple");'
2235 'sys.stdout.flush();'
2236 'sys.stderr.write("orange")'],
2237 stdin=stdin,
2238 stdout=subprocess.PIPE,
2239 stderr=subprocess.PIPE).communicate()
2240 err = support.strip_python_stderr(err)
2241 self.assertEqual((out, err), (b'apple', b'orange'))
2242 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002243 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002244
2245 def test_close_fd_0(self):
2246 self.check_close_std_fds([0])
2247
2248 def test_close_fd_1(self):
2249 self.check_close_std_fds([1])
2250
2251 def test_close_fd_2(self):
2252 self.check_close_std_fds([2])
2253
2254 def test_close_fds_0_1(self):
2255 self.check_close_std_fds([0, 1])
2256
2257 def test_close_fds_0_2(self):
2258 self.check_close_std_fds([0, 2])
2259
2260 def test_close_fds_1_2(self):
2261 self.check_close_std_fds([1, 2])
2262
2263 def test_close_fds_0_1_2(self):
2264 # Issue #10806: test that subprocess pipes still work properly with
2265 # all standard fds closed.
2266 self.check_close_std_fds([0, 1, 2])
2267
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002268 def test_small_errpipe_write_fd(self):
2269 """Issue #15798: Popen should work when stdio fds are available."""
2270 new_stdin = os.dup(0)
2271 new_stdout = os.dup(1)
2272 try:
2273 os.close(0)
2274 os.close(1)
2275
2276 # Side test: if errpipe_write fails to have its CLOEXEC
2277 # flag set this should cause the parent to think the exec
2278 # failed. Extremely unlikely: everyone supports CLOEXEC.
2279 subprocess.Popen([
2280 sys.executable, "-c",
2281 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2282 finally:
2283 # Restore original stdin and stdout
2284 os.dup2(new_stdin, 0)
2285 os.dup2(new_stdout, 1)
2286 os.close(new_stdin)
2287 os.close(new_stdout)
2288
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002289 def test_remapping_std_fds(self):
2290 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002291 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002292 try:
2293 temp_fds = [fd for fd, fname in temps]
2294
2295 # unlink the files -- we won't need to reopen them
2296 for fd, fname in temps:
2297 os.unlink(fname)
2298
2299 # write some data to what will become stdin, and rewind
2300 os.write(temp_fds[1], b"STDIN")
2301 os.lseek(temp_fds[1], 0, 0)
2302
2303 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002304 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002305 try:
2306 # duplicate the file objects over the standard fd's
2307 for fd, temp_fd in enumerate(temp_fds):
2308 os.dup2(temp_fd, fd)
2309
2310 # now use those files in the "wrong" order, so that subprocess
2311 # has to rearrange them in the child
2312 p = subprocess.Popen([sys.executable, "-c",
2313 'import sys; got = sys.stdin.read();'
2314 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2315 stdin=temp_fds[1],
2316 stdout=temp_fds[2],
2317 stderr=temp_fds[0])
2318 p.wait()
2319 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002320 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002321
2322 for fd in temp_fds:
2323 os.lseek(fd, 0, 0)
2324
2325 out = os.read(temp_fds[2], 1024)
2326 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2327 self.assertEqual(out, b"got STDIN")
2328 self.assertEqual(err, b"err")
2329
2330 finally:
2331 for fd in temp_fds:
2332 os.close(fd)
2333
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002334 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2335 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002336 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002337 temp_fds = [fd for fd, fname in temps]
2338 try:
2339 # unlink the files -- we won't need to reopen them
2340 for fd, fname in temps:
2341 os.unlink(fname)
2342
2343 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002344 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002345 try:
2346 # duplicate the temp files over the standard fd's 0, 1, 2
2347 for fd, temp_fd in enumerate(temp_fds):
2348 os.dup2(temp_fd, fd)
2349
2350 # write some data to what will become stdin, and rewind
2351 os.write(stdin_no, b"STDIN")
2352 os.lseek(stdin_no, 0, 0)
2353
2354 # now use those files in the given order, so that subprocess
2355 # has to rearrange them in the child
2356 p = subprocess.Popen([sys.executable, "-c",
2357 'import sys; got = sys.stdin.read();'
2358 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2359 stdin=stdin_no,
2360 stdout=stdout_no,
2361 stderr=stderr_no)
2362 p.wait()
2363
2364 for fd in temp_fds:
2365 os.lseek(fd, 0, 0)
2366
2367 out = os.read(stdout_no, 1024)
2368 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2369 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002370 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002371
2372 self.assertEqual(out, b"got STDIN")
2373 self.assertEqual(err, b"err")
2374
2375 finally:
2376 for fd in temp_fds:
2377 os.close(fd)
2378
2379 # When duping fds, if there arises a situation where one of the fds is
2380 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2381 # This tests all combinations of this.
2382 def test_swap_fds(self):
2383 self.check_swap_fds(0, 1, 2)
2384 self.check_swap_fds(0, 2, 1)
2385 self.check_swap_fds(1, 0, 2)
2386 self.check_swap_fds(1, 2, 0)
2387 self.check_swap_fds(2, 0, 1)
2388 self.check_swap_fds(2, 1, 0)
2389
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002390 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2391 saved_fds = self._save_fds(range(3))
2392 try:
2393 for from_fd in from_fds:
2394 with tempfile.TemporaryFile() as f:
2395 os.dup2(f.fileno(), from_fd)
2396
2397 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2398 os.close(fd_to_close)
2399
2400 arg_names = ['stdin', 'stdout', 'stderr']
2401 kwargs = {}
2402 for from_fd, to_fd in zip(from_fds, to_fds):
2403 kwargs[arg_names[to_fd]] = from_fd
2404
2405 code = textwrap.dedent(r'''
2406 import os, sys
2407 skipped_fd = int(sys.argv[1])
2408 for fd in range(3):
2409 if fd != skipped_fd:
2410 os.write(fd, str(fd).encode('ascii'))
2411 ''')
2412
2413 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2414
2415 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2416 **kwargs)
2417 self.assertEqual(rc, 0)
2418
2419 for from_fd, to_fd in zip(from_fds, to_fds):
2420 os.lseek(from_fd, 0, os.SEEK_SET)
2421 read_bytes = os.read(from_fd, 1024)
2422 read_fds = list(map(int, read_bytes.decode('ascii')))
2423 msg = textwrap.dedent(f"""
2424 When testing {from_fds} to {to_fds} redirection,
2425 parent descriptor {from_fd} got redirected
2426 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2427 """)
2428 self.assertEqual([to_fd], read_fds, msg)
2429 finally:
2430 self._restore_fds(saved_fds)
2431
2432 # Check that subprocess can remap std fds correctly even
2433 # if one of them is closed (#32844).
2434 def test_swap_std_fds_with_one_closed(self):
2435 for from_fds in itertools.combinations(range(3), 2):
2436 for to_fds in itertools.permutations(range(3), 2):
2437 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2438
Victor Stinner13bb71c2010-04-23 21:41:56 +00002439 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002440 def prepare():
2441 raise ValueError("surrogate:\uDCff")
2442
2443 try:
2444 subprocess.call(
2445 [sys.executable, "-c", "pass"],
2446 preexec_fn=prepare)
2447 except ValueError as err:
2448 # Pure Python implementations keeps the message
2449 self.assertIsNone(subprocess._posixsubprocess)
2450 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002451 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002452 # _posixsubprocess uses a default message
2453 self.assertIsNotNone(subprocess._posixsubprocess)
2454 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2455 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002456 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002457
Victor Stinner13bb71c2010-04-23 21:41:56 +00002458 def test_undecodable_env(self):
2459 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002460 encoded_value = value.encode("ascii", "surrogateescape")
2461
Victor Stinner13bb71c2010-04-23 21:41:56 +00002462 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002463 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002464 env = os.environ.copy()
2465 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002466 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002467 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002468 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002469 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002470 stdout = subprocess.check_output(
2471 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002472 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002473 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002474 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002475
2476 # test bytes
2477 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002478 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002479 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002480 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002481 stdout = subprocess.check_output(
2482 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002483 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002484 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002485 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002486
Victor Stinnerb745a742010-05-18 17:17:23 +00002487 def test_bytes_program(self):
2488 abs_program = os.fsencode(sys.executable)
2489 path, program = os.path.split(sys.executable)
2490 program = os.fsencode(program)
2491
2492 # absolute bytes path
2493 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002494 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002495
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002496 # absolute bytes path as a string
2497 cmd = b"'" + abs_program + b"' -c pass"
2498 exitcode = subprocess.call(cmd, shell=True)
2499 self.assertEqual(exitcode, 0)
2500
Victor Stinnerb745a742010-05-18 17:17:23 +00002501 # bytes program, unicode PATH
2502 env = os.environ.copy()
2503 env["PATH"] = path
2504 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002505 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002506
2507 # bytes program, bytes PATH
2508 envb = os.environb.copy()
2509 envb[b"PATH"] = os.fsencode(path)
2510 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002511 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002512
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002513 def test_pipe_cloexec(self):
2514 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2515 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2516
2517 p1 = subprocess.Popen([sys.executable, sleeper],
2518 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2519 stderr=subprocess.PIPE, close_fds=False)
2520
2521 self.addCleanup(p1.communicate, b'')
2522
2523 p2 = subprocess.Popen([sys.executable, fd_status],
2524 stdout=subprocess.PIPE, close_fds=False)
2525
2526 output, error = p2.communicate()
2527 result_fds = set(map(int, output.split(b',')))
2528 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2529 p1.stderr.fileno()])
2530
2531 self.assertFalse(result_fds & unwanted_fds,
2532 "Expected no fds from %r to be open in child, "
2533 "found %r" %
2534 (unwanted_fds, result_fds & unwanted_fds))
2535
2536 def test_pipe_cloexec_real_tools(self):
2537 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2538 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2539
2540 subdata = b'zxcvbn'
2541 data = subdata * 4 + b'\n'
2542
2543 p1 = subprocess.Popen([sys.executable, qcat],
2544 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2545 close_fds=False)
2546
2547 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2548 stdin=p1.stdout, stdout=subprocess.PIPE,
2549 close_fds=False)
2550
2551 self.addCleanup(p1.wait)
2552 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002553 def kill_p1():
2554 try:
2555 p1.terminate()
2556 except ProcessLookupError:
2557 pass
2558 def kill_p2():
2559 try:
2560 p2.terminate()
2561 except ProcessLookupError:
2562 pass
2563 self.addCleanup(kill_p1)
2564 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002565
2566 p1.stdin.write(data)
2567 p1.stdin.close()
2568
2569 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2570
2571 self.assertTrue(readfiles, "The child hung")
2572 self.assertEqual(p2.stdout.read(), data)
2573
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002574 p1.stdout.close()
2575 p2.stdout.close()
2576
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002577 def test_close_fds(self):
2578 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2579
2580 fds = os.pipe()
2581 self.addCleanup(os.close, fds[0])
2582 self.addCleanup(os.close, fds[1])
2583
2584 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002585 # add a bunch more fds
2586 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002587 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002588 self.addCleanup(os.close, fd)
2589 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002590
Victor Stinnerdaf45552013-08-28 00:53:59 +02002591 for fd in open_fds:
2592 os.set_inheritable(fd, True)
2593
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002594 p = subprocess.Popen([sys.executable, fd_status],
2595 stdout=subprocess.PIPE, close_fds=False)
2596 output, ignored = p.communicate()
2597 remaining_fds = set(map(int, output.split(b',')))
2598
2599 self.assertEqual(remaining_fds & open_fds, open_fds,
2600 "Some fds were closed")
2601
2602 p = subprocess.Popen([sys.executable, fd_status],
2603 stdout=subprocess.PIPE, close_fds=True)
2604 output, ignored = p.communicate()
2605 remaining_fds = set(map(int, output.split(b',')))
2606
2607 self.assertFalse(remaining_fds & open_fds,
2608 "Some fds were left open")
2609 self.assertIn(1, remaining_fds, "Subprocess failed")
2610
Gregory P. Smith8facece2012-01-21 14:01:08 -08002611 # Keep some of the fd's we opened open in the subprocess.
2612 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2613 fds_to_keep = set(open_fds.pop() for _ in range(8))
2614 p = subprocess.Popen([sys.executable, fd_status],
2615 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002616 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002617 output, ignored = p.communicate()
2618 remaining_fds = set(map(int, output.split(b',')))
2619
izbyshev2d8f0632017-12-19 03:26:49 +07002620 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002621 "Some fds not in pass_fds were left open")
2622 self.assertIn(1, remaining_fds, "Subprocess failed")
2623
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002624
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002625 @unittest.skipIf(sys.platform.startswith("freebsd") and
2626 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2627 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002628 def test_close_fds_when_max_fd_is_lowered(self):
2629 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2630 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2631
Gregory P. Smith634aa682014-06-15 17:51:04 -07002632 # This launches the meat of the test in a child process to
2633 # avoid messing with the larger unittest processes maximum
2634 # number of file descriptors.
2635 # This process launches:
2636 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2637 # a bunch of high open fds above the new lower rlimit.
2638 # Those are reported via stdout before launching a new
2639 # process with close_fds=False to run the actual test:
2640 # +--> The TEST: This one launches a fd_status.py
2641 # subprocess with close_fds=True so we can find out if
2642 # any of the fds above the lowered rlimit are still open.
2643 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2644 '''
2645 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002646 open_fds = set()
2647 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002648 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002649 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002650 open_fds.add(fd)
2651
2652 # Leave a two pairs of low ones available for use by the
2653 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002654 # We also leave 10 more open as some Python buildbots run into
2655 # "too many open files" errors during the test if we do not.
2656 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002657 os.close(fd)
2658 open_fds.remove(fd)
2659
2660 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002661 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002662 os.set_inheritable(fd, True)
2663
2664 max_fd_open = max(open_fds)
2665
Gregory P. Smith634aa682014-06-15 17:51:04 -07002666 # Communicate the open_fds to the parent unittest.TestCase process.
2667 print(','.join(map(str, sorted(open_fds))))
2668 sys.stdout.flush()
2669
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002670 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2671 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002672 # 29 is lower than the highest fds we are leaving open.
2673 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002674 # Launch a new Python interpreter with our low fd rlim_cur that
2675 # inherits open fds above that limit. It then uses subprocess
2676 # with close_fds=True to get a report of open fds in the child.
2677 # An explicit list of fds to check is passed to fd_status.py as
2678 # letting fd_status rely on its default logic would miss the
2679 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002680 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002681 [sys.executable, '-c',
2682 textwrap.dedent("""
2683 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002684 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002685 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002686 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002687 """.format(max_fd=max_fd_open+1))],
2688 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002689 finally:
2690 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002691 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002692
2693 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002694 output_lines = output.splitlines()
2695 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002696 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002697 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2698 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002699
Gregory P. Smith634aa682014-06-15 17:51:04 -07002700 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002701 msg="Some fds were left open.")
2702
2703
Victor Stinner88701e22011-06-01 13:13:04 +02002704 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2705 # descriptor of a pipe closed in the parent process is valid in the
2706 # child process according to fstat(), but the mode of the file
2707 # descriptor is invalid, and read or write raise an error.
2708 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002709 def test_pass_fds(self):
2710 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2711
2712 open_fds = set()
2713
2714 for x in range(5):
2715 fds = os.pipe()
2716 self.addCleanup(os.close, fds[0])
2717 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002718 os.set_inheritable(fds[0], True)
2719 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002720 open_fds.update(fds)
2721
2722 for fd in open_fds:
2723 p = subprocess.Popen([sys.executable, fd_status],
2724 stdout=subprocess.PIPE, close_fds=True,
2725 pass_fds=(fd, ))
2726 output, ignored = p.communicate()
2727
2728 remaining_fds = set(map(int, output.split(b',')))
2729 to_be_closed = open_fds - {fd}
2730
2731 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2732 self.assertFalse(remaining_fds & to_be_closed,
2733 "fd to be closed passed")
2734
2735 # pass_fds overrides close_fds with a warning.
2736 with self.assertWarns(RuntimeWarning) as context:
2737 self.assertFalse(subprocess.call(
2738 [sys.executable, "-c", "import sys; sys.exit(0)"],
2739 close_fds=False, pass_fds=(fd, )))
2740 self.assertIn('overriding close_fds', str(context.warning))
2741
Victor Stinnerdaf45552013-08-28 00:53:59 +02002742 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002743 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002744
2745 inheritable, non_inheritable = os.pipe()
2746 self.addCleanup(os.close, inheritable)
2747 self.addCleanup(os.close, non_inheritable)
2748 os.set_inheritable(inheritable, True)
2749 os.set_inheritable(non_inheritable, False)
2750 pass_fds = (inheritable, non_inheritable)
2751 args = [sys.executable, script]
2752 args += list(map(str, pass_fds))
2753
2754 p = subprocess.Popen(args,
2755 stdout=subprocess.PIPE, close_fds=True,
2756 pass_fds=pass_fds)
2757 output, ignored = p.communicate()
2758 fds = set(map(int, output.split(b',')))
2759
2760 # the inheritable file descriptor must be inherited, so its inheritable
2761 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002762 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002763
2764 # inheritable flag must not be changed in the parent process
2765 self.assertEqual(os.get_inheritable(inheritable), True)
2766 self.assertEqual(os.get_inheritable(non_inheritable), False)
2767
Gregory P. Smithce344102018-09-10 17:46:22 -07002768
2769 # bpo-32270: Ensure that descriptors specified in pass_fds
2770 # are inherited even if they are used in redirections.
2771 # Contributed by @izbyshev.
2772 def test_pass_fds_redirected(self):
2773 """Regression test for https://bugs.python.org/issue32270."""
2774 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2775 pass_fds = []
2776 for _ in range(2):
2777 fd = os.open(os.devnull, os.O_RDWR)
2778 self.addCleanup(os.close, fd)
2779 pass_fds.append(fd)
2780
2781 stdout_r, stdout_w = os.pipe()
2782 self.addCleanup(os.close, stdout_r)
2783 self.addCleanup(os.close, stdout_w)
2784 pass_fds.insert(1, stdout_w)
2785
2786 with subprocess.Popen([sys.executable, fd_status],
2787 stdin=pass_fds[0],
2788 stdout=pass_fds[1],
2789 stderr=pass_fds[2],
2790 close_fds=True,
2791 pass_fds=pass_fds):
2792 output = os.read(stdout_r, 1024)
2793 fds = {int(num) for num in output.split(b',')}
2794
2795 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2796
2797
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002798 def test_stdout_stdin_are_single_inout_fd(self):
2799 with io.open(os.devnull, "r+") as inout:
2800 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2801 stdout=inout, stdin=inout)
2802 p.wait()
2803
2804 def test_stdout_stderr_are_single_inout_fd(self):
2805 with io.open(os.devnull, "r+") as inout:
2806 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2807 stdout=inout, stderr=inout)
2808 p.wait()
2809
2810 def test_stderr_stdin_are_single_inout_fd(self):
2811 with io.open(os.devnull, "r+") as inout:
2812 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2813 stderr=inout, stdin=inout)
2814 p.wait()
2815
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002816 def test_wait_when_sigchild_ignored(self):
2817 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2818 sigchild_ignore = support.findfile("sigchild_ignore.py",
2819 subdir="subprocessdata")
2820 p = subprocess.Popen([sys.executable, sigchild_ignore],
2821 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2822 stdout, stderr = p.communicate()
2823 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002824 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002825 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002826
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002827 def test_select_unbuffered(self):
2828 # Issue #11459: bufsize=0 should really set the pipes as
2829 # unbuffered (and therefore let select() work properly).
2830 select = support.import_module("select")
2831 p = subprocess.Popen([sys.executable, "-c",
2832 'import sys;'
2833 'sys.stdout.write("apple")'],
2834 stdout=subprocess.PIPE,
2835 bufsize=0)
2836 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002837 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002838 try:
2839 self.assertEqual(f.read(4), b"appl")
2840 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2841 finally:
2842 p.wait()
2843
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002844 def test_zombie_fast_process_del(self):
2845 # Issue #12650: on Unix, if Popen.__del__() was called before the
2846 # process exited, it wouldn't be added to subprocess._active, and would
2847 # remain a zombie.
2848 # spawn a Popen, and delete its reference before it exits
2849 p = subprocess.Popen([sys.executable, "-c",
2850 'import sys, time;'
2851 'time.sleep(0.2)'],
2852 stdout=subprocess.PIPE,
2853 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002854 self.addCleanup(p.stdout.close)
2855 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002856 ident = id(p)
2857 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002858 with support.check_warnings(('', ResourceWarning)):
2859 p = None
2860
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002861 if mswindows:
2862 # subprocess._active is not used on Windows and is set to None.
2863 self.assertIsNone(subprocess._active)
2864 else:
2865 # check that p is in the active processes list
2866 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002867
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002868 def test_leak_fast_process_del_killed(self):
2869 # Issue #12650: on Unix, if Popen.__del__() was called before the
2870 # process exited, and the process got killed by a signal, it would never
2871 # be removed from subprocess._active, which triggered a FD and memory
2872 # leak.
2873 # spawn a Popen, delete its reference and kill it
2874 p = subprocess.Popen([sys.executable, "-c",
2875 'import time;'
2876 'time.sleep(3)'],
2877 stdout=subprocess.PIPE,
2878 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002879 self.addCleanup(p.stdout.close)
2880 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002881 ident = id(p)
2882 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002883 with support.check_warnings(('', ResourceWarning)):
2884 p = None
2885
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002886 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002887 if mswindows:
2888 # subprocess._active is not used on Windows and is set to None.
2889 self.assertIsNone(subprocess._active)
2890 else:
2891 # check that p is in the active processes list
2892 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002893
2894 # let some time for the process to exit, and create a new Popen: this
2895 # should trigger the wait() of p
2896 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002897 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002898 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002899 stdout=subprocess.PIPE,
2900 stderr=subprocess.PIPE) as proc:
2901 pass
2902 # p should have been wait()ed on, and removed from the _active list
2903 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002904 if mswindows:
2905 # subprocess._active is not used on Windows and is set to None.
2906 self.assertIsNone(subprocess._active)
2907 else:
2908 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002909
Charles-François Natali249cdc32013-08-25 18:24:45 +02002910 def test_close_fds_after_preexec(self):
2911 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2912
2913 # this FD is used as dup2() target by preexec_fn, and should be closed
2914 # in the child process
2915 fd = os.dup(1)
2916 self.addCleanup(os.close, fd)
2917
2918 p = subprocess.Popen([sys.executable, fd_status],
2919 stdout=subprocess.PIPE, close_fds=True,
2920 preexec_fn=lambda: os.dup2(1, fd))
2921 output, ignored = p.communicate()
2922
2923 remaining_fds = set(map(int, output.split(b',')))
2924
2925 self.assertNotIn(fd, remaining_fds)
2926
Victor Stinner8f437aa2014-10-05 17:25:19 +02002927 @support.cpython_only
2928 def test_fork_exec(self):
2929 # Issue #22290: fork_exec() must not crash on memory allocation failure
2930 # or other errors
2931 import _posixsubprocess
2932 gc_enabled = gc.isenabled()
2933 try:
2934 # Use a preexec function and enable the garbage collector
2935 # to force fork_exec() to re-enable the garbage collector
2936 # on error.
2937 func = lambda: None
2938 gc.enable()
2939
Victor Stinner8f437aa2014-10-05 17:25:19 +02002940 for args, exe_list, cwd, env_list in (
2941 (123, [b"exe"], None, [b"env"]),
2942 ([b"arg"], 123, None, [b"env"]),
2943 ([b"arg"], [b"exe"], 123, [b"env"]),
2944 ([b"arg"], [b"exe"], None, 123),
2945 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07002946 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02002947 _posixsubprocess.fork_exec(
2948 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002949 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002950 -1, -1, -1, -1,
2951 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07002952 True, True,
2953 False, [], 0,
2954 func)
2955 # Attempt to prevent
2956 # "TypeError: fork_exec() takes exactly N arguments (M given)"
2957 # from passing the test. More refactoring to have us start
2958 # with a valid *args list, confirm a good call with that works
2959 # before mutating it in various ways to ensure that bad calls
2960 # with individual arg type errors raise a typeerror would be
2961 # ideal. Saving that for a future PR...
2962 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02002963 finally:
2964 if not gc_enabled:
2965 gc.disable()
2966
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002967 @support.cpython_only
2968 def test_fork_exec_sorted_fd_sanity_check(self):
2969 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2970 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002971 class BadInt:
2972 first = True
2973 def __init__(self, value):
2974 self.value = value
2975 def __int__(self):
2976 if self.first:
2977 self.first = False
2978 return self.value
2979 raise ValueError
2980
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002981 gc_enabled = gc.isenabled()
2982 try:
2983 gc.enable()
2984
2985 for fds_to_keep in (
2986 (-1, 2, 3, 4, 5), # Negative number.
2987 ('str', 4), # Not an int.
2988 (18, 23, 42, 2**63), # Out of range.
2989 (5, 4), # Not sorted.
2990 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002991 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002992 ):
2993 with self.assertRaises(
2994 ValueError,
2995 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2996 _posixsubprocess.fork_exec(
2997 [b"false"], [b"false"],
2998 True, fds_to_keep, None, [b"env"],
2999 -1, -1, -1, -1,
3000 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003001 True, True,
3002 None, None, None,
3003 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003004 self.assertIn('fds_to_keep', str(c.exception))
3005 finally:
3006 if not gc_enabled:
3007 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003008
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003009 def test_communicate_BrokenPipeError_stdin_close(self):
3010 # By not setting stdout or stderr or a timeout we force the fast path
3011 # that just calls _stdin_write() internally due to our mock.
3012 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
3013 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3014 mock_proc_stdin.close.side_effect = BrokenPipeError
3015 proc.communicate() # Should swallow BrokenPipeError from close.
3016 mock_proc_stdin.close.assert_called_with()
3017
3018 def test_communicate_BrokenPipeError_stdin_write(self):
3019 # By not setting stdout or stderr or a timeout we force the fast path
3020 # that just calls _stdin_write() internally due to our mock.
3021 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
3022 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3023 mock_proc_stdin.write.side_effect = BrokenPipeError
3024 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3025 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3026 mock_proc_stdin.close.assert_called_once_with()
3027
3028 def test_communicate_BrokenPipeError_stdin_flush(self):
3029 # Setting stdin and stdout forces the ._communicate() code path.
3030 # python -h exits faster than python -c pass (but spams stdout).
3031 proc = subprocess.Popen([sys.executable, '-h'],
3032 stdin=subprocess.PIPE,
3033 stdout=subprocess.PIPE)
3034 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3035 open(os.devnull, 'wb') as dev_null:
3036 mock_proc_stdin.flush.side_effect = BrokenPipeError
3037 # because _communicate registers a selector using proc.stdin...
3038 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3039 # _communicate() should swallow BrokenPipeError from flush.
3040 proc.communicate(b'stuff')
3041 mock_proc_stdin.flush.assert_called_once_with()
3042
3043 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3044 # Setting stdin and stdout forces the ._communicate() code path.
3045 # python -h exits faster than python -c pass (but spams stdout).
3046 proc = subprocess.Popen([sys.executable, '-h'],
3047 stdin=subprocess.PIPE,
3048 stdout=subprocess.PIPE)
3049 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3050 mock_proc_stdin.close.side_effect = BrokenPipeError
3051 # _communicate() should swallow BrokenPipeError from close.
3052 proc.communicate(timeout=999)
3053 mock_proc_stdin.close.assert_called_once_with()
3054
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003055 @unittest.skipUnless(_testcapi is not None
3056 and hasattr(_testcapi, 'W_STOPCODE'),
3057 'need _testcapi.W_STOPCODE')
3058 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003059 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003060 args = [sys.executable, '-c', 'pass']
3061 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003062
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003063 # Wait until the real process completes to avoid zombie process
3064 pid = proc.pid
3065 pid, status = os.waitpid(pid, 0)
3066 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003067
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003068 status = _testcapi.W_STOPCODE(3)
3069 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
3070 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003071
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003072 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003073
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003074
Victor Stinner937ee9e2018-06-26 02:11:06 +02003075@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003076class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003077
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003078 def test_startupinfo(self):
3079 # startupinfo argument
3080 # We uses hardcoded constants, because we do not want to
3081 # depend on win32all.
3082 STARTF_USESHOWWINDOW = 1
3083 SW_MAXIMIZE = 3
3084 startupinfo = subprocess.STARTUPINFO()
3085 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3086 startupinfo.wShowWindow = SW_MAXIMIZE
3087 # Since Python is a console process, it won't be affected
3088 # by wShowWindow, but the argument should be silently
3089 # ignored
3090 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003091 startupinfo=startupinfo)
3092
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303093 def test_startupinfo_keywords(self):
3094 # startupinfo argument
3095 # We use hardcoded constants, because we do not want to
3096 # depend on win32all.
3097 STARTF_USERSHOWWINDOW = 1
3098 SW_MAXIMIZE = 3
3099 startupinfo = subprocess.STARTUPINFO(
3100 dwFlags=STARTF_USERSHOWWINDOW,
3101 wShowWindow=SW_MAXIMIZE
3102 )
3103 # Since Python is a console process, it won't be affected
3104 # by wShowWindow, but the argument should be silently
3105 # ignored
3106 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3107 startupinfo=startupinfo)
3108
Victor Stinner483422f2018-07-05 22:54:17 +02003109 def test_startupinfo_copy(self):
3110 # bpo-34044: Popen must not modify input STARTUPINFO structure
3111 startupinfo = subprocess.STARTUPINFO()
3112 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3113 startupinfo.wShowWindow = subprocess.SW_HIDE
3114
3115 # Call Popen() twice with the same startupinfo object to make sure
3116 # that it's not modified
3117 for _ in range(2):
3118 cmd = [sys.executable, "-c", "pass"]
3119 with open(os.devnull, 'w') as null:
3120 proc = subprocess.Popen(cmd,
3121 stdout=null,
3122 stderr=subprocess.STDOUT,
3123 startupinfo=startupinfo)
3124 with proc:
3125 proc.communicate()
3126 self.assertEqual(proc.returncode, 0)
3127
3128 self.assertEqual(startupinfo.dwFlags,
3129 subprocess.STARTF_USESHOWWINDOW)
3130 self.assertIsNone(startupinfo.hStdInput)
3131 self.assertIsNone(startupinfo.hStdOutput)
3132 self.assertIsNone(startupinfo.hStdError)
3133 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3134 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3135
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003136 def test_creationflags(self):
3137 # creationflags argument
3138 CREATE_NEW_CONSOLE = 16
3139 sys.stderr.write(" a DOS box should flash briefly ...\n")
3140 subprocess.call(sys.executable +
3141 ' -c "import time; time.sleep(0.25)"',
3142 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003143
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003144 def test_invalid_args(self):
3145 # invalid arguments should raise ValueError
3146 self.assertRaises(ValueError, subprocess.call,
3147 [sys.executable, "-c",
3148 "import sys; sys.exit(47)"],
3149 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003150
Oren Milman0b3a87e2017-09-14 22:30:28 +03003151 @support.cpython_only
3152 def test_issue31471(self):
3153 # There shouldn't be an assertion failure in Popen() in case the env
3154 # argument has a bad keys() method.
3155 class BadEnv(dict):
3156 keys = None
3157 with self.assertRaises(TypeError):
3158 subprocess.Popen([sys.executable, "-c", "pass"], env=BadEnv())
3159
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003160 def test_close_fds(self):
3161 # close file descriptors
3162 rc = subprocess.call([sys.executable, "-c",
3163 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003164 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003165 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003166
Segev Finerb2a60832017-12-18 11:28:19 +02003167 def test_close_fds_with_stdio(self):
3168 import msvcrt
3169
3170 fds = os.pipe()
3171 self.addCleanup(os.close, fds[0])
3172 self.addCleanup(os.close, fds[1])
3173
3174 handles = []
3175 for fd in fds:
3176 os.set_inheritable(fd, True)
3177 handles.append(msvcrt.get_osfhandle(fd))
3178
3179 p = subprocess.Popen([sys.executable, "-c",
3180 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3181 stdout=subprocess.PIPE, close_fds=False)
3182 stdout, stderr = p.communicate()
3183 self.assertEqual(p.returncode, 0)
3184 int(stdout.strip()) # Check that stdout is an integer
3185
3186 p = subprocess.Popen([sys.executable, "-c",
3187 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3188 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3189 stdout, stderr = p.communicate()
3190 self.assertEqual(p.returncode, 1)
3191 self.assertIn(b"OSError", stderr)
3192
3193 # The same as the previous call, but with an empty handle_list
3194 handle_list = []
3195 startupinfo = subprocess.STARTUPINFO()
3196 startupinfo.lpAttributeList = {"handle_list": handle_list}
3197 p = subprocess.Popen([sys.executable, "-c",
3198 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3199 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3200 startupinfo=startupinfo, close_fds=True)
3201 stdout, stderr = p.communicate()
3202 self.assertEqual(p.returncode, 1)
3203 self.assertIn(b"OSError", stderr)
3204
3205 # Check for a warning due to using handle_list and close_fds=False
3206 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3207 startupinfo = subprocess.STARTUPINFO()
3208 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3209 p = subprocess.Popen([sys.executable, "-c",
3210 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3211 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3212 startupinfo=startupinfo, close_fds=False)
3213 stdout, stderr = p.communicate()
3214 self.assertEqual(p.returncode, 0)
3215
3216 def test_empty_attribute_list(self):
3217 startupinfo = subprocess.STARTUPINFO()
3218 startupinfo.lpAttributeList = {}
3219 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3220 startupinfo=startupinfo)
3221
3222 def test_empty_handle_list(self):
3223 startupinfo = subprocess.STARTUPINFO()
3224 startupinfo.lpAttributeList = {"handle_list": []}
3225 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3226 startupinfo=startupinfo)
3227
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003228 def test_shell_sequence(self):
3229 # Run command through the shell (sequence)
3230 newenv = os.environ.copy()
3231 newenv["FRUIT"] = "physalis"
3232 p = subprocess.Popen(["set"], shell=1,
3233 stdout=subprocess.PIPE,
3234 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003235 with p:
3236 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003237
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003238 def test_shell_string(self):
3239 # Run command through the shell (string)
3240 newenv = os.environ.copy()
3241 newenv["FRUIT"] = "physalis"
3242 p = subprocess.Popen("set", shell=1,
3243 stdout=subprocess.PIPE,
3244 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003245 with p:
3246 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003247
Steve Dower050acae2016-09-06 20:16:17 -07003248 def test_shell_encodings(self):
3249 # Run command through the shell (string)
3250 for enc in ['ansi', 'oem']:
3251 newenv = os.environ.copy()
3252 newenv["FRUIT"] = "physalis"
3253 p = subprocess.Popen("set", shell=1,
3254 stdout=subprocess.PIPE,
3255 env=newenv,
3256 encoding=enc)
3257 with p:
3258 self.assertIn("physalis", p.stdout.read(), enc)
3259
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003260 def test_call_string(self):
3261 # call() function with string argument on Windows
3262 rc = subprocess.call(sys.executable +
3263 ' -c "import sys; sys.exit(47)"')
3264 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003265
Florent Xicluna4886d242010-03-08 13:27:26 +00003266 def _kill_process(self, method, *args):
3267 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003268 p = subprocess.Popen([sys.executable, "-c", """if 1:
3269 import sys, time
3270 sys.stdout.write('x\\n')
3271 sys.stdout.flush()
3272 time.sleep(30)
3273 """],
3274 stdin=subprocess.PIPE,
3275 stdout=subprocess.PIPE,
3276 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003277 with p:
3278 # Wait for the interpreter to be completely initialized before
3279 # sending any signal.
3280 p.stdout.read(1)
3281 getattr(p, method)(*args)
3282 _, stderr = p.communicate()
3283 self.assertStderrEqual(stderr, b'')
3284 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003285 self.assertNotEqual(returncode, 0)
3286
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003287 def _kill_dead_process(self, method, *args):
3288 p = subprocess.Popen([sys.executable, "-c", """if 1:
3289 import sys, time
3290 sys.stdout.write('x\\n')
3291 sys.stdout.flush()
3292 sys.exit(42)
3293 """],
3294 stdin=subprocess.PIPE,
3295 stdout=subprocess.PIPE,
3296 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003297 with p:
3298 # Wait for the interpreter to be completely initialized before
3299 # sending any signal.
3300 p.stdout.read(1)
3301 # The process should end after this
3302 time.sleep(1)
3303 # This shouldn't raise even though the child is now dead
3304 getattr(p, method)(*args)
3305 _, stderr = p.communicate()
3306 self.assertStderrEqual(stderr, b'')
3307 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003308 self.assertEqual(rc, 42)
3309
Florent Xicluna4886d242010-03-08 13:27:26 +00003310 def test_send_signal(self):
3311 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003312
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003313 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003314 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003315
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003316 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003317 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003318
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003319 def test_send_signal_dead(self):
3320 self._kill_dead_process('send_signal', signal.SIGTERM)
3321
3322 def test_kill_dead(self):
3323 self._kill_dead_process('kill')
3324
3325 def test_terminate_dead(self):
3326 self._kill_dead_process('terminate')
3327
Martin Panter23172bd2016-04-16 11:28:10 +00003328class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003329
3330 class RecordingPopen(subprocess.Popen):
3331 """A Popen that saves a reference to each instance for testing."""
3332 instances_created = []
3333
3334 def __init__(self, *args, **kwargs):
3335 super().__init__(*args, **kwargs)
3336 self.instances_created.append(self)
3337
3338 @mock.patch.object(subprocess.Popen, "_communicate")
3339 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3340 **kwargs):
3341 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3342
3343 This avoids the need to actually try and get test environments to send
3344 and receive signals reliably across platforms. The net effect of a ^C
3345 happening during a blocking subprocess execution which we want to clean
3346 up from is a KeyboardInterrupt coming out of communicate() or wait().
3347 """
3348
3349 mock__communicate.side_effect = KeyboardInterrupt
3350 try:
3351 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3352 # We patch out _wait() as no signal was involved so the
3353 # child process isn't actually going to exit rapidly.
3354 mock__wait.side_effect = KeyboardInterrupt
3355 with mock.patch.object(subprocess, "Popen",
3356 self.RecordingPopen):
3357 with self.assertRaises(KeyboardInterrupt):
3358 popener([sys.executable, "-c",
3359 "import time\ntime.sleep(9)\nimport sys\n"
3360 "sys.stderr.write('\\n!runaway child!\\n')"],
3361 stdout=subprocess.DEVNULL, **kwargs)
3362 for call in mock__wait.call_args_list[1:]:
3363 self.assertNotEqual(
3364 call, mock.call(timeout=None),
3365 "no open-ended wait() after the first allowed: "
3366 f"{mock__wait.call_args_list}")
3367 sigint_calls = []
3368 for call in mock__wait.call_args_list:
3369 if call == mock.call(timeout=0.25): # from Popen.__init__
3370 sigint_calls.append(call)
3371 self.assertLessEqual(mock__wait.call_count, 2,
3372 msg=mock__wait.call_args_list)
3373 self.assertEqual(len(sigint_calls), 1,
3374 msg=mock__wait.call_args_list)
3375 finally:
3376 # cleanup the forgotten (due to our mocks) child process
3377 process = self.RecordingPopen.instances_created.pop()
3378 process.kill()
3379 process.wait()
3380 self.assertEqual([], self.RecordingPopen.instances_created)
3381
3382 def test_call_keyboardinterrupt_no_kill(self):
3383 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3384
3385 def test_run_keyboardinterrupt_no_kill(self):
3386 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3387
3388 def test_context_manager_keyboardinterrupt_no_kill(self):
3389 def popen_via_context_manager(*args, **kwargs):
3390 with subprocess.Popen(*args, **kwargs) as unused_process:
3391 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3392 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3393
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003394 def test_getoutput(self):
3395 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3396 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3397 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003398
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003399 # we use mkdtemp in the next line to create an empty directory
3400 # under our exclusive control; from that, we can invent a pathname
3401 # that we _know_ won't exist. This is guaranteed to fail.
3402 dir = None
3403 try:
3404 dir = tempfile.mkdtemp()
3405 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003406 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003407 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003408 self.assertNotEqual(status, 0)
3409 finally:
3410 if dir is not None:
3411 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003412
Gregory P. Smithace55862015-04-07 15:57:54 -07003413 def test__all__(self):
3414 """Ensure that __all__ is populated properly."""
Patrick McLean2b2ead72019-09-12 10:15:44 -07003415 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003416 exported = set(subprocess.__all__)
3417 possible_exports = set()
3418 import types
3419 for name, value in subprocess.__dict__.items():
3420 if name.startswith('_'):
3421 continue
3422 if isinstance(value, (types.ModuleType,)):
3423 continue
3424 possible_exports.add(name)
3425 self.assertEqual(exported, possible_exports - intentionally_excluded)
3426
3427
Martin Panter23172bd2016-04-16 11:28:10 +00003428@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3429 "Test needs selectors.PollSelector")
3430class ProcessTestCaseNoPoll(ProcessTestCase):
3431 def setUp(self):
3432 self.orig_selector = subprocess._PopenSelector
3433 subprocess._PopenSelector = selectors.SelectSelector
3434 ProcessTestCase.setUp(self)
3435
3436 def tearDown(self):
3437 subprocess._PopenSelector = self.orig_selector
3438 ProcessTestCase.tearDown(self)
3439
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003440
Victor Stinner937ee9e2018-06-26 02:11:06 +02003441@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003442class CommandsWithSpaces (BaseTestCase):
3443
3444 def setUp(self):
3445 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003446 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003447 self.fname = fname.lower ()
3448 os.write(f, b"import sys;"
3449 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3450 )
3451 os.close(f)
3452
3453 def tearDown(self):
3454 os.remove(self.fname)
3455 super().tearDown()
3456
3457 def with_spaces(self, *args, **kwargs):
3458 kwargs['stdout'] = subprocess.PIPE
3459 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003460 with p:
3461 self.assertEqual(
3462 p.stdout.read ().decode("mbcs"),
3463 "2 [%r, 'ab cd']" % self.fname
3464 )
Tim Golden126c2962010-08-11 14:20:40 +00003465
3466 def test_shell_string_with_spaces(self):
3467 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003468 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3469 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003470
3471 def test_shell_sequence_with_spaces(self):
3472 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003473 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003474
3475 def test_noshell_string_with_spaces(self):
3476 # call() function with string argument with spaces on Windows
3477 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3478 "ab cd"))
3479
3480 def test_noshell_sequence_with_spaces(self):
3481 # call() function with sequence argument with spaces on Windows
3482 self.with_spaces([sys.executable, self.fname, "ab cd"])
3483
Brian Curtin79cdb662010-12-03 02:46:02 +00003484
Georg Brandla86b2622012-02-20 21:34:57 +01003485class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003486
3487 def test_pipe(self):
3488 with subprocess.Popen([sys.executable, "-c",
3489 "import sys;"
3490 "sys.stdout.write('stdout');"
3491 "sys.stderr.write('stderr');"],
3492 stdout=subprocess.PIPE,
3493 stderr=subprocess.PIPE) as proc:
3494 self.assertEqual(proc.stdout.read(), b"stdout")
3495 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3496
3497 self.assertTrue(proc.stdout.closed)
3498 self.assertTrue(proc.stderr.closed)
3499
3500 def test_returncode(self):
3501 with subprocess.Popen([sys.executable, "-c",
3502 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003503 pass
3504 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003505 self.assertEqual(proc.returncode, 100)
3506
3507 def test_communicate_stdin(self):
3508 with subprocess.Popen([sys.executable, "-c",
3509 "import sys;"
3510 "sys.exit(sys.stdin.read() == 'context')"],
3511 stdin=subprocess.PIPE) as proc:
3512 proc.communicate(b"context")
3513 self.assertEqual(proc.returncode, 1)
3514
3515 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003516 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003517 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003518 stdout=subprocess.PIPE,
3519 stderr=subprocess.PIPE) as proc:
3520 pass
3521
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003522 def test_broken_pipe_cleanup(self):
3523 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003524 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01003525 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003526 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003527 proc = proc.__enter__()
3528 # Prepare to send enough data to overflow any OS pipe buffering and
3529 # guarantee a broken pipe error. Data is held in BufferedWriter
3530 # buffer until closed.
3531 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003532 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003533 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003534 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003535 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003536 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003537
Brian Curtin79cdb662010-12-03 02:46:02 +00003538
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003539if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003540 unittest.main()