blob: ddee3b94fed95d5d41769efea5c018b8e7b4cfc5 [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
Gregory P. Smith50e16e32017-01-22 17:28:38 -08006import platform
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04008import io
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
Charles-François Natali3a4586a2013-11-08 19:56:59 +010013import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000015import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040016import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020017import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050018import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030019import textwrap
Miss Islington (bot)a13b6542018-03-02 02:17:51 -080020from test.support import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050021
22try:
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080023 import ctypes
24except ImportError:
25 ctypes = None
Gregory P. Smith56bc3b72017-05-23 07:49:13 -070026else:
27 import ctypes.util
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080028
29try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020030 import _testcapi
31except ImportError:
32 _testcapi = None
33
Steve Dower22d06982016-09-06 19:38:15 -070034if support.PGO:
35 raise unittest.SkipTest("test is not helpful for PGO")
36
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000037mswindows = (sys.platform == "win32")
38
39#
40# Depends on the following external programs: Python
41#
42
43if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000044 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
45 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000046else:
47 SETBINARY = ''
48
Victor Stinner9a83f652017-08-21 23:51:31 +020049NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010050# Ignore errors that indicate the command was not found
51NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020052
Florent Xiclunab1e94e82010-02-27 22:12:37 +000053
Florent Xiclunac049d872010-03-27 22:47:23 +000054class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000055 def setUp(self):
56 # Try to minimize the number of children we have so this test
57 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000058 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000060 def tearDown(self):
61 for inst in subprocess._active:
62 inst.wait()
63 subprocess._cleanup()
64 self.assertFalse(subprocess._active, "subprocess._active not empty")
Victor Stinnercc42c122017-07-28 18:00:22 +020065 self.doCleanups()
66 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000067
Florent Xiclunab1e94e82010-02-27 22:12:37 +000068 def assertStderrEqual(self, stderr, expected, msg=None):
69 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
70 # shutdown time. That frustrates tests trying to check stderr produced
71 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000072 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040073 # strip_python_stderr also strips whitespace, so we do too.
74 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000075 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076
Florent Xiclunac049d872010-03-27 22:47:23 +000077
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080078class PopenTestException(Exception):
79 pass
80
81
82class PopenExecuteChildRaises(subprocess.Popen):
83 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
84 _execute_child fails.
85 """
86 def _execute_child(self, *args, **kwargs):
87 raise PopenTestException("Forced Exception for Test")
88
89
Florent Xiclunac049d872010-03-27 22:47:23 +000090class ProcessTestCase(BaseTestCase):
91
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070092 def test_io_buffered_by_default(self):
93 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
94 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
95 stderr=subprocess.PIPE)
96 try:
97 self.assertIsInstance(p.stdin, io.BufferedIOBase)
98 self.assertIsInstance(p.stdout, io.BufferedIOBase)
99 self.assertIsInstance(p.stderr, io.BufferedIOBase)
100 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700101 p.stdin.close()
102 p.stdout.close()
103 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700104 p.wait()
105
106 def test_io_unbuffered_works(self):
107 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
108 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
109 stderr=subprocess.PIPE, bufsize=0)
110 try:
111 self.assertIsInstance(p.stdin, io.RawIOBase)
112 self.assertIsInstance(p.stdout, io.RawIOBase)
113 self.assertIsInstance(p.stderr, io.RawIOBase)
114 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700115 p.stdin.close()
116 p.stdout.close()
117 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700118 p.wait()
119
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000120 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000121 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000122 rc = subprocess.call([sys.executable, "-c",
123 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000124 self.assertEqual(rc, 47)
125
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400126 def test_call_timeout(self):
127 # call() function with timeout argument; we want to test that the child
128 # process gets killed when the timeout expires. If the child isn't
129 # killed, this call will deadlock since subprocess.call waits for the
130 # child.
131 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
132 [sys.executable, "-c", "while True: pass"],
133 timeout=0.1)
134
Peter Astrand454f7672005-01-01 09:36:35 +0000135 def test_check_call_zero(self):
136 # check_call() function with zero return code
137 rc = subprocess.check_call([sys.executable, "-c",
138 "import sys; sys.exit(0)"])
139 self.assertEqual(rc, 0)
140
141 def test_check_call_nonzero(self):
142 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000143 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000144 subprocess.check_call([sys.executable, "-c",
145 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000146 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000147
Georg Brandlf9734072008-12-07 15:30:06 +0000148 def test_check_output(self):
149 # check_output() function with zero return code
150 output = subprocess.check_output(
151 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000152 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000153
154 def test_check_output_nonzero(self):
155 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000156 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000157 subprocess.check_output(
158 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000159 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000160
161 def test_check_output_stderr(self):
162 # check_output() function stderr redirected to stdout
163 output = subprocess.check_output(
164 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
165 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000166 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000167
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300168 def test_check_output_stdin_arg(self):
169 # check_output() can be called with stdin set to a file
170 tf = tempfile.TemporaryFile()
171 self.addCleanup(tf.close)
172 tf.write(b'pear')
173 tf.seek(0)
174 output = subprocess.check_output(
175 [sys.executable, "-c",
176 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
177 stdin=tf)
178 self.assertIn(b'PEAR', output)
179
180 def test_check_output_input_arg(self):
181 # check_output() can be called with input set to a string
182 output = subprocess.check_output(
183 [sys.executable, "-c",
184 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
185 input=b'pear')
186 self.assertIn(b'PEAR', output)
187
Georg Brandlf9734072008-12-07 15:30:06 +0000188 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300189 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000190 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000191 output = subprocess.check_output(
192 [sys.executable, "-c", "print('will not be run')"],
193 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000194 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000195 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000196
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300197 def test_check_output_stdin_with_input_arg(self):
198 # check_output() refuses to accept 'stdin' with 'input'
199 tf = tempfile.TemporaryFile()
200 self.addCleanup(tf.close)
201 tf.write(b'pear')
202 tf.seek(0)
203 with self.assertRaises(ValueError) as c:
204 output = subprocess.check_output(
205 [sys.executable, "-c", "print('will not be run')"],
206 stdin=tf, input=b'hare')
207 self.fail("Expected ValueError when stdin and input args supplied.")
208 self.assertIn('stdin', c.exception.args[0])
209 self.assertIn('input', c.exception.args[0])
210
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400211 def test_check_output_timeout(self):
212 # check_output() function with timeout arg
213 with self.assertRaises(subprocess.TimeoutExpired) as c:
214 output = subprocess.check_output(
215 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200216 "import sys, time\n"
217 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400218 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200219 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400220 # Some heavily loaded buildbots (sparc Debian 3.x) require
221 # this much time to start and print.
222 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400223 self.fail("Expected TimeoutExpired.")
224 self.assertEqual(c.exception.output, b'BDFL')
225
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000226 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000227 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000228 newenv = os.environ.copy()
229 newenv["FRUIT"] = "banana"
230 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000231 'import sys, os;'
232 'sys.exit(os.getenv("FRUIT")=="banana")'],
233 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000234 self.assertEqual(rc, 1)
235
Victor Stinner87b9bc32011-06-01 00:57:47 +0200236 def test_invalid_args(self):
237 # Popen() called with invalid arguments should raise TypeError
238 # but Popen.__del__ should not complain (issue #12085)
239 with support.captured_stderr() as s:
240 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
241 argcount = subprocess.Popen.__init__.__code__.co_argcount
242 too_many_args = [0] * (argcount + 1)
243 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
244 self.assertEqual(s.getvalue(), '')
245
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000246 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000247 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000248 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000249 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000250 self.addCleanup(p.stdout.close)
251 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000252 p.wait()
253 self.assertEqual(p.stdin, None)
254
255 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200256 # .stdout is None when not redirected, and the child's stdout will
257 # be inherited from the parent. In order to test this we run a
258 # subprocess in a subprocess:
259 # this_test
260 # \-- subprocess created by this test (parent)
261 # \-- subprocess created by the parent subprocess (child)
262 # The parent doesn't specify stdout, so the child will use the
263 # parent's stdout. This test checks that the message printed by the
264 # child goes to the parent stdout. The parent also checks that the
265 # child's stdout is None. See #11963.
266 code = ('import sys; from subprocess import Popen, PIPE;'
267 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
268 ' stdin=PIPE, stderr=PIPE);'
269 'p.wait(); assert p.stdout is None;')
270 p = subprocess.Popen([sys.executable, "-c", code],
271 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
272 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000273 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200274 out, err = p.communicate()
275 self.assertEqual(p.returncode, 0, err)
276 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000277
278 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000279 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000280 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000282 self.addCleanup(p.stdout.close)
283 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000284 p.wait()
285 self.assertEqual(p.stderr, None)
286
Chris Jerdonek776cb192012-10-08 15:56:43 -0700287 def _assert_python(self, pre_args, **kwargs):
288 # We include sys.exit() to prevent the test runner from hanging
289 # whenever python is found.
290 args = pre_args + ["import sys; sys.exit(47)"]
291 p = subprocess.Popen(args, **kwargs)
292 p.wait()
293 self.assertEqual(47, p.returncode)
294
295 def test_executable(self):
296 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700297 #
298 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
299 # determine where its standard library is, so we need the directory
300 # of args[0] to be valid for the Popen() call to Python to succeed.
301 # See also issue #16170 and issue #7774.
302 doesnotexist = os.path.join(os.path.dirname(sys.executable),
303 "doesnotexist")
304 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700305
306 def test_executable_takes_precedence(self):
307 # Check that the executable argument takes precedence over args[0].
308 #
309 # Verify first that the call succeeds without the executable arg.
310 pre_args = [sys.executable, "-c"]
311 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100312 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100313 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100314 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700315
316 @unittest.skipIf(mswindows, "executable argument replaces shell")
317 def test_executable_replaces_shell(self):
318 # Check that the executable argument replaces the default shell
319 # when shell=True.
320 self._assert_python([], executable=sys.executable, shell=True)
321
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700322 # For use in the test_cwd* tests below.
323 def _normalize_cwd(self, cwd):
324 # Normalize an expected cwd (for Tru64 support).
325 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
326 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300327 with support.change_cwd(cwd):
328 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700329
330 # For use in the test_cwd* tests below.
331 def _split_python_path(self):
332 # Return normalized (python_dir, python_base).
333 python_path = os.path.realpath(sys.executable)
334 return os.path.split(python_path)
335
336 # For use in the test_cwd* tests below.
337 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
338 # Invoke Python via Popen, and assert that (1) the call succeeds,
339 # and that (2) the current working directory of the child process
340 # matches *expected_cwd*.
341 p = subprocess.Popen([python_arg, "-c",
342 "import os, sys; "
343 "sys.stdout.write(os.getcwd()); "
344 "sys.exit(47)"],
345 stdout=subprocess.PIPE,
346 **kwargs)
347 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000348 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700349 self.assertEqual(47, p.returncode)
350 normcase = os.path.normcase
351 self.assertEqual(normcase(expected_cwd),
352 normcase(p.stdout.read().decode("utf-8")))
353
354 def test_cwd(self):
355 # Check that cwd changes the cwd for the child process.
356 temp_dir = tempfile.gettempdir()
357 temp_dir = self._normalize_cwd(temp_dir)
358 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
359
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530360 def test_cwd_with_pathlike(self):
361 temp_dir = tempfile.gettempdir()
362 temp_dir = self._normalize_cwd(temp_dir)
Miss Islington (bot)a13b6542018-03-02 02:17:51 -0800363 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530364
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700365 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700366 def test_cwd_with_relative_arg(self):
367 # Check that Popen looks for args[0] relative to cwd if args[0]
368 # is relative.
369 python_dir, python_base = self._split_python_path()
370 rel_python = os.path.join(os.curdir, python_base)
371 with support.temp_cwd() as wrong_dir:
372 # Before calling with the correct cwd, confirm that the call fails
373 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700374 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700375 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700376 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700377 [rel_python], cwd=wrong_dir)
378 python_dir = self._normalize_cwd(python_dir)
379 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
380
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700381 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700382 def test_cwd_with_relative_executable(self):
383 # Check that Popen looks for executable relative to cwd if executable
384 # is relative (and that executable takes precedence over args[0]).
385 python_dir, python_base = self._split_python_path()
386 rel_python = os.path.join(os.curdir, python_base)
387 doesntexist = "somethingyoudonthave"
388 with support.temp_cwd() as wrong_dir:
389 # Before calling with the correct cwd, confirm that the call fails
390 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700391 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700392 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700393 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700394 [doesntexist], executable=rel_python,
395 cwd=wrong_dir)
396 python_dir = self._normalize_cwd(python_dir)
397 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
398 cwd=python_dir)
399
400 def test_cwd_with_absolute_arg(self):
401 # Check that Popen can find the executable when the cwd is wrong
402 # if args[0] is an absolute path.
403 python_dir, python_base = self._split_python_path()
404 abs_python = os.path.join(python_dir, python_base)
405 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300406 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700407 # Before calling with an absolute path, confirm that using a
408 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700409 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700410 [rel_python], cwd=wrong_dir)
411 wrong_dir = self._normalize_cwd(wrong_dir)
412 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
413
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100414 @unittest.skipIf(sys.base_prefix != sys.prefix,
415 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000416 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700417 python_dir, python_base = self._split_python_path()
418 python_dir = self._normalize_cwd(python_dir)
419 self._assert_cwd(python_dir, "somethingyoudonthave",
420 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000421
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100422 @unittest.skipIf(sys.base_prefix != sys.prefix,
423 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000424 @unittest.skipIf(sysconfig.is_python_build(),
425 "need an installed Python. See #7774")
426 def test_executable_without_cwd(self):
427 # For a normal installation, it should work without 'cwd'
428 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700429 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
430 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000431
432 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000433 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000434 p = subprocess.Popen([sys.executable, "-c",
435 'import sys; sys.exit(sys.stdin.read() == "pear")'],
436 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000437 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438 p.stdin.close()
439 p.wait()
440 self.assertEqual(p.returncode, 1)
441
442 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000443 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000444 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000445 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000446 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000447 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000448 os.lseek(d, 0, 0)
449 p = subprocess.Popen([sys.executable, "-c",
450 'import sys; sys.exit(sys.stdin.read() == "pear")'],
451 stdin=d)
452 p.wait()
453 self.assertEqual(p.returncode, 1)
454
455 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000456 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000457 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000458 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000459 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000460 tf.seek(0)
461 p = subprocess.Popen([sys.executable, "-c",
462 'import sys; sys.exit(sys.stdin.read() == "pear")'],
463 stdin=tf)
464 p.wait()
465 self.assertEqual(p.returncode, 1)
466
467 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000468 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000469 p = subprocess.Popen([sys.executable, "-c",
470 'import sys; sys.stdout.write("orange")'],
471 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200472 with p:
473 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474
475 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000476 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000477 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000478 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479 d = tf.fileno()
480 p = subprocess.Popen([sys.executable, "-c",
481 'import sys; sys.stdout.write("orange")'],
482 stdout=d)
483 p.wait()
484 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000485 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000486
487 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000488 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000489 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000490 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000491 p = subprocess.Popen([sys.executable, "-c",
492 'import sys; sys.stdout.write("orange")'],
493 stdout=tf)
494 p.wait()
495 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000496 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000497
498 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000499 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500 p = subprocess.Popen([sys.executable, "-c",
501 'import sys; sys.stderr.write("strawberry")'],
502 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200503 with p:
504 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000505
506 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000507 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000508 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000509 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000510 d = tf.fileno()
511 p = subprocess.Popen([sys.executable, "-c",
512 'import sys; sys.stderr.write("strawberry")'],
513 stderr=d)
514 p.wait()
515 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000516 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517
518 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000519 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000520 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000521 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 p = subprocess.Popen([sys.executable, "-c",
523 'import sys; sys.stderr.write("strawberry")'],
524 stderr=tf)
525 p.wait()
526 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000527 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528
Martin Panterc7635892016-05-13 01:54:44 +0000529 def test_stderr_redirect_with_no_stdout_redirect(self):
530 # test stderr=STDOUT while stdout=None (not set)
531
532 # - grandchild prints to stderr
533 # - child redirects grandchild's stderr to its stdout
534 # - the parent should get grandchild's stderr in child's stdout
535 p = subprocess.Popen([sys.executable, "-c",
536 'import sys, subprocess;'
537 'rc = subprocess.call([sys.executable, "-c",'
538 ' "import sys;"'
539 ' "sys.stderr.write(\'42\')"],'
540 ' stderr=subprocess.STDOUT);'
541 'sys.exit(rc)'],
542 stdout=subprocess.PIPE,
543 stderr=subprocess.PIPE)
544 stdout, stderr = p.communicate()
545 #NOTE: stdout should get stderr from grandchild
546 self.assertStderrEqual(stdout, b'42')
547 self.assertStderrEqual(stderr, b'') # should be empty
548 self.assertEqual(p.returncode, 0)
549
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000550 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000551 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000552 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000553 'import sys;'
554 'sys.stdout.write("apple");'
555 'sys.stdout.flush();'
556 'sys.stderr.write("orange")'],
557 stdout=subprocess.PIPE,
558 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200559 with p:
560 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561
562 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000563 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000564 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000565 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000566 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000567 'import sys;'
568 'sys.stdout.write("apple");'
569 'sys.stdout.flush();'
570 'sys.stderr.write("orange")'],
571 stdout=tf,
572 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000573 p.wait()
574 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000575 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000576
Thomas Wouters89f507f2006-12-13 04:49:30 +0000577 def test_stdout_filedes_of_stdout(self):
578 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200579 # To avoid printing the text on stdout, we do something similar to
580 # test_stdout_none (see above). The parent subprocess calls the child
581 # subprocess passing stdout=1, and this test uses stdout=PIPE in
582 # order to capture and check the output of the parent. See #11963.
583 code = ('import sys, subprocess; '
584 'rc = subprocess.call([sys.executable, "-c", '
585 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
586 'b\'test with stdout=1\'))"], stdout=1); '
587 'assert rc == 18')
588 p = subprocess.Popen([sys.executable, "-c", code],
589 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
590 self.addCleanup(p.stdout.close)
591 self.addCleanup(p.stderr.close)
592 out, err = p.communicate()
593 self.assertEqual(p.returncode, 0, err)
594 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000595
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200596 def test_stdout_devnull(self):
597 p = subprocess.Popen([sys.executable, "-c",
598 'for i in range(10240):'
599 'print("x" * 1024)'],
600 stdout=subprocess.DEVNULL)
601 p.wait()
602 self.assertEqual(p.stdout, None)
603
604 def test_stderr_devnull(self):
605 p = subprocess.Popen([sys.executable, "-c",
606 'import sys\n'
607 'for i in range(10240):'
608 'sys.stderr.write("x" * 1024)'],
609 stderr=subprocess.DEVNULL)
610 p.wait()
611 self.assertEqual(p.stderr, None)
612
613 def test_stdin_devnull(self):
614 p = subprocess.Popen([sys.executable, "-c",
615 'import sys;'
616 'sys.stdin.read(1)'],
617 stdin=subprocess.DEVNULL)
618 p.wait()
619 self.assertEqual(p.stdin, None)
620
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000621 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000622 newenv = os.environ.copy()
623 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200624 with subprocess.Popen([sys.executable, "-c",
625 'import sys,os;'
626 'sys.stdout.write(os.getenv("FRUIT"))'],
627 stdout=subprocess.PIPE,
628 env=newenv) as p:
629 stdout, stderr = p.communicate()
630 self.assertEqual(stdout, b"orange")
631
Victor Stinner62d51182011-06-23 01:02:25 +0200632 # Windows requires at least the SYSTEMROOT environment variable to start
633 # Python
634 @unittest.skipIf(sys.platform == 'win32',
635 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700636 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
637 'The Python shared library cannot be loaded '
638 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200639 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700640 """Verify that env={} is as empty as possible."""
641
Gregory P. Smith85aba232017-05-30 16:21:47 -0700642 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700643 """Determine if an environment variable is under our control."""
644 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
645 # on adding even when the environment in exec is empty.
646 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700647 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400648 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000649 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
650 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700651
Victor Stinnerf1512a22011-06-21 17:18:38 +0200652 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700653 'import os; print(list(os.environ.keys()))'],
654 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200655 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700656 child_env_names = eval(stdout.strip())
657 self.assertIsInstance(child_env_names, list)
658 child_env_names = [k for k in child_env_names
659 if not is_env_var_to_ignore(k)]
660 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000661
Serhiy Storchakad174d242017-06-23 19:39:27 +0300662 def test_invalid_cmd(self):
663 # null character in the command name
664 cmd = sys.executable + '\0'
665 with self.assertRaises(ValueError):
666 subprocess.Popen([cmd, "-c", "pass"])
667
668 # null character in the command argument
669 with self.assertRaises(ValueError):
670 subprocess.Popen([sys.executable, "-c", "pass#\0"])
671
672 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300673 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300674 newenv = os.environ.copy()
675 newenv["FRUIT\0VEGETABLE"] = "cabbage"
676 with self.assertRaises(ValueError):
677 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
678
Ville Skyttä49b27342017-08-03 09:00:59 +0300679 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300680 newenv = os.environ.copy()
681 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
682 with self.assertRaises(ValueError):
683 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
684
Ville Skyttä49b27342017-08-03 09:00:59 +0300685 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300686 newenv = os.environ.copy()
687 newenv["FRUIT=ORANGE"] = "lemon"
688 with self.assertRaises(ValueError):
689 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
690
Ville Skyttä49b27342017-08-03 09:00:59 +0300691 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300692 newenv = os.environ.copy()
693 newenv["FRUIT"] = "orange=lemon"
694 with subprocess.Popen([sys.executable, "-c",
695 'import sys, os;'
696 'sys.stdout.write(os.getenv("FRUIT"))'],
697 stdout=subprocess.PIPE,
698 env=newenv) as p:
699 stdout, stderr = p.communicate()
700 self.assertEqual(stdout, b"orange=lemon")
701
Peter Astrandcbac93c2005-03-03 20:24:28 +0000702 def test_communicate_stdin(self):
703 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000704 'import sys;'
705 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000706 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000707 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000708 self.assertEqual(p.returncode, 1)
709
710 def test_communicate_stdout(self):
711 p = subprocess.Popen([sys.executable, "-c",
712 'import sys; sys.stdout.write("pineapple")'],
713 stdout=subprocess.PIPE)
714 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000715 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000716 self.assertEqual(stderr, None)
717
718 def test_communicate_stderr(self):
719 p = subprocess.Popen([sys.executable, "-c",
720 'import sys; sys.stderr.write("pineapple")'],
721 stderr=subprocess.PIPE)
722 (stdout, stderr) = p.communicate()
723 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000724 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000725
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000726 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000727 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000728 'import sys,os;'
729 'sys.stderr.write("pineapple");'
730 'sys.stdout.write(sys.stdin.read())'],
731 stdin=subprocess.PIPE,
732 stdout=subprocess.PIPE,
733 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000734 self.addCleanup(p.stdout.close)
735 self.addCleanup(p.stderr.close)
736 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000737 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000738 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000739 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000740
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400741 def test_communicate_timeout(self):
742 p = subprocess.Popen([sys.executable, "-c",
743 'import sys,os,time;'
744 'sys.stderr.write("pineapple\\n");'
745 'time.sleep(1);'
746 'sys.stderr.write("pear\\n");'
747 'sys.stdout.write(sys.stdin.read())'],
748 universal_newlines=True,
749 stdin=subprocess.PIPE,
750 stdout=subprocess.PIPE,
751 stderr=subprocess.PIPE)
752 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
753 timeout=0.3)
754 # Make sure we can keep waiting for it, and that we get the whole output
755 # after it completes.
756 (stdout, stderr) = p.communicate()
757 self.assertEqual(stdout, "banana")
758 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
759
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700760 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200761 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400762 p = subprocess.Popen([sys.executable, "-c",
763 'import sys,os,time;'
764 'sys.stdout.write("a" * (64 * 1024));'
765 'time.sleep(0.2);'
766 'sys.stdout.write("a" * (64 * 1024));'
767 'time.sleep(0.2);'
768 'sys.stdout.write("a" * (64 * 1024));'
769 'time.sleep(0.2);'
770 'sys.stdout.write("a" * (64 * 1024));'],
771 stdout=subprocess.PIPE)
772 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
773 (stdout, _) = p.communicate()
774 self.assertEqual(len(stdout), 4 * 64 * 1024)
775
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000776 # Test for the fd leak reported in http://bugs.python.org/issue2791.
777 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000778 for stdin_pipe in (False, True):
779 for stdout_pipe in (False, True):
780 for stderr_pipe in (False, True):
781 options = {}
782 if stdin_pipe:
783 options['stdin'] = subprocess.PIPE
784 if stdout_pipe:
785 options['stdout'] = subprocess.PIPE
786 if stderr_pipe:
787 options['stderr'] = subprocess.PIPE
788 if not options:
789 continue
790 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
791 p.communicate()
792 if p.stdin is not None:
793 self.assertTrue(p.stdin.closed)
794 if p.stdout is not None:
795 self.assertTrue(p.stdout.closed)
796 if p.stderr is not None:
797 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000798
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000799 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000800 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000801 p = subprocess.Popen([sys.executable, "-c",
802 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000803 (stdout, stderr) = p.communicate()
804 self.assertEqual(stdout, None)
805 self.assertEqual(stderr, None)
806
807 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000808 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000809 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000810 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000811 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000812 os.close(x)
813 os.close(y)
814 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000815 'import sys,os;'
816 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200817 'sys.stderr.write("x" * %d);'
818 'sys.stdout.write(sys.stdin.read())' %
819 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000820 stdin=subprocess.PIPE,
821 stdout=subprocess.PIPE,
822 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000823 self.addCleanup(p.stdout.close)
824 self.addCleanup(p.stderr.close)
825 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200826 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000827 (stdout, stderr) = p.communicate(string_to_write)
828 self.assertEqual(stdout, string_to_write)
829
830 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000831 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000832 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000833 'import sys,os;'
834 'sys.stdout.write(sys.stdin.read())'],
835 stdin=subprocess.PIPE,
836 stdout=subprocess.PIPE,
837 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000838 self.addCleanup(p.stdout.close)
839 self.addCleanup(p.stderr.close)
840 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000841 p.stdin.write(b"banana")
842 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000843 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000844 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000845
andyclegg7fed7bd2017-10-23 03:01:19 +0100846 def test_universal_newlines_and_text(self):
847 args = [
848 sys.executable, "-c",
849 'import sys,os;' + SETBINARY +
850 'buf = sys.stdout.buffer;'
851 'buf.write(sys.stdin.readline().encode());'
852 'buf.flush();'
853 'buf.write(b"line2\\n");'
854 'buf.flush();'
855 'buf.write(sys.stdin.read().encode());'
856 'buf.flush();'
857 'buf.write(b"line4\\n");'
858 'buf.flush();'
859 'buf.write(b"line5\\r\\n");'
860 'buf.flush();'
861 'buf.write(b"line6\\r");'
862 'buf.flush();'
863 'buf.write(b"\\nline7");'
864 'buf.flush();'
865 'buf.write(b"\\nline8");']
866
867 for extra_kwarg in ('universal_newlines', 'text'):
868 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
869 'stdout': subprocess.PIPE,
870 extra_kwarg: True})
871 with p:
872 p.stdin.write("line1\n")
873 p.stdin.flush()
874 self.assertEqual(p.stdout.readline(), "line1\n")
875 p.stdin.write("line3\n")
876 p.stdin.close()
877 self.addCleanup(p.stdout.close)
878 self.assertEqual(p.stdout.readline(),
879 "line2\n")
880 self.assertEqual(p.stdout.read(6),
881 "line3\n")
882 self.assertEqual(p.stdout.read(),
883 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000884
885 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000886 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000887 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000888 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200889 'buf = sys.stdout.buffer;'
890 'buf.write(b"line2\\n");'
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");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200901 stderr=subprocess.PIPE,
902 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000903 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000904 self.addCleanup(p.stdout.close)
905 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000906 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200907 self.assertEqual(stdout,
908 "line2\nline4\nline5\nline6\nline7\nline8")
909
910 def test_universal_newlines_communicate_stdin(self):
911 # universal newlines through communicate(), with only stdin
912 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300913 'import sys,os;' + SETBINARY + textwrap.dedent('''
914 s = sys.stdin.readline()
915 assert s == "line1\\n", repr(s)
916 s = sys.stdin.read()
917 assert s == "line3\\n", repr(s)
918 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200919 stdin=subprocess.PIPE,
920 universal_newlines=1)
921 (stdout, stderr) = p.communicate("line1\nline3\n")
922 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000923
Andrew Svetlovf3765072012-08-14 18:35:17 +0300924 def test_universal_newlines_communicate_input_none(self):
925 # Test communicate(input=None) with universal newlines.
926 #
927 # We set stdout to PIPE because, as of this writing, a different
928 # code path is tested when the number of pipes is zero or one.
929 p = subprocess.Popen([sys.executable, "-c", "pass"],
930 stdin=subprocess.PIPE,
931 stdout=subprocess.PIPE,
932 universal_newlines=True)
933 p.communicate()
934 self.assertEqual(p.returncode, 0)
935
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300936 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300937 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300938 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300939 'import sys,os;' + SETBINARY + textwrap.dedent('''
940 s = sys.stdin.buffer.readline()
941 sys.stdout.buffer.write(s)
942 sys.stdout.buffer.write(b"line2\\r")
943 sys.stderr.buffer.write(b"eline2\\n")
944 s = sys.stdin.buffer.read()
945 sys.stdout.buffer.write(s)
946 sys.stdout.buffer.write(b"line4\\n")
947 sys.stdout.buffer.write(b"line5\\r\\n")
948 sys.stderr.buffer.write(b"eline6\\r")
949 sys.stderr.buffer.write(b"eline7\\r\\nz")
950 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300951 stdin=subprocess.PIPE,
952 stderr=subprocess.PIPE,
953 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300954 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300955 self.addCleanup(p.stdout.close)
956 self.addCleanup(p.stderr.close)
957 (stdout, stderr) = p.communicate("line1\nline3\n")
958 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300959 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300960 # Python debug build push something like "[42442 refs]\n"
961 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300962 # Don't use assertStderrEqual because it strips CR and LF from output.
963 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300964
Andrew Svetlov82860712012-08-19 22:13:41 +0300965 def test_universal_newlines_communicate_encodings(self):
966 # Check that universal newlines mode works for various encodings,
967 # in particular for encodings in the UTF-16 and UTF-32 families.
968 # See issue #15595.
969 #
970 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
971 # without, and UTF-16 and UTF-32.
972 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300973 code = ("import sys; "
974 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
975 encoding)
976 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700977 # We set stdin to be non-None because, as of this writing,
978 # a different code path is used when the number of pipes is
979 # zero or one.
980 popen = subprocess.Popen(args,
981 stdin=subprocess.PIPE,
982 stdout=subprocess.PIPE,
983 encoding=encoding)
984 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +0300985 self.assertEqual(stdout, '1\n2\n3\n4')
986
Steve Dower050acae2016-09-06 20:16:17 -0700987 def test_communicate_errors(self):
988 for errors, expected in [
989 ('ignore', ''),
990 ('replace', '\ufffd\ufffd'),
991 ('surrogateescape', '\udc80\udc80'),
992 ('backslashreplace', '\\x80\\x80'),
993 ]:
994 code = ("import sys; "
995 r"sys.stdout.buffer.write(b'[\x80\x80]')")
996 args = [sys.executable, '-c', code]
997 # We set stdin to be non-None because, as of this writing,
998 # a different code path is used when the number of pipes is
999 # zero or one.
1000 popen = subprocess.Popen(args,
1001 stdin=subprocess.PIPE,
1002 stdout=subprocess.PIPE,
1003 encoding='utf-8',
1004 errors=errors)
1005 stdout, stderr = popen.communicate(input='')
1006 self.assertEqual(stdout, '[{}]'.format(expected))
1007
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001008 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001009 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +00001010 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001011 max_handles = 1026 # too much for most UNIX systems
1012 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001013 max_handles = 2050 # too much for (at least some) Windows setups
1014 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001015 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001016 try:
1017 for i in range(max_handles):
1018 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001019 tmpfile = os.path.join(tmpdir, support.TESTFN)
1020 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001021 except OSError as e:
1022 if e.errno != errno.EMFILE:
1023 raise
1024 break
1025 else:
1026 self.skipTest("failed to reach the file descriptor limit "
1027 "(tried %d)" % max_handles)
1028 # Close a couple of them (should be enough for a subprocess)
1029 for i in range(10):
1030 os.close(handles.pop())
1031 # Loop creating some subprocesses. If one of them leaks some fds,
1032 # the next loop iteration will fail by reaching the max fd limit.
1033 for i in range(15):
1034 p = subprocess.Popen([sys.executable, "-c",
1035 "import sys;"
1036 "sys.stdout.write(sys.stdin.read())"],
1037 stdin=subprocess.PIPE,
1038 stdout=subprocess.PIPE,
1039 stderr=subprocess.PIPE)
1040 data = p.communicate(b"lime")[0]
1041 self.assertEqual(data, b"lime")
1042 finally:
1043 for h in handles:
1044 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001045 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001046
1047 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001048 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1049 '"a b c" d e')
1050 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1051 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001052 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1053 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001054 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1055 'a\\\\\\b "de fg" h')
1056 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1057 'a\\\\\\"b c d')
1058 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1059 '"a\\\\b c" d e')
1060 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1061 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001062 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1063 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001064
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001065 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001066 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001067 "import os; os.read(0, 1)"],
1068 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001069 self.addCleanup(p.stdin.close)
1070 self.assertIsNone(p.poll())
1071 os.write(p.stdin.fileno(), b'A')
1072 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001073 # Subsequent invocations should just return the returncode
1074 self.assertEqual(p.poll(), 0)
1075
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001076 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001077 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001078 self.assertEqual(p.wait(), 0)
1079 # Subsequent invocations should just return the returncode
1080 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001081
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001082 def test_wait_timeout(self):
1083 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001084 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001085 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001086 p.wait(timeout=0.0001)
1087 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001088 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1089 # time to start.
1090 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001091
Peter Astrand738131d2004-11-30 21:04:45 +00001092 def test_invalid_bufsize(self):
1093 # an invalid type of the bufsize argument should raise
1094 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001095 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001096 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001097
Guido van Rossum46a05a72007-06-07 21:56:45 +00001098 def test_bufsize_is_none(self):
1099 # bufsize=None should be the same as bufsize=0.
1100 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1101 self.assertEqual(p.wait(), 0)
1102 # Again with keyword arg
1103 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1104 self.assertEqual(p.wait(), 0)
1105
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001106 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1107 # subprocess may deadlock with bufsize=1, see issue #21332
1108 with subprocess.Popen([sys.executable, "-c", "import sys;"
1109 "sys.stdout.write(sys.stdin.readline());"
1110 "sys.stdout.flush()"],
1111 stdin=subprocess.PIPE,
1112 stdout=subprocess.PIPE,
1113 stderr=subprocess.DEVNULL,
1114 bufsize=1,
1115 universal_newlines=universal_newlines) as p:
1116 p.stdin.write(line) # expect that it flushes the line in text mode
1117 os.close(p.stdin.fileno()) # close it without flushing the buffer
1118 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001119 with support.SuppressCrashReport():
1120 try:
1121 p.stdin.close()
1122 except OSError:
1123 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001124 p.stdin = None
1125 self.assertEqual(p.returncode, 0)
1126 self.assertEqual(read_line, expected)
1127
1128 def test_bufsize_equal_one_text_mode(self):
1129 # line is flushed in text mode with bufsize=1.
1130 # we should get the full line in return
1131 line = "line\n"
1132 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1133
1134 def test_bufsize_equal_one_binary_mode(self):
1135 # line is not flushed in binary mode with bufsize=1.
1136 # we should get empty response
1137 line = b'line' + os.linesep.encode() # assume ascii-based locale
1138 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1139
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001140 def test_leaking_fds_on_error(self):
1141 # see bug #5179: Popen leaks file descriptors to PIPEs if
1142 # the child fails to execute; this will eventually exhaust
1143 # the maximum number of open fds. 1024 seems a very common
1144 # value for that limit, but Windows has 2048, so we loop
1145 # 1024 times (each call leaked two fds).
1146 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001147 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001148 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001149 stdout=subprocess.PIPE,
1150 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001151
Victor Stinner9a83f652017-08-21 23:51:31 +02001152 def test_nonexisting_with_pipes(self):
1153 # bpo-30121: Popen with pipes must close properly pipes on error.
1154 # Previously, os.close() was called with a Windows handle which is not
1155 # a valid file descriptor.
1156 #
1157 # Run the test in a subprocess to control how the CRT reports errors
1158 # and to get stderr content.
1159 try:
1160 import msvcrt
1161 msvcrt.CrtSetReportMode
1162 except (AttributeError, ImportError):
1163 self.skipTest("need msvcrt.CrtSetReportMode")
1164
1165 code = textwrap.dedent(f"""
1166 import msvcrt
1167 import subprocess
1168
1169 cmd = {NONEXISTING_CMD!r}
1170
1171 for report_type in [msvcrt.CRT_WARN,
1172 msvcrt.CRT_ERROR,
1173 msvcrt.CRT_ASSERT]:
1174 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1175 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1176
1177 try:
Miss Islington (bot)622a8242018-02-19 13:00:22 -08001178 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001179 stdout=subprocess.PIPE,
1180 stderr=subprocess.PIPE)
1181 except OSError:
1182 pass
1183 """)
1184 cmd = [sys.executable, "-c", code]
1185 proc = subprocess.Popen(cmd,
1186 stderr=subprocess.PIPE,
1187 universal_newlines=True)
1188 with proc:
1189 stderr = proc.communicate()[1]
1190 self.assertEqual(stderr, "")
1191 self.assertEqual(proc.returncode, 0)
1192
Antoine Pitroua8392712013-08-30 23:38:13 +02001193 def test_double_close_on_error(self):
1194 # Issue #18851
1195 fds = []
1196 def open_fds():
1197 for i in range(20):
1198 fds.extend(os.pipe())
1199 time.sleep(0.001)
1200 t = threading.Thread(target=open_fds)
1201 t.start()
1202 try:
1203 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001204 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001205 stdin=subprocess.PIPE,
1206 stdout=subprocess.PIPE,
1207 stderr=subprocess.PIPE)
1208 finally:
1209 t.join()
1210 exc = None
1211 for fd in fds:
1212 # If a double close occurred, some of those fds will
1213 # already have been closed by mistake, and os.close()
1214 # here will raise.
1215 try:
1216 os.close(fd)
1217 except OSError as e:
1218 exc = e
1219 if exc is not None:
1220 raise exc
1221
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001222 def test_threadsafe_wait(self):
1223 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1224 proc = subprocess.Popen([sys.executable, '-c',
1225 'import time; time.sleep(12)'])
1226 self.assertEqual(proc.returncode, None)
1227 results = []
1228
1229 def kill_proc_timer_thread():
1230 results.append(('thread-start-poll-result', proc.poll()))
1231 # terminate it from the thread and wait for the result.
1232 proc.kill()
1233 proc.wait()
1234 results.append(('thread-after-kill-and-wait', proc.returncode))
1235 # this wait should be a no-op given the above.
1236 proc.wait()
1237 results.append(('thread-after-second-wait', proc.returncode))
1238
1239 # This is a timing sensitive test, the failure mode is
1240 # triggered when both the main thread and this thread are in
1241 # the wait() call at once. The delay here is to allow the
1242 # main thread to most likely be blocked in its wait() call.
1243 t = threading.Timer(0.2, kill_proc_timer_thread)
1244 t.start()
1245
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001246 if mswindows:
1247 expected_errorcode = 1
1248 else:
1249 # Should be -9 because of the proc.kill() from the thread.
1250 expected_errorcode = -9
1251
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001252 # Wait for the process to finish; the thread should kill it
1253 # long before it finishes on its own. Supplying a timeout
1254 # triggers a different code path for better coverage.
1255 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001256 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001257 msg="unexpected result in wait from main thread")
1258
1259 # This should be a no-op with no change in returncode.
1260 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001261 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001262 msg="unexpected result in second main wait.")
1263
1264 t.join()
1265 # Ensure that all of the thread results are as expected.
1266 # When a race condition occurs in wait(), the returncode could
1267 # be set by the wrong thread that doesn't actually have it
1268 # leading to an incorrect value.
1269 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001270 ('thread-after-kill-and-wait', expected_errorcode),
1271 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001272 results)
1273
Victor Stinnerb3693582010-05-21 20:13:12 +00001274 def test_issue8780(self):
1275 # Ensure that stdout is inherited from the parent
1276 # if stdout=PIPE is not used
1277 code = ';'.join((
1278 'import subprocess, sys',
1279 'retcode = subprocess.call('
1280 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1281 'assert retcode == 0'))
1282 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001283 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001284
Tim Goldenaf5ac392010-08-06 13:03:56 +00001285 def test_handles_closed_on_exception(self):
1286 # If CreateProcess exits with an error, ensure the
1287 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001288 ifhandle, ifname = tempfile.mkstemp()
1289 ofhandle, ofname = tempfile.mkstemp()
1290 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001291 try:
1292 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1293 stderr=efhandle)
1294 except OSError:
1295 os.close(ifhandle)
1296 os.remove(ifname)
1297 os.close(ofhandle)
1298 os.remove(ofname)
1299 os.close(efhandle)
1300 os.remove(efname)
1301 self.assertFalse(os.path.exists(ifname))
1302 self.assertFalse(os.path.exists(ofname))
1303 self.assertFalse(os.path.exists(efname))
1304
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001305 def test_communicate_epipe(self):
1306 # Issue 10963: communicate() should hide EPIPE
1307 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1308 stdin=subprocess.PIPE,
1309 stdout=subprocess.PIPE,
1310 stderr=subprocess.PIPE)
1311 self.addCleanup(p.stdout.close)
1312 self.addCleanup(p.stderr.close)
1313 self.addCleanup(p.stdin.close)
1314 p.communicate(b"x" * 2**20)
1315
1316 def test_communicate_epipe_only_stdin(self):
1317 # Issue 10963: communicate() should hide EPIPE
1318 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1319 stdin=subprocess.PIPE)
1320 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001321 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001322 p.communicate(b"x" * 2**20)
1323
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001324 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1325 "Requires signal.SIGUSR1")
1326 @unittest.skipUnless(hasattr(os, 'kill'),
1327 "Requires os.kill")
1328 @unittest.skipUnless(hasattr(os, 'getppid'),
1329 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001330 def test_communicate_eintr(self):
1331 # Issue #12493: communicate() should handle EINTR
1332 def handler(signum, frame):
1333 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001334 old_handler = signal.signal(signal.SIGUSR1, handler)
1335 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001336
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001337 args = [sys.executable, "-c",
1338 'import os, signal;'
1339 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001340 for stream in ('stdout', 'stderr'):
1341 kw = {stream: subprocess.PIPE}
1342 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001343 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001344 process.communicate()
1345
Tim Peterse718f612004-10-12 21:51:32 +00001346
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001347 # This test is Linux-ish specific for simplicity to at least have
1348 # some coverage. It is not a platform specific bug.
1349 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1350 "Linux specific")
1351 def test_failed_child_execute_fd_leak(self):
1352 """Test for the fork() failure fd leak reported in issue16327."""
1353 fd_directory = '/proc/%d/fd' % os.getpid()
1354 fds_before_popen = os.listdir(fd_directory)
1355 with self.assertRaises(PopenTestException):
1356 PopenExecuteChildRaises(
1357 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1358 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1359
1360 # NOTE: This test doesn't verify that the real _execute_child
1361 # does not close the file descriptors itself on the way out
1362 # during an exception. Code inspection has confirmed that.
1363
1364 fds_after_exception = os.listdir(fd_directory)
1365 self.assertEqual(fds_before_popen, fds_after_exception)
1366
Gregory P. Smitha3a6df32017-08-24 18:15:02 -07001367 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001368 def test_file_not_found_includes_filename(self):
1369 with self.assertRaises(FileNotFoundError) as c:
1370 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1371 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1372
Gregory P. Smitha3a6df32017-08-24 18:15:02 -07001373 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001374 def test_file_not_found_with_bad_cwd(self):
1375 with self.assertRaises(FileNotFoundError) as c:
1376 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1377 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1378
Gregory P. Smith6e730002015-04-14 16:14:25 -07001379
1380class RunFuncTestCase(BaseTestCase):
1381 def run_python(self, code, **kwargs):
1382 """Run Python code in a subprocess using subprocess.run"""
1383 argv = [sys.executable, "-c", code]
1384 return subprocess.run(argv, **kwargs)
1385
1386 def test_returncode(self):
1387 # call() function with sequence argument
1388 cp = self.run_python("import sys; sys.exit(47)")
1389 self.assertEqual(cp.returncode, 47)
1390 with self.assertRaises(subprocess.CalledProcessError):
1391 cp.check_returncode()
1392
1393 def test_check(self):
1394 with self.assertRaises(subprocess.CalledProcessError) as c:
1395 self.run_python("import sys; sys.exit(47)", check=True)
1396 self.assertEqual(c.exception.returncode, 47)
1397
1398 def test_check_zero(self):
1399 # check_returncode shouldn't raise when returncode is zero
1400 cp = self.run_python("import sys; sys.exit(0)", check=True)
1401 self.assertEqual(cp.returncode, 0)
1402
1403 def test_timeout(self):
1404 # run() function with timeout argument; we want to test that the child
1405 # process gets killed when the timeout expires. If the child isn't
1406 # killed, this call will deadlock since subprocess.run waits for the
1407 # child.
1408 with self.assertRaises(subprocess.TimeoutExpired):
1409 self.run_python("while True: pass", timeout=0.0001)
1410
1411 def test_capture_stdout(self):
1412 # capture stdout with zero return code
1413 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1414 self.assertIn(b'BDFL', cp.stdout)
1415
1416 def test_capture_stderr(self):
1417 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1418 stderr=subprocess.PIPE)
1419 self.assertIn(b'BDFL', cp.stderr)
1420
1421 def test_check_output_stdin_arg(self):
1422 # run() can be called with stdin set to a file
1423 tf = tempfile.TemporaryFile()
1424 self.addCleanup(tf.close)
1425 tf.write(b'pear')
1426 tf.seek(0)
1427 cp = self.run_python(
1428 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1429 stdin=tf, stdout=subprocess.PIPE)
1430 self.assertIn(b'PEAR', cp.stdout)
1431
1432 def test_check_output_input_arg(self):
1433 # check_output() can be called with input set to a string
1434 cp = self.run_python(
1435 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1436 input=b'pear', stdout=subprocess.PIPE)
1437 self.assertIn(b'PEAR', cp.stdout)
1438
1439 def test_check_output_stdin_with_input_arg(self):
1440 # run() refuses to accept 'stdin' with 'input'
1441 tf = tempfile.TemporaryFile()
1442 self.addCleanup(tf.close)
1443 tf.write(b'pear')
1444 tf.seek(0)
1445 with self.assertRaises(ValueError,
1446 msg="Expected ValueError when stdin and input args supplied.") as c:
1447 output = self.run_python("print('will not be run')",
1448 stdin=tf, input=b'hare')
1449 self.assertIn('stdin', c.exception.args[0])
1450 self.assertIn('input', c.exception.args[0])
1451
1452 def test_check_output_timeout(self):
1453 with self.assertRaises(subprocess.TimeoutExpired) as c:
1454 cp = self.run_python((
1455 "import sys, time\n"
1456 "sys.stdout.write('BDFL')\n"
1457 "sys.stdout.flush()\n"
1458 "time.sleep(3600)"),
1459 # Some heavily loaded buildbots (sparc Debian 3.x) require
1460 # this much time to start and print.
1461 timeout=3, stdout=subprocess.PIPE)
1462 self.assertEqual(c.exception.output, b'BDFL')
1463 # output is aliased to stdout
1464 self.assertEqual(c.exception.stdout, b'BDFL')
1465
1466 def test_run_kwargs(self):
1467 newenv = os.environ.copy()
1468 newenv["FRUIT"] = "banana"
1469 cp = self.run_python(('import sys, os;'
1470 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1471 env=newenv)
1472 self.assertEqual(cp.returncode, 33)
1473
Bo Baylesce0f33d2018-01-30 00:40:39 -06001474 def test_capture_output(self):
1475 cp = self.run_python(("import sys;"
1476 "sys.stdout.write('BDFL'); "
1477 "sys.stderr.write('FLUFL')"),
1478 capture_output=True)
1479 self.assertIn(b'BDFL', cp.stdout)
1480 self.assertIn(b'FLUFL', cp.stderr)
1481
1482 def test_stdout_with_capture_output_arg(self):
1483 # run() refuses to accept 'stdout' with 'capture_output'
1484 tf = tempfile.TemporaryFile()
1485 self.addCleanup(tf.close)
1486 with self.assertRaises(ValueError,
1487 msg=("Expected ValueError when stdout and capture_output "
1488 "args supplied.")) as c:
1489 output = self.run_python("print('will not be run')",
1490 capture_output=True, stdout=tf)
1491 self.assertIn('stdout', c.exception.args[0])
1492 self.assertIn('capture_output', c.exception.args[0])
1493
1494 def test_stderr_with_capture_output_arg(self):
1495 # run() refuses to accept 'stderr' with 'capture_output'
1496 tf = tempfile.TemporaryFile()
1497 self.addCleanup(tf.close)
1498 with self.assertRaises(ValueError,
1499 msg=("Expected ValueError when stderr and capture_output "
1500 "args supplied.")) as c:
1501 output = self.run_python("print('will not be run')",
1502 capture_output=True, stderr=tf)
1503 self.assertIn('stderr', c.exception.args[0])
1504 self.assertIn('capture_output', c.exception.args[0])
1505
Gregory P. Smith6e730002015-04-14 16:14:25 -07001506
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001507@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001508class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001509
Gregory P. Smith5591b022012-10-10 03:34:47 -07001510 def setUp(self):
1511 super().setUp()
1512 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1513
1514 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001515 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001516 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001517 except OSError as e:
1518 # This avoids hard coding the errno value or the OS perror()
1519 # string and instead capture the exception that we want to see
1520 # below for comparison.
1521 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001522 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001523 else:
Martin Pantereb995702016-07-28 01:11:04 +00001524 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001525 self._nonexistent_dir)
1526 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001527
Gregory P. Smith5591b022012-10-10 03:34:47 -07001528 def test_exception_cwd(self):
1529 """Test error in the child raised in the parent for a bad cwd."""
1530 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001531 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001532 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001533 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001534 except OSError as e:
1535 # Test that the child process chdir failure actually makes
1536 # it up to the parent process as the correct exception.
1537 self.assertEqual(desired_exception.errno, e.errno)
1538 self.assertEqual(desired_exception.strerror, e.strerror)
1539 else:
1540 self.fail("Expected OSError: %s" % desired_exception)
1541
Gregory P. Smith5591b022012-10-10 03:34:47 -07001542 def test_exception_bad_executable(self):
1543 """Test error in the child raised in the parent for a bad executable."""
1544 desired_exception = self._get_chdir_exception()
1545 try:
1546 p = subprocess.Popen([sys.executable, "-c", ""],
1547 executable=self._nonexistent_dir)
1548 except OSError as e:
1549 # Test that the child process exec failure actually makes
1550 # it up to the parent process as the correct exception.
1551 self.assertEqual(desired_exception.errno, e.errno)
1552 self.assertEqual(desired_exception.strerror, e.strerror)
1553 else:
1554 self.fail("Expected OSError: %s" % desired_exception)
1555
1556 def test_exception_bad_args_0(self):
1557 """Test error in the child raised in the parent for a bad args[0]."""
1558 desired_exception = self._get_chdir_exception()
1559 try:
1560 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1561 except OSError as e:
1562 # Test that the child process exec failure actually makes
1563 # it up to the parent process as the correct exception.
1564 self.assertEqual(desired_exception.errno, e.errno)
1565 self.assertEqual(desired_exception.strerror, e.strerror)
1566 else:
1567 self.fail("Expected OSError: %s" % desired_exception)
1568
Ammar Askar3fc499b2017-09-06 02:41:30 -04001569 # We mock the __del__ method for Popen in the next two tests
1570 # because it does cleanup based on the pid returned by fork_exec
1571 # along with issuing a resource warning if it still exists. Since
1572 # we don't actually spawn a process in these tests we can forego
1573 # the destructor. An alternative would be to set _child_created to
1574 # False before the destructor is called but there is no easy way
1575 # to do that
1576 class PopenNoDestructor(subprocess.Popen):
1577 def __del__(self):
1578 pass
1579
1580 @mock.patch("subprocess._posixsubprocess.fork_exec")
1581 def test_exception_errpipe_normal(self, fork_exec):
1582 """Test error passing done through errpipe_write in the good case"""
1583 def proper_error(*args):
1584 errpipe_write = args[13]
1585 # Write the hex for the error code EISDIR: 'is a directory'
1586 err_code = '{:x}'.format(errno.EISDIR).encode()
1587 os.write(errpipe_write, b"OSError:" + err_code + b":")
1588 return 0
1589
1590 fork_exec.side_effect = proper_error
1591
Victor Stinner11045c92017-10-05 06:32:53 -07001592 with mock.patch("subprocess.os.waitpid",
1593 side_effect=ChildProcessError):
1594 with self.assertRaises(IsADirectoryError):
1595 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001596
1597 @mock.patch("subprocess._posixsubprocess.fork_exec")
1598 def test_exception_errpipe_bad_data(self, fork_exec):
1599 """Test error passing done through errpipe_write where its not
1600 in the expected format"""
1601 error_data = b"\xFF\x00\xDE\xAD"
1602 def bad_error(*args):
1603 errpipe_write = args[13]
1604 # Anything can be in the pipe, no assumptions should
1605 # be made about its encoding, so we'll write some
1606 # arbitrary hex bytes to test it out
1607 os.write(errpipe_write, error_data)
1608 return 0
1609
1610 fork_exec.side_effect = bad_error
1611
Victor Stinner11045c92017-10-05 06:32:53 -07001612 with mock.patch("subprocess.os.waitpid",
1613 side_effect=ChildProcessError):
1614 with self.assertRaises(subprocess.SubprocessError) as e:
1615 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001616
1617 self.assertIn(repr(error_data), str(e.exception))
1618
1619
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001620 def test_restore_signals(self):
1621 # Code coverage for both values of restore_signals to make sure it
1622 # at least does not blow up.
1623 # A test for behavior would be complex. Contributions welcome.
1624 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1625 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1626
1627 def test_start_new_session(self):
1628 # For code coverage of calling setsid(). We don't care if we get an
1629 # EPERM error from it depending on the test execution environment, that
1630 # still indicates that it was called.
1631 try:
1632 output = subprocess.check_output(
1633 [sys.executable, "-c",
1634 "import os; print(os.getpgid(os.getpid()))"],
1635 start_new_session=True)
1636 except OSError as e:
1637 if e.errno != errno.EPERM:
1638 raise
1639 else:
1640 parent_pgid = os.getpgid(os.getpid())
1641 child_pgid = int(output)
1642 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001643
1644 def test_run_abort(self):
1645 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001646 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001647 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001648 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001649 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001650 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001651
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001652 def test_CalledProcessError_str_signal(self):
1653 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1654 error_string = str(err)
1655 # We're relying on the repr() of the signal.Signals intenum to provide
1656 # the word signal, the signal name and the numeric value.
1657 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001658 # We're not being specific about the signal name as some signals have
1659 # multiple names and which name is revealed can vary.
1660 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001661 self.assertIn(str(signal.SIGABRT), error_string)
1662
1663 def test_CalledProcessError_str_unknown_signal(self):
1664 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1665 error_string = str(err)
1666 self.assertIn("unknown signal 9876543.", error_string)
1667
1668 def test_CalledProcessError_str_non_zero(self):
1669 err = subprocess.CalledProcessError(2, "fake cmd")
1670 error_string = str(err)
1671 self.assertIn("non-zero exit status 2.", error_string)
1672
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001673 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001674 # DISCLAIMER: Setting environment variables is *not* a good use
1675 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001676 p = subprocess.Popen([sys.executable, "-c",
1677 'import sys,os;'
1678 'sys.stdout.write(os.getenv("FRUIT"))'],
1679 stdout=subprocess.PIPE,
1680 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001681 with p:
1682 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001683
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001684 def test_preexec_exception(self):
1685 def raise_it():
1686 raise ValueError("What if two swallows carried a coconut?")
1687 try:
1688 p = subprocess.Popen([sys.executable, "-c", ""],
1689 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001690 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001691 self.assertTrue(
1692 subprocess._posixsubprocess,
1693 "Expected a ValueError from the preexec_fn")
1694 except ValueError as e:
1695 self.assertIn("coconut", e.args[0])
1696 else:
1697 self.fail("Exception raised by preexec_fn did not make it "
1698 "to the parent process.")
1699
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001700 class _TestExecuteChildPopen(subprocess.Popen):
1701 """Used to test behavior at the end of _execute_child."""
1702 def __init__(self, testcase, *args, **kwargs):
1703 self._testcase = testcase
1704 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001705
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001706 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001707 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001708 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001709 finally:
1710 # Open a bunch of file descriptors and verify that
1711 # none of them are the same as the ones the Popen
1712 # instance is using for stdin/stdout/stderr.
1713 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1714 for _ in range(8)]
1715 try:
1716 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001717 self._testcase.assertNotIn(
1718 fd, (self.stdin.fileno(), self.stdout.fileno(),
1719 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001720 msg="At least one fd was closed early.")
1721 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001722 for fd in devzero_fds:
1723 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001724
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001725 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1726 def test_preexec_errpipe_does_not_double_close_pipes(self):
1727 """Issue16140: Don't double close pipes on preexec error."""
1728
1729 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001730 raise subprocess.SubprocessError(
1731 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001732
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001733 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001734 self._TestExecuteChildPopen(
1735 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001736 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1737 stderr=subprocess.PIPE, preexec_fn=raise_it)
1738
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001739 def test_preexec_gc_module_failure(self):
1740 # This tests the code that disables garbage collection if the child
1741 # process will execute any Python.
1742 def raise_runtime_error():
1743 raise RuntimeError("this shouldn't escape")
1744 enabled = gc.isenabled()
1745 orig_gc_disable = gc.disable
1746 orig_gc_isenabled = gc.isenabled
1747 try:
1748 gc.disable()
1749 self.assertFalse(gc.isenabled())
1750 subprocess.call([sys.executable, '-c', ''],
1751 preexec_fn=lambda: None)
1752 self.assertFalse(gc.isenabled(),
1753 "Popen enabled gc when it shouldn't.")
1754
1755 gc.enable()
1756 self.assertTrue(gc.isenabled())
1757 subprocess.call([sys.executable, '-c', ''],
1758 preexec_fn=lambda: None)
1759 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1760
1761 gc.disable = raise_runtime_error
1762 self.assertRaises(RuntimeError, subprocess.Popen,
1763 [sys.executable, '-c', ''],
1764 preexec_fn=lambda: None)
1765
1766 del gc.isenabled # force an AttributeError
1767 self.assertRaises(AttributeError, subprocess.Popen,
1768 [sys.executable, '-c', ''],
1769 preexec_fn=lambda: None)
1770 finally:
1771 gc.disable = orig_gc_disable
1772 gc.isenabled = orig_gc_isenabled
1773 if not enabled:
1774 gc.disable()
1775
Martin Panterf7fdbda2015-12-05 09:51:52 +00001776 @unittest.skipIf(
1777 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001778 def test_preexec_fork_failure(self):
1779 # The internal code did not preserve the previous exception when
1780 # re-enabling garbage collection
1781 try:
1782 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1783 except ImportError as err:
1784 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1785 limits = getrlimit(RLIMIT_NPROC)
1786 [_, hard] = limits
1787 setrlimit(RLIMIT_NPROC, (0, hard))
1788 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001789 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001790 subprocess.call([sys.executable, '-c', ''],
1791 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001792 except BlockingIOError:
1793 # Forking should raise EAGAIN, translated to BlockingIOError
1794 pass
1795 else:
1796 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001797
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001798 def test_args_string(self):
1799 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001800 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001801 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001802 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001803 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001804 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1805 sys.executable)
1806 os.chmod(fname, 0o700)
1807 p = subprocess.Popen(fname)
1808 p.wait()
1809 os.remove(fname)
1810 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001811
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001812 def test_invalid_args(self):
1813 # invalid arguments should raise ValueError
1814 self.assertRaises(ValueError, subprocess.call,
1815 [sys.executable, "-c",
1816 "import sys; sys.exit(47)"],
1817 startupinfo=47)
1818 self.assertRaises(ValueError, subprocess.call,
1819 [sys.executable, "-c",
1820 "import sys; sys.exit(47)"],
1821 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001822
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001823 def test_shell_sequence(self):
1824 # Run command through the shell (sequence)
1825 newenv = os.environ.copy()
1826 newenv["FRUIT"] = "apple"
1827 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1828 stdout=subprocess.PIPE,
1829 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001830 with p:
1831 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001832
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001833 def test_shell_string(self):
1834 # Run command through the shell (string)
1835 newenv = os.environ.copy()
1836 newenv["FRUIT"] = "apple"
1837 p = subprocess.Popen("echo $FRUIT", shell=1,
1838 stdout=subprocess.PIPE,
1839 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001840 with p:
1841 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001842
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001843 def test_call_string(self):
1844 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001845 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001846 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001847 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001848 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001849 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1850 sys.executable)
1851 os.chmod(fname, 0o700)
1852 rc = subprocess.call(fname)
1853 os.remove(fname)
1854 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001855
Stefan Krah9542cc62010-07-19 14:20:53 +00001856 def test_specific_shell(self):
1857 # Issue #9265: Incorrect name passed as arg[0].
1858 shells = []
1859 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1860 for name in ['bash', 'ksh']:
1861 sh = os.path.join(prefix, name)
1862 if os.path.isfile(sh):
1863 shells.append(sh)
1864 if not shells: # Will probably work for any shell but csh.
1865 self.skipTest("bash or ksh required for this test")
1866 sh = '/bin/sh'
1867 if os.path.isfile(sh) and not os.path.islink(sh):
1868 # Test will fail if /bin/sh is a symlink to csh.
1869 shells.append(sh)
1870 for sh in shells:
1871 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1872 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001873 with p:
1874 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001875
Florent Xicluna4886d242010-03-08 13:27:26 +00001876 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001877 # Do not inherit file handles from the parent.
1878 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001879 # Also set the SIGINT handler to the default to make sure it's not
1880 # being ignored (some tests rely on that.)
1881 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1882 try:
1883 p = subprocess.Popen([sys.executable, "-c", """if 1:
1884 import sys, time
1885 sys.stdout.write('x\\n')
1886 sys.stdout.flush()
1887 time.sleep(30)
1888 """],
1889 close_fds=True,
1890 stdin=subprocess.PIPE,
1891 stdout=subprocess.PIPE,
1892 stderr=subprocess.PIPE)
1893 finally:
1894 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001895 # Wait for the interpreter to be completely initialized before
1896 # sending any signal.
1897 p.stdout.read(1)
1898 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001899 return p
1900
Charles-François Natali53221e32013-01-12 16:52:20 +01001901 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1902 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001903 def _kill_dead_process(self, method, *args):
1904 # Do not inherit file handles from the parent.
1905 # It should fix failures on some platforms.
1906 p = subprocess.Popen([sys.executable, "-c", """if 1:
1907 import sys, time
1908 sys.stdout.write('x\\n')
1909 sys.stdout.flush()
1910 """],
1911 close_fds=True,
1912 stdin=subprocess.PIPE,
1913 stdout=subprocess.PIPE,
1914 stderr=subprocess.PIPE)
1915 # Wait for the interpreter to be completely initialized before
1916 # sending any signal.
1917 p.stdout.read(1)
1918 # The process should end after this
1919 time.sleep(1)
1920 # This shouldn't raise even though the child is now dead
1921 getattr(p, method)(*args)
1922 p.communicate()
1923
Florent Xicluna4886d242010-03-08 13:27:26 +00001924 def test_send_signal(self):
1925 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001926 _, stderr = p.communicate()
1927 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001928 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001929
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001930 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001931 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001932 _, stderr = p.communicate()
1933 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001934 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001935
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001936 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001937 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001938 _, stderr = p.communicate()
1939 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001940 self.assertEqual(p.wait(), -signal.SIGTERM)
1941
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001942 def test_send_signal_dead(self):
1943 # Sending a signal to a dead process
1944 self._kill_dead_process('send_signal', signal.SIGINT)
1945
1946 def test_kill_dead(self):
1947 # Killing a dead process
1948 self._kill_dead_process('kill')
1949
1950 def test_terminate_dead(self):
1951 # Terminating a dead process
1952 self._kill_dead_process('terminate')
1953
Victor Stinnerdaf45552013-08-28 00:53:59 +02001954 def _save_fds(self, save_fds):
1955 fds = []
1956 for fd in save_fds:
1957 inheritable = os.get_inheritable(fd)
1958 saved = os.dup(fd)
1959 fds.append((fd, saved, inheritable))
1960 return fds
1961
1962 def _restore_fds(self, fds):
1963 for fd, saved, inheritable in fds:
1964 os.dup2(saved, fd, inheritable=inheritable)
1965 os.close(saved)
1966
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001967 def check_close_std_fds(self, fds):
1968 # Issue #9905: test that subprocess pipes still work properly with
1969 # some standard fds closed
1970 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001971 saved_fds = self._save_fds(fds)
1972 for fd, saved, inheritable in saved_fds:
1973 if fd == 0:
1974 stdin = saved
1975 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001976 try:
1977 for fd in fds:
1978 os.close(fd)
1979 out, err = subprocess.Popen([sys.executable, "-c",
1980 'import sys;'
1981 'sys.stdout.write("apple");'
1982 'sys.stdout.flush();'
1983 'sys.stderr.write("orange")'],
1984 stdin=stdin,
1985 stdout=subprocess.PIPE,
1986 stderr=subprocess.PIPE).communicate()
1987 err = support.strip_python_stderr(err)
1988 self.assertEqual((out, err), (b'apple', b'orange'))
1989 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001990 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001991
1992 def test_close_fd_0(self):
1993 self.check_close_std_fds([0])
1994
1995 def test_close_fd_1(self):
1996 self.check_close_std_fds([1])
1997
1998 def test_close_fd_2(self):
1999 self.check_close_std_fds([2])
2000
2001 def test_close_fds_0_1(self):
2002 self.check_close_std_fds([0, 1])
2003
2004 def test_close_fds_0_2(self):
2005 self.check_close_std_fds([0, 2])
2006
2007 def test_close_fds_1_2(self):
2008 self.check_close_std_fds([1, 2])
2009
2010 def test_close_fds_0_1_2(self):
2011 # Issue #10806: test that subprocess pipes still work properly with
2012 # all standard fds closed.
2013 self.check_close_std_fds([0, 1, 2])
2014
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002015 def test_small_errpipe_write_fd(self):
2016 """Issue #15798: Popen should work when stdio fds are available."""
2017 new_stdin = os.dup(0)
2018 new_stdout = os.dup(1)
2019 try:
2020 os.close(0)
2021 os.close(1)
2022
2023 # Side test: if errpipe_write fails to have its CLOEXEC
2024 # flag set this should cause the parent to think the exec
2025 # failed. Extremely unlikely: everyone supports CLOEXEC.
2026 subprocess.Popen([
2027 sys.executable, "-c",
2028 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2029 finally:
2030 # Restore original stdin and stdout
2031 os.dup2(new_stdin, 0)
2032 os.dup2(new_stdout, 1)
2033 os.close(new_stdin)
2034 os.close(new_stdout)
2035
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002036 def test_remapping_std_fds(self):
2037 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002038 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002039 try:
2040 temp_fds = [fd for fd, fname in temps]
2041
2042 # unlink the files -- we won't need to reopen them
2043 for fd, fname in temps:
2044 os.unlink(fname)
2045
2046 # write some data to what will become stdin, and rewind
2047 os.write(temp_fds[1], b"STDIN")
2048 os.lseek(temp_fds[1], 0, 0)
2049
2050 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002051 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002052 try:
2053 # duplicate the file objects over the standard fd's
2054 for fd, temp_fd in enumerate(temp_fds):
2055 os.dup2(temp_fd, fd)
2056
2057 # now use those files in the "wrong" order, so that subprocess
2058 # has to rearrange them in the child
2059 p = subprocess.Popen([sys.executable, "-c",
2060 'import sys; got = sys.stdin.read();'
2061 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2062 stdin=temp_fds[1],
2063 stdout=temp_fds[2],
2064 stderr=temp_fds[0])
2065 p.wait()
2066 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002067 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002068
2069 for fd in temp_fds:
2070 os.lseek(fd, 0, 0)
2071
2072 out = os.read(temp_fds[2], 1024)
2073 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2074 self.assertEqual(out, b"got STDIN")
2075 self.assertEqual(err, b"err")
2076
2077 finally:
2078 for fd in temp_fds:
2079 os.close(fd)
2080
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002081 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2082 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002083 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002084 temp_fds = [fd for fd, fname in temps]
2085 try:
2086 # unlink the files -- we won't need to reopen them
2087 for fd, fname in temps:
2088 os.unlink(fname)
2089
2090 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002091 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002092 try:
2093 # duplicate the temp files over the standard fd's 0, 1, 2
2094 for fd, temp_fd in enumerate(temp_fds):
2095 os.dup2(temp_fd, fd)
2096
2097 # write some data to what will become stdin, and rewind
2098 os.write(stdin_no, b"STDIN")
2099 os.lseek(stdin_no, 0, 0)
2100
2101 # now use those files in the given order, so that subprocess
2102 # has to rearrange them in the child
2103 p = subprocess.Popen([sys.executable, "-c",
2104 'import sys; got = sys.stdin.read();'
2105 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2106 stdin=stdin_no,
2107 stdout=stdout_no,
2108 stderr=stderr_no)
2109 p.wait()
2110
2111 for fd in temp_fds:
2112 os.lseek(fd, 0, 0)
2113
2114 out = os.read(stdout_no, 1024)
2115 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2116 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002117 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002118
2119 self.assertEqual(out, b"got STDIN")
2120 self.assertEqual(err, b"err")
2121
2122 finally:
2123 for fd in temp_fds:
2124 os.close(fd)
2125
2126 # When duping fds, if there arises a situation where one of the fds is
2127 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2128 # This tests all combinations of this.
2129 def test_swap_fds(self):
2130 self.check_swap_fds(0, 1, 2)
2131 self.check_swap_fds(0, 2, 1)
2132 self.check_swap_fds(1, 0, 2)
2133 self.check_swap_fds(1, 2, 0)
2134 self.check_swap_fds(2, 0, 1)
2135 self.check_swap_fds(2, 1, 0)
2136
Victor Stinner13bb71c2010-04-23 21:41:56 +00002137 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002138 def prepare():
2139 raise ValueError("surrogate:\uDCff")
2140
2141 try:
2142 subprocess.call(
2143 [sys.executable, "-c", "pass"],
2144 preexec_fn=prepare)
2145 except ValueError as err:
2146 # Pure Python implementations keeps the message
2147 self.assertIsNone(subprocess._posixsubprocess)
2148 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002149 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002150 # _posixsubprocess uses a default message
2151 self.assertIsNotNone(subprocess._posixsubprocess)
2152 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2153 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002154 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002155
Victor Stinner13bb71c2010-04-23 21:41:56 +00002156 def test_undecodable_env(self):
2157 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002158 encoded_value = value.encode("ascii", "surrogateescape")
2159
Victor Stinner13bb71c2010-04-23 21:41:56 +00002160 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002161 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002162 env = os.environ.copy()
2163 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002164 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00002165 # surrogate-escaping of \xFF in the child process; otherwise it can
2166 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00002167 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01002168 if sys.platform.startswith("aix"):
2169 # On AIX, the C locale uses the Latin1 encoding
2170 decoded_value = encoded_value.decode("latin1", "surrogateescape")
2171 else:
2172 # On other UNIXes, the C locale uses the ASCII encoding
2173 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002174 stdout = subprocess.check_output(
2175 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002176 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002177 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002178 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002179
2180 # test bytes
2181 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002182 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002183 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002184 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002185 stdout = subprocess.check_output(
2186 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002187 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002188 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002189 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002190
Victor Stinnerb745a742010-05-18 17:17:23 +00002191 def test_bytes_program(self):
2192 abs_program = os.fsencode(sys.executable)
2193 path, program = os.path.split(sys.executable)
2194 program = os.fsencode(program)
2195
2196 # absolute bytes path
2197 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002198 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002199
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002200 # absolute bytes path as a string
2201 cmd = b"'" + abs_program + b"' -c pass"
2202 exitcode = subprocess.call(cmd, shell=True)
2203 self.assertEqual(exitcode, 0)
2204
Victor Stinnerb745a742010-05-18 17:17:23 +00002205 # bytes program, unicode PATH
2206 env = os.environ.copy()
2207 env["PATH"] = path
2208 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002209 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002210
2211 # bytes program, bytes PATH
2212 envb = os.environb.copy()
2213 envb[b"PATH"] = os.fsencode(path)
2214 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002215 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002216
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002217 def test_pipe_cloexec(self):
2218 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2219 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2220
2221 p1 = subprocess.Popen([sys.executable, sleeper],
2222 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2223 stderr=subprocess.PIPE, close_fds=False)
2224
2225 self.addCleanup(p1.communicate, b'')
2226
2227 p2 = subprocess.Popen([sys.executable, fd_status],
2228 stdout=subprocess.PIPE, close_fds=False)
2229
2230 output, error = p2.communicate()
2231 result_fds = set(map(int, output.split(b',')))
2232 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2233 p1.stderr.fileno()])
2234
2235 self.assertFalse(result_fds & unwanted_fds,
2236 "Expected no fds from %r to be open in child, "
2237 "found %r" %
2238 (unwanted_fds, result_fds & unwanted_fds))
2239
2240 def test_pipe_cloexec_real_tools(self):
2241 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2242 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2243
2244 subdata = b'zxcvbn'
2245 data = subdata * 4 + b'\n'
2246
2247 p1 = subprocess.Popen([sys.executable, qcat],
2248 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2249 close_fds=False)
2250
2251 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2252 stdin=p1.stdout, stdout=subprocess.PIPE,
2253 close_fds=False)
2254
2255 self.addCleanup(p1.wait)
2256 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002257 def kill_p1():
2258 try:
2259 p1.terminate()
2260 except ProcessLookupError:
2261 pass
2262 def kill_p2():
2263 try:
2264 p2.terminate()
2265 except ProcessLookupError:
2266 pass
2267 self.addCleanup(kill_p1)
2268 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002269
2270 p1.stdin.write(data)
2271 p1.stdin.close()
2272
2273 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2274
2275 self.assertTrue(readfiles, "The child hung")
2276 self.assertEqual(p2.stdout.read(), data)
2277
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002278 p1.stdout.close()
2279 p2.stdout.close()
2280
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002281 def test_close_fds(self):
2282 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2283
2284 fds = os.pipe()
2285 self.addCleanup(os.close, fds[0])
2286 self.addCleanup(os.close, fds[1])
2287
2288 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002289 # add a bunch more fds
2290 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002291 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002292 self.addCleanup(os.close, fd)
2293 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002294
Victor Stinnerdaf45552013-08-28 00:53:59 +02002295 for fd in open_fds:
2296 os.set_inheritable(fd, True)
2297
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002298 p = subprocess.Popen([sys.executable, fd_status],
2299 stdout=subprocess.PIPE, close_fds=False)
2300 output, ignored = p.communicate()
2301 remaining_fds = set(map(int, output.split(b',')))
2302
2303 self.assertEqual(remaining_fds & open_fds, open_fds,
2304 "Some fds were closed")
2305
2306 p = subprocess.Popen([sys.executable, fd_status],
2307 stdout=subprocess.PIPE, close_fds=True)
2308 output, ignored = p.communicate()
2309 remaining_fds = set(map(int, output.split(b',')))
2310
2311 self.assertFalse(remaining_fds & open_fds,
2312 "Some fds were left open")
2313 self.assertIn(1, remaining_fds, "Subprocess failed")
2314
Gregory P. Smith8facece2012-01-21 14:01:08 -08002315 # Keep some of the fd's we opened open in the subprocess.
2316 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2317 fds_to_keep = set(open_fds.pop() for _ in range(8))
2318 p = subprocess.Popen([sys.executable, fd_status],
2319 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002320 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002321 output, ignored = p.communicate()
2322 remaining_fds = set(map(int, output.split(b',')))
2323
izbyshev2d8f0632017-12-19 03:26:49 +07002324 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002325 "Some fds not in pass_fds were left open")
2326 self.assertIn(1, remaining_fds, "Subprocess failed")
2327
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002328
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002329 @unittest.skipIf(sys.platform.startswith("freebsd") and
2330 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2331 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002332 def test_close_fds_when_max_fd_is_lowered(self):
2333 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2334 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2335
Gregory P. Smith634aa682014-06-15 17:51:04 -07002336 # This launches the meat of the test in a child process to
2337 # avoid messing with the larger unittest processes maximum
2338 # number of file descriptors.
2339 # This process launches:
2340 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2341 # a bunch of high open fds above the new lower rlimit.
2342 # Those are reported via stdout before launching a new
2343 # process with close_fds=False to run the actual test:
2344 # +--> The TEST: This one launches a fd_status.py
2345 # subprocess with close_fds=True so we can find out if
2346 # any of the fds above the lowered rlimit are still open.
2347 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2348 '''
2349 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002350 open_fds = set()
2351 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002352 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002353 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002354 open_fds.add(fd)
2355
2356 # Leave a two pairs of low ones available for use by the
2357 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002358 # We also leave 10 more open as some Python buildbots run into
2359 # "too many open files" errors during the test if we do not.
2360 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002361 os.close(fd)
2362 open_fds.remove(fd)
2363
2364 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002365 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002366 os.set_inheritable(fd, True)
2367
2368 max_fd_open = max(open_fds)
2369
Gregory P. Smith634aa682014-06-15 17:51:04 -07002370 # Communicate the open_fds to the parent unittest.TestCase process.
2371 print(','.join(map(str, sorted(open_fds))))
2372 sys.stdout.flush()
2373
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002374 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2375 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002376 # 29 is lower than the highest fds we are leaving open.
2377 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002378 # Launch a new Python interpreter with our low fd rlim_cur that
2379 # inherits open fds above that limit. It then uses subprocess
2380 # with close_fds=True to get a report of open fds in the child.
2381 # An explicit list of fds to check is passed to fd_status.py as
2382 # letting fd_status rely on its default logic would miss the
2383 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002384 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002385 [sys.executable, '-c',
2386 textwrap.dedent("""
2387 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002388 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002389 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002390 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002391 """.format(max_fd=max_fd_open+1))],
2392 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002393 finally:
2394 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002395 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002396
2397 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002398 output_lines = output.splitlines()
2399 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002400 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002401 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2402 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002403
Gregory P. Smith634aa682014-06-15 17:51:04 -07002404 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002405 msg="Some fds were left open.")
2406
2407
Victor Stinner88701e22011-06-01 13:13:04 +02002408 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2409 # descriptor of a pipe closed in the parent process is valid in the
2410 # child process according to fstat(), but the mode of the file
2411 # descriptor is invalid, and read or write raise an error.
2412 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002413 def test_pass_fds(self):
2414 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2415
2416 open_fds = set()
2417
2418 for x in range(5):
2419 fds = os.pipe()
2420 self.addCleanup(os.close, fds[0])
2421 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002422 os.set_inheritable(fds[0], True)
2423 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002424 open_fds.update(fds)
2425
2426 for fd in open_fds:
2427 p = subprocess.Popen([sys.executable, fd_status],
2428 stdout=subprocess.PIPE, close_fds=True,
2429 pass_fds=(fd, ))
2430 output, ignored = p.communicate()
2431
2432 remaining_fds = set(map(int, output.split(b',')))
2433 to_be_closed = open_fds - {fd}
2434
2435 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2436 self.assertFalse(remaining_fds & to_be_closed,
2437 "fd to be closed passed")
2438
2439 # pass_fds overrides close_fds with a warning.
2440 with self.assertWarns(RuntimeWarning) as context:
2441 self.assertFalse(subprocess.call(
2442 [sys.executable, "-c", "import sys; sys.exit(0)"],
2443 close_fds=False, pass_fds=(fd, )))
2444 self.assertIn('overriding close_fds', str(context.warning))
2445
Victor Stinnerdaf45552013-08-28 00:53:59 +02002446 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002447 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002448
2449 inheritable, non_inheritable = os.pipe()
2450 self.addCleanup(os.close, inheritable)
2451 self.addCleanup(os.close, non_inheritable)
2452 os.set_inheritable(inheritable, True)
2453 os.set_inheritable(non_inheritable, False)
2454 pass_fds = (inheritable, non_inheritable)
2455 args = [sys.executable, script]
2456 args += list(map(str, pass_fds))
2457
2458 p = subprocess.Popen(args,
2459 stdout=subprocess.PIPE, close_fds=True,
2460 pass_fds=pass_fds)
2461 output, ignored = p.communicate()
2462 fds = set(map(int, output.split(b',')))
2463
2464 # the inheritable file descriptor must be inherited, so its inheritable
2465 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002466 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002467
2468 # inheritable flag must not be changed in the parent process
2469 self.assertEqual(os.get_inheritable(inheritable), True)
2470 self.assertEqual(os.get_inheritable(non_inheritable), False)
2471
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002472 def test_stdout_stdin_are_single_inout_fd(self):
2473 with io.open(os.devnull, "r+") as inout:
2474 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2475 stdout=inout, stdin=inout)
2476 p.wait()
2477
2478 def test_stdout_stderr_are_single_inout_fd(self):
2479 with io.open(os.devnull, "r+") as inout:
2480 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2481 stdout=inout, stderr=inout)
2482 p.wait()
2483
2484 def test_stderr_stdin_are_single_inout_fd(self):
2485 with io.open(os.devnull, "r+") as inout:
2486 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2487 stderr=inout, stdin=inout)
2488 p.wait()
2489
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002490 def test_wait_when_sigchild_ignored(self):
2491 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2492 sigchild_ignore = support.findfile("sigchild_ignore.py",
2493 subdir="subprocessdata")
2494 p = subprocess.Popen([sys.executable, sigchild_ignore],
2495 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2496 stdout, stderr = p.communicate()
2497 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002498 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002499 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002500
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002501 def test_select_unbuffered(self):
2502 # Issue #11459: bufsize=0 should really set the pipes as
2503 # unbuffered (and therefore let select() work properly).
2504 select = support.import_module("select")
2505 p = subprocess.Popen([sys.executable, "-c",
2506 'import sys;'
2507 'sys.stdout.write("apple")'],
2508 stdout=subprocess.PIPE,
2509 bufsize=0)
2510 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002511 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002512 try:
2513 self.assertEqual(f.read(4), b"appl")
2514 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2515 finally:
2516 p.wait()
2517
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002518 def test_zombie_fast_process_del(self):
2519 # Issue #12650: on Unix, if Popen.__del__() was called before the
2520 # process exited, it wouldn't be added to subprocess._active, and would
2521 # remain a zombie.
2522 # spawn a Popen, and delete its reference before it exits
2523 p = subprocess.Popen([sys.executable, "-c",
2524 'import sys, time;'
2525 'time.sleep(0.2)'],
2526 stdout=subprocess.PIPE,
2527 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002528 self.addCleanup(p.stdout.close)
2529 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002530 ident = id(p)
2531 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002532 with support.check_warnings(('', ResourceWarning)):
2533 p = None
2534
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002535 # check that p is in the active processes list
2536 self.assertIn(ident, [id(o) for o in subprocess._active])
2537
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002538 def test_leak_fast_process_del_killed(self):
2539 # Issue #12650: on Unix, if Popen.__del__() was called before the
2540 # process exited, and the process got killed by a signal, it would never
2541 # be removed from subprocess._active, which triggered a FD and memory
2542 # leak.
2543 # spawn a Popen, delete its reference and kill it
2544 p = subprocess.Popen([sys.executable, "-c",
2545 'import time;'
2546 'time.sleep(3)'],
2547 stdout=subprocess.PIPE,
2548 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002549 self.addCleanup(p.stdout.close)
2550 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002551 ident = id(p)
2552 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002553 with support.check_warnings(('', ResourceWarning)):
2554 p = None
2555
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002556 os.kill(pid, signal.SIGKILL)
2557 # check that p is in the active processes list
2558 self.assertIn(ident, [id(o) for o in subprocess._active])
2559
2560 # let some time for the process to exit, and create a new Popen: this
2561 # should trigger the wait() of p
2562 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002563 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002564 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002565 stdout=subprocess.PIPE,
2566 stderr=subprocess.PIPE) as proc:
2567 pass
2568 # p should have been wait()ed on, and removed from the _active list
2569 self.assertRaises(OSError, os.waitpid, pid, 0)
2570 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2571
Charles-François Natali249cdc32013-08-25 18:24:45 +02002572 def test_close_fds_after_preexec(self):
2573 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2574
2575 # this FD is used as dup2() target by preexec_fn, and should be closed
2576 # in the child process
2577 fd = os.dup(1)
2578 self.addCleanup(os.close, fd)
2579
2580 p = subprocess.Popen([sys.executable, fd_status],
2581 stdout=subprocess.PIPE, close_fds=True,
2582 preexec_fn=lambda: os.dup2(1, fd))
2583 output, ignored = p.communicate()
2584
2585 remaining_fds = set(map(int, output.split(b',')))
2586
2587 self.assertNotIn(fd, remaining_fds)
2588
Victor Stinner8f437aa2014-10-05 17:25:19 +02002589 @support.cpython_only
2590 def test_fork_exec(self):
2591 # Issue #22290: fork_exec() must not crash on memory allocation failure
2592 # or other errors
2593 import _posixsubprocess
2594 gc_enabled = gc.isenabled()
2595 try:
2596 # Use a preexec function and enable the garbage collector
2597 # to force fork_exec() to re-enable the garbage collector
2598 # on error.
2599 func = lambda: None
2600 gc.enable()
2601
Victor Stinner8f437aa2014-10-05 17:25:19 +02002602 for args, exe_list, cwd, env_list in (
2603 (123, [b"exe"], None, [b"env"]),
2604 ([b"arg"], 123, None, [b"env"]),
2605 ([b"arg"], [b"exe"], 123, [b"env"]),
2606 ([b"arg"], [b"exe"], None, 123),
2607 ):
2608 with self.assertRaises(TypeError):
2609 _posixsubprocess.fork_exec(
2610 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002611 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002612 -1, -1, -1, -1,
2613 1, 2, 3, 4,
2614 True, True, func)
2615 finally:
2616 if not gc_enabled:
2617 gc.disable()
2618
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002619 @support.cpython_only
2620 def test_fork_exec_sorted_fd_sanity_check(self):
2621 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2622 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002623 class BadInt:
2624 first = True
2625 def __init__(self, value):
2626 self.value = value
2627 def __int__(self):
2628 if self.first:
2629 self.first = False
2630 return self.value
2631 raise ValueError
2632
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002633 gc_enabled = gc.isenabled()
2634 try:
2635 gc.enable()
2636
2637 for fds_to_keep in (
2638 (-1, 2, 3, 4, 5), # Negative number.
2639 ('str', 4), # Not an int.
2640 (18, 23, 42, 2**63), # Out of range.
2641 (5, 4), # Not sorted.
2642 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002643 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002644 ):
2645 with self.assertRaises(
2646 ValueError,
2647 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2648 _posixsubprocess.fork_exec(
2649 [b"false"], [b"false"],
2650 True, fds_to_keep, None, [b"env"],
2651 -1, -1, -1, -1,
2652 1, 2, 3, 4,
2653 True, True, None)
2654 self.assertIn('fds_to_keep', str(c.exception))
2655 finally:
2656 if not gc_enabled:
2657 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002658
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002659 def test_communicate_BrokenPipeError_stdin_close(self):
2660 # By not setting stdout or stderr or a timeout we force the fast path
2661 # that just calls _stdin_write() internally due to our mock.
2662 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2663 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2664 mock_proc_stdin.close.side_effect = BrokenPipeError
2665 proc.communicate() # Should swallow BrokenPipeError from close.
2666 mock_proc_stdin.close.assert_called_with()
2667
2668 def test_communicate_BrokenPipeError_stdin_write(self):
2669 # By not setting stdout or stderr or a timeout we force the fast path
2670 # that just calls _stdin_write() internally due to our mock.
2671 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2672 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2673 mock_proc_stdin.write.side_effect = BrokenPipeError
2674 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2675 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2676 mock_proc_stdin.close.assert_called_once_with()
2677
2678 def test_communicate_BrokenPipeError_stdin_flush(self):
2679 # Setting stdin and stdout forces the ._communicate() code path.
2680 # python -h exits faster than python -c pass (but spams stdout).
2681 proc = subprocess.Popen([sys.executable, '-h'],
2682 stdin=subprocess.PIPE,
2683 stdout=subprocess.PIPE)
2684 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2685 open(os.devnull, 'wb') as dev_null:
2686 mock_proc_stdin.flush.side_effect = BrokenPipeError
2687 # because _communicate registers a selector using proc.stdin...
2688 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2689 # _communicate() should swallow BrokenPipeError from flush.
2690 proc.communicate(b'stuff')
2691 mock_proc_stdin.flush.assert_called_once_with()
2692
2693 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2694 # Setting stdin and stdout forces the ._communicate() code path.
2695 # python -h exits faster than python -c pass (but spams stdout).
2696 proc = subprocess.Popen([sys.executable, '-h'],
2697 stdin=subprocess.PIPE,
2698 stdout=subprocess.PIPE)
2699 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2700 mock_proc_stdin.close.side_effect = BrokenPipeError
2701 # _communicate() should swallow BrokenPipeError from close.
2702 proc.communicate(timeout=999)
2703 mock_proc_stdin.close.assert_called_once_with()
2704
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002705 @unittest.skipUnless(_testcapi is not None
2706 and hasattr(_testcapi, 'W_STOPCODE'),
2707 'need _testcapi.W_STOPCODE')
2708 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002709 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002710 args = [sys.executable, '-c', 'pass']
2711 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002712
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002713 # Wait until the real process completes to avoid zombie process
2714 pid = proc.pid
2715 pid, status = os.waitpid(pid, 0)
2716 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002717
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002718 status = _testcapi.W_STOPCODE(3)
2719 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
2720 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02002721
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002722 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002723
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002724
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002725@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002726class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002727
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002728 def test_startupinfo(self):
2729 # startupinfo argument
2730 # We uses hardcoded constants, because we do not want to
2731 # depend on win32all.
2732 STARTF_USESHOWWINDOW = 1
2733 SW_MAXIMIZE = 3
2734 startupinfo = subprocess.STARTUPINFO()
2735 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2736 startupinfo.wShowWindow = SW_MAXIMIZE
2737 # Since Python is a console process, it won't be affected
2738 # by wShowWindow, but the argument should be silently
2739 # ignored
2740 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002741 startupinfo=startupinfo)
2742
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302743 def test_startupinfo_keywords(self):
2744 # startupinfo argument
2745 # We use hardcoded constants, because we do not want to
2746 # depend on win32all.
2747 STARTF_USERSHOWWINDOW = 1
2748 SW_MAXIMIZE = 3
2749 startupinfo = subprocess.STARTUPINFO(
2750 dwFlags=STARTF_USERSHOWWINDOW,
2751 wShowWindow=SW_MAXIMIZE
2752 )
2753 # Since Python is a console process, it won't be affected
2754 # by wShowWindow, but the argument should be silently
2755 # ignored
2756 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2757 startupinfo=startupinfo)
2758
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002759 def test_creationflags(self):
2760 # creationflags argument
2761 CREATE_NEW_CONSOLE = 16
2762 sys.stderr.write(" a DOS box should flash briefly ...\n")
2763 subprocess.call(sys.executable +
2764 ' -c "import time; time.sleep(0.25)"',
2765 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002766
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002767 def test_invalid_args(self):
2768 # invalid arguments should raise ValueError
2769 self.assertRaises(ValueError, subprocess.call,
2770 [sys.executable, "-c",
2771 "import sys; sys.exit(47)"],
2772 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002773
Oren Milman0b3a87e2017-09-14 22:30:28 +03002774 @support.cpython_only
2775 def test_issue31471(self):
2776 # There shouldn't be an assertion failure in Popen() in case the env
2777 # argument has a bad keys() method.
2778 class BadEnv(dict):
2779 keys = None
2780 with self.assertRaises(TypeError):
2781 subprocess.Popen([sys.executable, "-c", "pass"], env=BadEnv())
2782
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002783 def test_close_fds(self):
2784 # close file descriptors
2785 rc = subprocess.call([sys.executable, "-c",
2786 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002787 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002788 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002789
Segev Finerb2a60832017-12-18 11:28:19 +02002790 def test_close_fds_with_stdio(self):
2791 import msvcrt
2792
2793 fds = os.pipe()
2794 self.addCleanup(os.close, fds[0])
2795 self.addCleanup(os.close, fds[1])
2796
2797 handles = []
2798 for fd in fds:
2799 os.set_inheritable(fd, True)
2800 handles.append(msvcrt.get_osfhandle(fd))
2801
2802 p = subprocess.Popen([sys.executable, "-c",
2803 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2804 stdout=subprocess.PIPE, close_fds=False)
2805 stdout, stderr = p.communicate()
2806 self.assertEqual(p.returncode, 0)
2807 int(stdout.strip()) # Check that stdout is an integer
2808
2809 p = subprocess.Popen([sys.executable, "-c",
2810 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2811 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
2812 stdout, stderr = p.communicate()
2813 self.assertEqual(p.returncode, 1)
2814 self.assertIn(b"OSError", stderr)
2815
2816 # The same as the previous call, but with an empty handle_list
2817 handle_list = []
2818 startupinfo = subprocess.STARTUPINFO()
2819 startupinfo.lpAttributeList = {"handle_list": handle_list}
2820 p = subprocess.Popen([sys.executable, "-c",
2821 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2822 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
2823 startupinfo=startupinfo, close_fds=True)
2824 stdout, stderr = p.communicate()
2825 self.assertEqual(p.returncode, 1)
2826 self.assertIn(b"OSError", stderr)
2827
2828 # Check for a warning due to using handle_list and close_fds=False
2829 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
2830 startupinfo = subprocess.STARTUPINFO()
2831 startupinfo.lpAttributeList = {"handle_list": handles[:]}
2832 p = subprocess.Popen([sys.executable, "-c",
2833 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2834 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
2835 startupinfo=startupinfo, close_fds=False)
2836 stdout, stderr = p.communicate()
2837 self.assertEqual(p.returncode, 0)
2838
2839 def test_empty_attribute_list(self):
2840 startupinfo = subprocess.STARTUPINFO()
2841 startupinfo.lpAttributeList = {}
2842 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2843 startupinfo=startupinfo)
2844
2845 def test_empty_handle_list(self):
2846 startupinfo = subprocess.STARTUPINFO()
2847 startupinfo.lpAttributeList = {"handle_list": []}
2848 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2849 startupinfo=startupinfo)
2850
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002851 def test_shell_sequence(self):
2852 # Run command through the shell (sequence)
2853 newenv = os.environ.copy()
2854 newenv["FRUIT"] = "physalis"
2855 p = subprocess.Popen(["set"], shell=1,
2856 stdout=subprocess.PIPE,
2857 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002858 with p:
2859 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002860
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002861 def test_shell_string(self):
2862 # Run command through the shell (string)
2863 newenv = os.environ.copy()
2864 newenv["FRUIT"] = "physalis"
2865 p = subprocess.Popen("set", shell=1,
2866 stdout=subprocess.PIPE,
2867 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002868 with p:
2869 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002870
Steve Dower050acae2016-09-06 20:16:17 -07002871 def test_shell_encodings(self):
2872 # Run command through the shell (string)
2873 for enc in ['ansi', 'oem']:
2874 newenv = os.environ.copy()
2875 newenv["FRUIT"] = "physalis"
2876 p = subprocess.Popen("set", shell=1,
2877 stdout=subprocess.PIPE,
2878 env=newenv,
2879 encoding=enc)
2880 with p:
2881 self.assertIn("physalis", p.stdout.read(), enc)
2882
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002883 def test_call_string(self):
2884 # call() function with string argument on Windows
2885 rc = subprocess.call(sys.executable +
2886 ' -c "import sys; sys.exit(47)"')
2887 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002888
Florent Xicluna4886d242010-03-08 13:27:26 +00002889 def _kill_process(self, method, *args):
2890 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002891 p = subprocess.Popen([sys.executable, "-c", """if 1:
2892 import sys, time
2893 sys.stdout.write('x\\n')
2894 sys.stdout.flush()
2895 time.sleep(30)
2896 """],
2897 stdin=subprocess.PIPE,
2898 stdout=subprocess.PIPE,
2899 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002900 with p:
2901 # Wait for the interpreter to be completely initialized before
2902 # sending any signal.
2903 p.stdout.read(1)
2904 getattr(p, method)(*args)
2905 _, stderr = p.communicate()
2906 self.assertStderrEqual(stderr, b'')
2907 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002908 self.assertNotEqual(returncode, 0)
2909
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002910 def _kill_dead_process(self, method, *args):
2911 p = subprocess.Popen([sys.executable, "-c", """if 1:
2912 import sys, time
2913 sys.stdout.write('x\\n')
2914 sys.stdout.flush()
2915 sys.exit(42)
2916 """],
2917 stdin=subprocess.PIPE,
2918 stdout=subprocess.PIPE,
2919 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002920 with p:
2921 # Wait for the interpreter to be completely initialized before
2922 # sending any signal.
2923 p.stdout.read(1)
2924 # The process should end after this
2925 time.sleep(1)
2926 # This shouldn't raise even though the child is now dead
2927 getattr(p, method)(*args)
2928 _, stderr = p.communicate()
2929 self.assertStderrEqual(stderr, b'')
2930 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002931 self.assertEqual(rc, 42)
2932
Florent Xicluna4886d242010-03-08 13:27:26 +00002933 def test_send_signal(self):
2934 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002935
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002936 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002937 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002938
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002939 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002940 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002941
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002942 def test_send_signal_dead(self):
2943 self._kill_dead_process('send_signal', signal.SIGTERM)
2944
2945 def test_kill_dead(self):
2946 self._kill_dead_process('kill')
2947
2948 def test_terminate_dead(self):
2949 self._kill_dead_process('terminate')
2950
Martin Panter23172bd2016-04-16 11:28:10 +00002951class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08002952
2953 class RecordingPopen(subprocess.Popen):
2954 """A Popen that saves a reference to each instance for testing."""
2955 instances_created = []
2956
2957 def __init__(self, *args, **kwargs):
2958 super().__init__(*args, **kwargs)
2959 self.instances_created.append(self)
2960
2961 @mock.patch.object(subprocess.Popen, "_communicate")
2962 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
2963 **kwargs):
2964 """Fake a SIGINT happening during Popen._communicate() and ._wait().
2965
2966 This avoids the need to actually try and get test environments to send
2967 and receive signals reliably across platforms. The net effect of a ^C
2968 happening during a blocking subprocess execution which we want to clean
2969 up from is a KeyboardInterrupt coming out of communicate() or wait().
2970 """
2971
2972 mock__communicate.side_effect = KeyboardInterrupt
2973 try:
2974 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
2975 # We patch out _wait() as no signal was involved so the
2976 # child process isn't actually going to exit rapidly.
2977 mock__wait.side_effect = KeyboardInterrupt
2978 with mock.patch.object(subprocess, "Popen",
2979 self.RecordingPopen):
2980 with self.assertRaises(KeyboardInterrupt):
2981 popener([sys.executable, "-c",
2982 "import time\ntime.sleep(9)\nimport sys\n"
2983 "sys.stderr.write('\\n!runaway child!\\n')"],
2984 stdout=subprocess.DEVNULL, **kwargs)
2985 for call in mock__wait.call_args_list[1:]:
2986 self.assertNotEqual(
2987 call, mock.call(timeout=None),
2988 "no open-ended wait() after the first allowed: "
2989 f"{mock__wait.call_args_list}")
2990 sigint_calls = []
2991 for call in mock__wait.call_args_list:
2992 if call == mock.call(timeout=0.25): # from Popen.__init__
2993 sigint_calls.append(call)
2994 self.assertLessEqual(mock__wait.call_count, 2,
2995 msg=mock__wait.call_args_list)
2996 self.assertEqual(len(sigint_calls), 1,
2997 msg=mock__wait.call_args_list)
2998 finally:
2999 # cleanup the forgotten (due to our mocks) child process
3000 process = self.RecordingPopen.instances_created.pop()
3001 process.kill()
3002 process.wait()
3003 self.assertEqual([], self.RecordingPopen.instances_created)
3004
3005 def test_call_keyboardinterrupt_no_kill(self):
3006 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3007
3008 def test_run_keyboardinterrupt_no_kill(self):
3009 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3010
3011 def test_context_manager_keyboardinterrupt_no_kill(self):
3012 def popen_via_context_manager(*args, **kwargs):
3013 with subprocess.Popen(*args, **kwargs) as unused_process:
3014 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3015 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3016
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003017 def test_getoutput(self):
3018 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3019 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3020 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003021
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003022 # we use mkdtemp in the next line to create an empty directory
3023 # under our exclusive control; from that, we can invent a pathname
3024 # that we _know_ won't exist. This is guaranteed to fail.
3025 dir = None
3026 try:
3027 dir = tempfile.mkdtemp()
3028 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003029 status, output = subprocess.getstatusoutput(
3030 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003031 self.assertNotEqual(status, 0)
3032 finally:
3033 if dir is not None:
3034 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003035
Gregory P. Smithace55862015-04-07 15:57:54 -07003036 def test__all__(self):
3037 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00003038 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003039 exported = set(subprocess.__all__)
3040 possible_exports = set()
3041 import types
3042 for name, value in subprocess.__dict__.items():
3043 if name.startswith('_'):
3044 continue
3045 if isinstance(value, (types.ModuleType,)):
3046 continue
3047 possible_exports.add(name)
3048 self.assertEqual(exported, possible_exports - intentionally_excluded)
3049
3050
Martin Panter23172bd2016-04-16 11:28:10 +00003051@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3052 "Test needs selectors.PollSelector")
3053class ProcessTestCaseNoPoll(ProcessTestCase):
3054 def setUp(self):
3055 self.orig_selector = subprocess._PopenSelector
3056 subprocess._PopenSelector = selectors.SelectSelector
3057 ProcessTestCase.setUp(self)
3058
3059 def tearDown(self):
3060 subprocess._PopenSelector = self.orig_selector
3061 ProcessTestCase.tearDown(self)
3062
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003063
Tim Golden126c2962010-08-11 14:20:40 +00003064@unittest.skipUnless(mswindows, "Windows-specific tests")
3065class CommandsWithSpaces (BaseTestCase):
3066
3067 def setUp(self):
3068 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003069 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003070 self.fname = fname.lower ()
3071 os.write(f, b"import sys;"
3072 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3073 )
3074 os.close(f)
3075
3076 def tearDown(self):
3077 os.remove(self.fname)
3078 super().tearDown()
3079
3080 def with_spaces(self, *args, **kwargs):
3081 kwargs['stdout'] = subprocess.PIPE
3082 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003083 with p:
3084 self.assertEqual(
3085 p.stdout.read ().decode("mbcs"),
3086 "2 [%r, 'ab cd']" % self.fname
3087 )
Tim Golden126c2962010-08-11 14:20:40 +00003088
3089 def test_shell_string_with_spaces(self):
3090 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003091 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3092 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003093
3094 def test_shell_sequence_with_spaces(self):
3095 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003096 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003097
3098 def test_noshell_string_with_spaces(self):
3099 # call() function with string argument with spaces on Windows
3100 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3101 "ab cd"))
3102
3103 def test_noshell_sequence_with_spaces(self):
3104 # call() function with sequence argument with spaces on Windows
3105 self.with_spaces([sys.executable, self.fname, "ab cd"])
3106
Brian Curtin79cdb662010-12-03 02:46:02 +00003107
Georg Brandla86b2622012-02-20 21:34:57 +01003108class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003109
3110 def test_pipe(self):
3111 with subprocess.Popen([sys.executable, "-c",
3112 "import sys;"
3113 "sys.stdout.write('stdout');"
3114 "sys.stderr.write('stderr');"],
3115 stdout=subprocess.PIPE,
3116 stderr=subprocess.PIPE) as proc:
3117 self.assertEqual(proc.stdout.read(), b"stdout")
3118 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3119
3120 self.assertTrue(proc.stdout.closed)
3121 self.assertTrue(proc.stderr.closed)
3122
3123 def test_returncode(self):
3124 with subprocess.Popen([sys.executable, "-c",
3125 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003126 pass
3127 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003128 self.assertEqual(proc.returncode, 100)
3129
3130 def test_communicate_stdin(self):
3131 with subprocess.Popen([sys.executable, "-c",
3132 "import sys;"
3133 "sys.exit(sys.stdin.read() == 'context')"],
3134 stdin=subprocess.PIPE) as proc:
3135 proc.communicate(b"context")
3136 self.assertEqual(proc.returncode, 1)
3137
3138 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003139 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003140 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003141 stdout=subprocess.PIPE,
3142 stderr=subprocess.PIPE) as proc:
3143 pass
3144
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003145 def test_broken_pipe_cleanup(self):
3146 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003147 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01003148 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003149 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003150 proc = proc.__enter__()
3151 # Prepare to send enough data to overflow any OS pipe buffering and
3152 # guarantee a broken pipe error. Data is held in BufferedWriter
3153 # buffer until closed.
3154 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003155 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003156 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003157 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003158 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003159 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003160
Brian Curtin79cdb662010-12-03 02:46:02 +00003161
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003162if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003163 unittest.main()