blob: 4b409b7bd43c1044a2be6c7b4fa256b6abda6f09 [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
Berker Peksagce643912015-05-06 06:33:17 +03003from test.support import script_helper
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00005import subprocess
6import sys
7import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04008import io
Andrew Svetlov82860712012-08-19 22:13:41 +03009import locale
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000010import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000011import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000012import tempfile
13import time
Tim Peters3761e8d2004-10-13 04:07:12 +000014import re
Charles-François Natali3a4586a2013-11-08 19:56:59 +010015import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000016import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000017import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000018import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040019import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050020import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030021import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050022
23try:
Antoine Pitroua8392712013-08-30 23:38:13 +020024 import threading
25except ImportError:
26 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050027
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000028mswindows = (sys.platform == "win32")
29
30#
31# Depends on the following external programs: Python
32#
33
34if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000035 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
36 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000037else:
38 SETBINARY = ''
39
Florent Xiclunab1e94e82010-02-27 22:12:37 +000040
Florent Xiclunac049d872010-03-27 22:47:23 +000041class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000042 def setUp(self):
43 # Try to minimize the number of children we have so this test
44 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000045 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000046
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000047 def tearDown(self):
48 for inst in subprocess._active:
49 inst.wait()
50 subprocess._cleanup()
51 self.assertFalse(subprocess._active, "subprocess._active not empty")
52
Florent Xiclunab1e94e82010-02-27 22:12:37 +000053 def assertStderrEqual(self, stderr, expected, msg=None):
54 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
55 # shutdown time. That frustrates tests trying to check stderr produced
56 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000057 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040058 # strip_python_stderr also strips whitespace, so we do too.
59 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000060 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000061
Florent Xiclunac049d872010-03-27 22:47:23 +000062
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080063class PopenTestException(Exception):
64 pass
65
66
67class PopenExecuteChildRaises(subprocess.Popen):
68 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
69 _execute_child fails.
70 """
71 def _execute_child(self, *args, **kwargs):
72 raise PopenTestException("Forced Exception for Test")
73
74
Florent Xiclunac049d872010-03-27 22:47:23 +000075class ProcessTestCase(BaseTestCase):
76
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070077 def test_io_buffered_by_default(self):
78 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
79 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
80 stderr=subprocess.PIPE)
81 try:
82 self.assertIsInstance(p.stdin, io.BufferedIOBase)
83 self.assertIsInstance(p.stdout, io.BufferedIOBase)
84 self.assertIsInstance(p.stderr, io.BufferedIOBase)
85 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070086 p.stdin.close()
87 p.stdout.close()
88 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070089 p.wait()
90
91 def test_io_unbuffered_works(self):
92 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
93 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
94 stderr=subprocess.PIPE, bufsize=0)
95 try:
96 self.assertIsInstance(p.stdin, io.RawIOBase)
97 self.assertIsInstance(p.stdout, io.RawIOBase)
98 self.assertIsInstance(p.stderr, io.RawIOBase)
99 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700100 p.stdin.close()
101 p.stdout.close()
102 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700103 p.wait()
104
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000105 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000106 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000107 rc = subprocess.call([sys.executable, "-c",
108 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000109 self.assertEqual(rc, 47)
110
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400111 def test_call_timeout(self):
112 # call() function with timeout argument; we want to test that the child
113 # process gets killed when the timeout expires. If the child isn't
114 # killed, this call will deadlock since subprocess.call waits for the
115 # child.
116 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
117 [sys.executable, "-c", "while True: pass"],
118 timeout=0.1)
119
Peter Astrand454f7672005-01-01 09:36:35 +0000120 def test_check_call_zero(self):
121 # check_call() function with zero return code
122 rc = subprocess.check_call([sys.executable, "-c",
123 "import sys; sys.exit(0)"])
124 self.assertEqual(rc, 0)
125
126 def test_check_call_nonzero(self):
127 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000128 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000129 subprocess.check_call([sys.executable, "-c",
130 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000131 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000132
Georg Brandlf9734072008-12-07 15:30:06 +0000133 def test_check_output(self):
134 # check_output() function with zero return code
135 output = subprocess.check_output(
136 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000137 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000138
139 def test_check_output_nonzero(self):
140 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000141 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000142 subprocess.check_output(
143 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000144 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000145
146 def test_check_output_stderr(self):
147 # check_output() function stderr redirected to stdout
148 output = subprocess.check_output(
149 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
150 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000151 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000152
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300153 def test_check_output_stdin_arg(self):
154 # check_output() can be called with stdin set to a file
155 tf = tempfile.TemporaryFile()
156 self.addCleanup(tf.close)
157 tf.write(b'pear')
158 tf.seek(0)
159 output = subprocess.check_output(
160 [sys.executable, "-c",
161 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
162 stdin=tf)
163 self.assertIn(b'PEAR', output)
164
165 def test_check_output_input_arg(self):
166 # check_output() can be called with input set to a string
167 output = subprocess.check_output(
168 [sys.executable, "-c",
169 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
170 input=b'pear')
171 self.assertIn(b'PEAR', output)
172
Georg Brandlf9734072008-12-07 15:30:06 +0000173 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300174 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000175 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000176 output = subprocess.check_output(
177 [sys.executable, "-c", "print('will not be run')"],
178 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000179 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000180 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000181
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300182 def test_check_output_stdin_with_input_arg(self):
183 # check_output() refuses to accept 'stdin' with 'input'
184 tf = tempfile.TemporaryFile()
185 self.addCleanup(tf.close)
186 tf.write(b'pear')
187 tf.seek(0)
188 with self.assertRaises(ValueError) as c:
189 output = subprocess.check_output(
190 [sys.executable, "-c", "print('will not be run')"],
191 stdin=tf, input=b'hare')
192 self.fail("Expected ValueError when stdin and input args supplied.")
193 self.assertIn('stdin', c.exception.args[0])
194 self.assertIn('input', c.exception.args[0])
195
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400196 def test_check_output_timeout(self):
197 # check_output() function with timeout arg
198 with self.assertRaises(subprocess.TimeoutExpired) as c:
199 output = subprocess.check_output(
200 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200201 "import sys, time\n"
202 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400203 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200204 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400205 # Some heavily loaded buildbots (sparc Debian 3.x) require
206 # this much time to start and print.
207 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400208 self.fail("Expected TimeoutExpired.")
209 self.assertEqual(c.exception.output, b'BDFL')
210
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000211 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000212 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000213 newenv = os.environ.copy()
214 newenv["FRUIT"] = "banana"
215 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000216 'import sys, os;'
217 'sys.exit(os.getenv("FRUIT")=="banana")'],
218 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000219 self.assertEqual(rc, 1)
220
Victor Stinner87b9bc32011-06-01 00:57:47 +0200221 def test_invalid_args(self):
222 # Popen() called with invalid arguments should raise TypeError
223 # but Popen.__del__ should not complain (issue #12085)
224 with support.captured_stderr() as s:
225 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
226 argcount = subprocess.Popen.__init__.__code__.co_argcount
227 too_many_args = [0] * (argcount + 1)
228 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
229 self.assertEqual(s.getvalue(), '')
230
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000231 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000232 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000233 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000234 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000235 self.addCleanup(p.stdout.close)
236 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000237 p.wait()
238 self.assertEqual(p.stdin, None)
239
240 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200241 # .stdout is None when not redirected, and the child's stdout will
242 # be inherited from the parent. In order to test this we run a
243 # subprocess in a subprocess:
244 # this_test
245 # \-- subprocess created by this test (parent)
246 # \-- subprocess created by the parent subprocess (child)
247 # The parent doesn't specify stdout, so the child will use the
248 # parent's stdout. This test checks that the message printed by the
249 # child goes to the parent stdout. The parent also checks that the
250 # child's stdout is None. See #11963.
251 code = ('import sys; from subprocess import Popen, PIPE;'
252 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
253 ' stdin=PIPE, stderr=PIPE);'
254 'p.wait(); assert p.stdout is None;')
255 p = subprocess.Popen([sys.executable, "-c", code],
256 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
257 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000258 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200259 out, err = p.communicate()
260 self.assertEqual(p.returncode, 0, err)
261 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262
263 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000264 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000265 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000266 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000267 self.addCleanup(p.stdout.close)
268 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269 p.wait()
270 self.assertEqual(p.stderr, None)
271
Chris Jerdonek776cb192012-10-08 15:56:43 -0700272 def _assert_python(self, pre_args, **kwargs):
273 # We include sys.exit() to prevent the test runner from hanging
274 # whenever python is found.
275 args = pre_args + ["import sys; sys.exit(47)"]
276 p = subprocess.Popen(args, **kwargs)
277 p.wait()
278 self.assertEqual(47, p.returncode)
279
280 def test_executable(self):
281 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700282 #
283 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
284 # determine where its standard library is, so we need the directory
285 # of args[0] to be valid for the Popen() call to Python to succeed.
286 # See also issue #16170 and issue #7774.
287 doesnotexist = os.path.join(os.path.dirname(sys.executable),
288 "doesnotexist")
289 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700290
291 def test_executable_takes_precedence(self):
292 # Check that the executable argument takes precedence over args[0].
293 #
294 # Verify first that the call succeeds without the executable arg.
295 pre_args = [sys.executable, "-c"]
296 self._assert_python(pre_args)
297 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
298 executable="doesnotexist")
299
300 @unittest.skipIf(mswindows, "executable argument replaces shell")
301 def test_executable_replaces_shell(self):
302 # Check that the executable argument replaces the default shell
303 # when shell=True.
304 self._assert_python([], executable=sys.executable, shell=True)
305
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700306 # For use in the test_cwd* tests below.
307 def _normalize_cwd(self, cwd):
308 # Normalize an expected cwd (for Tru64 support).
309 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
310 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300311 with support.change_cwd(cwd):
312 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700313
314 # For use in the test_cwd* tests below.
315 def _split_python_path(self):
316 # Return normalized (python_dir, python_base).
317 python_path = os.path.realpath(sys.executable)
318 return os.path.split(python_path)
319
320 # For use in the test_cwd* tests below.
321 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
322 # Invoke Python via Popen, and assert that (1) the call succeeds,
323 # and that (2) the current working directory of the child process
324 # matches *expected_cwd*.
325 p = subprocess.Popen([python_arg, "-c",
326 "import os, sys; "
327 "sys.stdout.write(os.getcwd()); "
328 "sys.exit(47)"],
329 stdout=subprocess.PIPE,
330 **kwargs)
331 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000332 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700333 self.assertEqual(47, p.returncode)
334 normcase = os.path.normcase
335 self.assertEqual(normcase(expected_cwd),
336 normcase(p.stdout.read().decode("utf-8")))
337
338 def test_cwd(self):
339 # Check that cwd changes the cwd for the child process.
340 temp_dir = tempfile.gettempdir()
341 temp_dir = self._normalize_cwd(temp_dir)
342 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
343
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700344 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700345 def test_cwd_with_relative_arg(self):
346 # Check that Popen looks for args[0] relative to cwd if args[0]
347 # is relative.
348 python_dir, python_base = self._split_python_path()
349 rel_python = os.path.join(os.curdir, python_base)
350 with support.temp_cwd() as wrong_dir:
351 # Before calling with the correct cwd, confirm that the call fails
352 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700353 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700354 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700355 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700356 [rel_python], cwd=wrong_dir)
357 python_dir = self._normalize_cwd(python_dir)
358 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
359
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700360 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700361 def test_cwd_with_relative_executable(self):
362 # Check that Popen looks for executable relative to cwd if executable
363 # is relative (and that executable takes precedence over args[0]).
364 python_dir, python_base = self._split_python_path()
365 rel_python = os.path.join(os.curdir, python_base)
366 doesntexist = "somethingyoudonthave"
367 with support.temp_cwd() as wrong_dir:
368 # Before calling with the correct cwd, confirm that the call fails
369 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700370 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700371 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700372 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700373 [doesntexist], executable=rel_python,
374 cwd=wrong_dir)
375 python_dir = self._normalize_cwd(python_dir)
376 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
377 cwd=python_dir)
378
379 def test_cwd_with_absolute_arg(self):
380 # Check that Popen can find the executable when the cwd is wrong
381 # if args[0] is an absolute path.
382 python_dir, python_base = self._split_python_path()
383 abs_python = os.path.join(python_dir, python_base)
384 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300385 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700386 # Before calling with an absolute path, confirm that using a
387 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700388 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700389 [rel_python], cwd=wrong_dir)
390 wrong_dir = self._normalize_cwd(wrong_dir)
391 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
392
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100393 @unittest.skipIf(sys.base_prefix != sys.prefix,
394 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000395 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700396 python_dir, python_base = self._split_python_path()
397 python_dir = self._normalize_cwd(python_dir)
398 self._assert_cwd(python_dir, "somethingyoudonthave",
399 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000400
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100401 @unittest.skipIf(sys.base_prefix != sys.prefix,
402 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000403 @unittest.skipIf(sysconfig.is_python_build(),
404 "need an installed Python. See #7774")
405 def test_executable_without_cwd(self):
406 # For a normal installation, it should work without 'cwd'
407 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700408 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
409 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000410
411 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000412 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413 p = subprocess.Popen([sys.executable, "-c",
414 'import sys; sys.exit(sys.stdin.read() == "pear")'],
415 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000416 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000417 p.stdin.close()
418 p.wait()
419 self.assertEqual(p.returncode, 1)
420
421 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000422 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000423 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000424 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000425 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000426 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000427 os.lseek(d, 0, 0)
428 p = subprocess.Popen([sys.executable, "-c",
429 'import sys; sys.exit(sys.stdin.read() == "pear")'],
430 stdin=d)
431 p.wait()
432 self.assertEqual(p.returncode, 1)
433
434 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000435 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000436 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000437 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000438 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000439 tf.seek(0)
440 p = subprocess.Popen([sys.executable, "-c",
441 'import sys; sys.exit(sys.stdin.read() == "pear")'],
442 stdin=tf)
443 p.wait()
444 self.assertEqual(p.returncode, 1)
445
446 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000447 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000448 p = subprocess.Popen([sys.executable, "-c",
449 'import sys; sys.stdout.write("orange")'],
450 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000451 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000452 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000453
454 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000455 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000456 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000457 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000458 d = tf.fileno()
459 p = subprocess.Popen([sys.executable, "-c",
460 'import sys; sys.stdout.write("orange")'],
461 stdout=d)
462 p.wait()
463 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000464 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000465
466 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000467 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000468 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000469 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470 p = subprocess.Popen([sys.executable, "-c",
471 'import sys; sys.stdout.write("orange")'],
472 stdout=tf)
473 p.wait()
474 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000475 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476
477 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000478 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479 p = subprocess.Popen([sys.executable, "-c",
480 'import sys; sys.stderr.write("strawberry")'],
481 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000482 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000483 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484
485 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000486 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000487 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000488 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 d = tf.fileno()
490 p = subprocess.Popen([sys.executable, "-c",
491 'import sys; sys.stderr.write("strawberry")'],
492 stderr=d)
493 p.wait()
494 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000495 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000496
497 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000498 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000499 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000500 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501 p = subprocess.Popen([sys.executable, "-c",
502 'import sys; sys.stderr.write("strawberry")'],
503 stderr=tf)
504 p.wait()
505 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000506 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507
Martin Panterc7635892016-05-13 01:54:44 +0000508 def test_stderr_redirect_with_no_stdout_redirect(self):
509 # test stderr=STDOUT while stdout=None (not set)
510
511 # - grandchild prints to stderr
512 # - child redirects grandchild's stderr to its stdout
513 # - the parent should get grandchild's stderr in child's stdout
514 p = subprocess.Popen([sys.executable, "-c",
515 'import sys, subprocess;'
516 'rc = subprocess.call([sys.executable, "-c",'
517 ' "import sys;"'
518 ' "sys.stderr.write(\'42\')"],'
519 ' stderr=subprocess.STDOUT);'
520 'sys.exit(rc)'],
521 stdout=subprocess.PIPE,
522 stderr=subprocess.PIPE)
523 stdout, stderr = p.communicate()
524 #NOTE: stdout should get stderr from grandchild
525 self.assertStderrEqual(stdout, b'42')
526 self.assertStderrEqual(stderr, b'') # should be empty
527 self.assertEqual(p.returncode, 0)
528
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000529 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000530 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000532 'import sys;'
533 'sys.stdout.write("apple");'
534 'sys.stdout.flush();'
535 'sys.stderr.write("orange")'],
536 stdout=subprocess.PIPE,
537 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000538 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000539 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540
541 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000542 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000544 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000546 'import sys;'
547 'sys.stdout.write("apple");'
548 'sys.stdout.flush();'
549 'sys.stderr.write("orange")'],
550 stdout=tf,
551 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000552 p.wait()
553 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000554 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000555
Thomas Wouters89f507f2006-12-13 04:49:30 +0000556 def test_stdout_filedes_of_stdout(self):
557 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200558 # To avoid printing the text on stdout, we do something similar to
559 # test_stdout_none (see above). The parent subprocess calls the child
560 # subprocess passing stdout=1, and this test uses stdout=PIPE in
561 # order to capture and check the output of the parent. See #11963.
562 code = ('import sys, subprocess; '
563 'rc = subprocess.call([sys.executable, "-c", '
564 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
565 'b\'test with stdout=1\'))"], stdout=1); '
566 'assert rc == 18')
567 p = subprocess.Popen([sys.executable, "-c", code],
568 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
569 self.addCleanup(p.stdout.close)
570 self.addCleanup(p.stderr.close)
571 out, err = p.communicate()
572 self.assertEqual(p.returncode, 0, err)
573 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000574
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200575 def test_stdout_devnull(self):
576 p = subprocess.Popen([sys.executable, "-c",
577 'for i in range(10240):'
578 'print("x" * 1024)'],
579 stdout=subprocess.DEVNULL)
580 p.wait()
581 self.assertEqual(p.stdout, None)
582
583 def test_stderr_devnull(self):
584 p = subprocess.Popen([sys.executable, "-c",
585 'import sys\n'
586 'for i in range(10240):'
587 'sys.stderr.write("x" * 1024)'],
588 stderr=subprocess.DEVNULL)
589 p.wait()
590 self.assertEqual(p.stderr, None)
591
592 def test_stdin_devnull(self):
593 p = subprocess.Popen([sys.executable, "-c",
594 'import sys;'
595 'sys.stdin.read(1)'],
596 stdin=subprocess.DEVNULL)
597 p.wait()
598 self.assertEqual(p.stdin, None)
599
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000600 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601 newenv = os.environ.copy()
602 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200603 with subprocess.Popen([sys.executable, "-c",
604 'import sys,os;'
605 'sys.stdout.write(os.getenv("FRUIT"))'],
606 stdout=subprocess.PIPE,
607 env=newenv) as p:
608 stdout, stderr = p.communicate()
609 self.assertEqual(stdout, b"orange")
610
Victor Stinner62d51182011-06-23 01:02:25 +0200611 # Windows requires at least the SYSTEMROOT environment variable to start
612 # Python
613 @unittest.skipIf(sys.platform == 'win32',
614 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200615 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200616 'the python library cannot be loaded '
617 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200618 def test_empty_env(self):
619 with subprocess.Popen([sys.executable, "-c",
620 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200621 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200622 stdout=subprocess.PIPE,
623 env={}) as p:
624 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200625 self.assertIn(stdout.strip(),
626 (b"[]",
627 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
628 # environment
629 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000630
Peter Astrandcbac93c2005-03-03 20:24:28 +0000631 def test_communicate_stdin(self):
632 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000633 'import sys;'
634 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000635 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000636 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000637 self.assertEqual(p.returncode, 1)
638
639 def test_communicate_stdout(self):
640 p = subprocess.Popen([sys.executable, "-c",
641 'import sys; sys.stdout.write("pineapple")'],
642 stdout=subprocess.PIPE)
643 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000644 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000645 self.assertEqual(stderr, None)
646
647 def test_communicate_stderr(self):
648 p = subprocess.Popen([sys.executable, "-c",
649 'import sys; sys.stderr.write("pineapple")'],
650 stderr=subprocess.PIPE)
651 (stdout, stderr) = p.communicate()
652 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000653 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000654
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000655 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000656 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000657 'import sys,os;'
658 'sys.stderr.write("pineapple");'
659 'sys.stdout.write(sys.stdin.read())'],
660 stdin=subprocess.PIPE,
661 stdout=subprocess.PIPE,
662 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000663 self.addCleanup(p.stdout.close)
664 self.addCleanup(p.stderr.close)
665 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000666 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000667 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000668 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000669
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400670 def test_communicate_timeout(self):
671 p = subprocess.Popen([sys.executable, "-c",
672 'import sys,os,time;'
673 'sys.stderr.write("pineapple\\n");'
674 'time.sleep(1);'
675 'sys.stderr.write("pear\\n");'
676 'sys.stdout.write(sys.stdin.read())'],
677 universal_newlines=True,
678 stdin=subprocess.PIPE,
679 stdout=subprocess.PIPE,
680 stderr=subprocess.PIPE)
681 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
682 timeout=0.3)
683 # Make sure we can keep waiting for it, and that we get the whole output
684 # after it completes.
685 (stdout, stderr) = p.communicate()
686 self.assertEqual(stdout, "banana")
687 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
688
689 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200690 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400691 p = subprocess.Popen([sys.executable, "-c",
692 'import sys,os,time;'
693 'sys.stdout.write("a" * (64 * 1024));'
694 'time.sleep(0.2);'
695 'sys.stdout.write("a" * (64 * 1024));'
696 'time.sleep(0.2);'
697 'sys.stdout.write("a" * (64 * 1024));'
698 'time.sleep(0.2);'
699 'sys.stdout.write("a" * (64 * 1024));'],
700 stdout=subprocess.PIPE)
701 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
702 (stdout, _) = p.communicate()
703 self.assertEqual(len(stdout), 4 * 64 * 1024)
704
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000705 # Test for the fd leak reported in http://bugs.python.org/issue2791.
706 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000707 for stdin_pipe in (False, True):
708 for stdout_pipe in (False, True):
709 for stderr_pipe in (False, True):
710 options = {}
711 if stdin_pipe:
712 options['stdin'] = subprocess.PIPE
713 if stdout_pipe:
714 options['stdout'] = subprocess.PIPE
715 if stderr_pipe:
716 options['stderr'] = subprocess.PIPE
717 if not options:
718 continue
719 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
720 p.communicate()
721 if p.stdin is not None:
722 self.assertTrue(p.stdin.closed)
723 if p.stdout is not None:
724 self.assertTrue(p.stdout.closed)
725 if p.stderr is not None:
726 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000727
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000728 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000729 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000730 p = subprocess.Popen([sys.executable, "-c",
731 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000732 (stdout, stderr) = p.communicate()
733 self.assertEqual(stdout, None)
734 self.assertEqual(stderr, None)
735
736 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000737 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000739 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000740 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000741 os.close(x)
742 os.close(y)
743 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000744 'import sys,os;'
745 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200746 'sys.stderr.write("x" * %d);'
747 'sys.stdout.write(sys.stdin.read())' %
748 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000749 stdin=subprocess.PIPE,
750 stdout=subprocess.PIPE,
751 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000752 self.addCleanup(p.stdout.close)
753 self.addCleanup(p.stderr.close)
754 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200755 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000756 (stdout, stderr) = p.communicate(string_to_write)
757 self.assertEqual(stdout, string_to_write)
758
759 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000760 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000761 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000762 'import sys,os;'
763 'sys.stdout.write(sys.stdin.read())'],
764 stdin=subprocess.PIPE,
765 stdout=subprocess.PIPE,
766 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000767 self.addCleanup(p.stdout.close)
768 self.addCleanup(p.stderr.close)
769 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000770 p.stdin.write(b"banana")
771 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000772 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000773 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000774
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000775 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000776 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000777 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200778 'buf = sys.stdout.buffer;'
779 'buf.write(sys.stdin.readline().encode());'
780 'buf.flush();'
781 'buf.write(b"line2\\n");'
782 'buf.flush();'
783 'buf.write(sys.stdin.read().encode());'
784 'buf.flush();'
785 'buf.write(b"line4\\n");'
786 'buf.flush();'
787 'buf.write(b"line5\\r\\n");'
788 'buf.flush();'
789 'buf.write(b"line6\\r");'
790 'buf.flush();'
791 'buf.write(b"\\nline7");'
792 'buf.flush();'
793 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200794 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000795 stdout=subprocess.PIPE,
796 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200797 p.stdin.write("line1\n")
Antoine Pitrouc644e7c2014-05-09 00:24:50 +0200798 p.stdin.flush()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200799 self.assertEqual(p.stdout.readline(), "line1\n")
800 p.stdin.write("line3\n")
801 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000802 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200803 self.assertEqual(p.stdout.readline(),
804 "line2\n")
805 self.assertEqual(p.stdout.read(6),
806 "line3\n")
807 self.assertEqual(p.stdout.read(),
808 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000809
810 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000811 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000812 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000813 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200814 'buf = sys.stdout.buffer;'
815 'buf.write(b"line2\\n");'
816 'buf.flush();'
817 'buf.write(b"line4\\n");'
818 'buf.flush();'
819 'buf.write(b"line5\\r\\n");'
820 'buf.flush();'
821 'buf.write(b"line6\\r");'
822 'buf.flush();'
823 'buf.write(b"\\nline7");'
824 'buf.flush();'
825 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200826 stderr=subprocess.PIPE,
827 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000828 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000829 self.addCleanup(p.stdout.close)
830 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000831 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200832 self.assertEqual(stdout,
833 "line2\nline4\nline5\nline6\nline7\nline8")
834
835 def test_universal_newlines_communicate_stdin(self):
836 # universal newlines through communicate(), with only stdin
837 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300838 'import sys,os;' + SETBINARY + textwrap.dedent('''
839 s = sys.stdin.readline()
840 assert s == "line1\\n", repr(s)
841 s = sys.stdin.read()
842 assert s == "line3\\n", repr(s)
843 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200844 stdin=subprocess.PIPE,
845 universal_newlines=1)
846 (stdout, stderr) = p.communicate("line1\nline3\n")
847 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848
Andrew Svetlovf3765072012-08-14 18:35:17 +0300849 def test_universal_newlines_communicate_input_none(self):
850 # Test communicate(input=None) with universal newlines.
851 #
852 # We set stdout to PIPE because, as of this writing, a different
853 # code path is tested when the number of pipes is zero or one.
854 p = subprocess.Popen([sys.executable, "-c", "pass"],
855 stdin=subprocess.PIPE,
856 stdout=subprocess.PIPE,
857 universal_newlines=True)
858 p.communicate()
859 self.assertEqual(p.returncode, 0)
860
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300861 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300862 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300863 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300864 'import sys,os;' + SETBINARY + textwrap.dedent('''
865 s = sys.stdin.buffer.readline()
866 sys.stdout.buffer.write(s)
867 sys.stdout.buffer.write(b"line2\\r")
868 sys.stderr.buffer.write(b"eline2\\n")
869 s = sys.stdin.buffer.read()
870 sys.stdout.buffer.write(s)
871 sys.stdout.buffer.write(b"line4\\n")
872 sys.stdout.buffer.write(b"line5\\r\\n")
873 sys.stderr.buffer.write(b"eline6\\r")
874 sys.stderr.buffer.write(b"eline7\\r\\nz")
875 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300876 stdin=subprocess.PIPE,
877 stderr=subprocess.PIPE,
878 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300879 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300880 self.addCleanup(p.stdout.close)
881 self.addCleanup(p.stderr.close)
882 (stdout, stderr) = p.communicate("line1\nline3\n")
883 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300884 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300885 # Python debug build push something like "[42442 refs]\n"
886 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300887 # Don't use assertStderrEqual because it strips CR and LF from output.
888 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300889
Andrew Svetlov82860712012-08-19 22:13:41 +0300890 def test_universal_newlines_communicate_encodings(self):
891 # Check that universal newlines mode works for various encodings,
892 # in particular for encodings in the UTF-16 and UTF-32 families.
893 # See issue #15595.
894 #
895 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
896 # without, and UTF-16 and UTF-32.
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200897 import _bootlocale
Andrew Svetlov82860712012-08-19 22:13:41 +0300898 for encoding in ['utf-16', 'utf-32-be']:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200899 old_getpreferredencoding = _bootlocale.getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300900 # Indirectly via io.TextIOWrapper, Popen() defaults to
901 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
902 # locale.getpreferredencoding().
903 def getpreferredencoding(do_setlocale=True):
904 return encoding
905 code = ("import sys; "
906 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
907 encoding)
908 args = [sys.executable, '-c', code]
909 try:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200910 _bootlocale.getpreferredencoding = getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300911 # We set stdin to be non-None because, as of this writing,
912 # a different code path is used when the number of pipes is
913 # zero or one.
914 popen = subprocess.Popen(args, universal_newlines=True,
915 stdin=subprocess.PIPE,
916 stdout=subprocess.PIPE)
917 stdout, stderr = popen.communicate(input='')
918 finally:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200919 _bootlocale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300920 self.assertEqual(stdout, '1\n2\n3\n4')
921
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000922 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000923 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000924 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000925 max_handles = 1026 # too much for most UNIX systems
926 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000927 max_handles = 2050 # too much for (at least some) Windows setups
928 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400929 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000930 try:
931 for i in range(max_handles):
932 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400933 tmpfile = os.path.join(tmpdir, support.TESTFN)
934 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000935 except OSError as e:
936 if e.errno != errno.EMFILE:
937 raise
938 break
939 else:
940 self.skipTest("failed to reach the file descriptor limit "
941 "(tried %d)" % max_handles)
942 # Close a couple of them (should be enough for a subprocess)
943 for i in range(10):
944 os.close(handles.pop())
945 # Loop creating some subprocesses. If one of them leaks some fds,
946 # the next loop iteration will fail by reaching the max fd limit.
947 for i in range(15):
948 p = subprocess.Popen([sys.executable, "-c",
949 "import sys;"
950 "sys.stdout.write(sys.stdin.read())"],
951 stdin=subprocess.PIPE,
952 stdout=subprocess.PIPE,
953 stderr=subprocess.PIPE)
954 data = p.communicate(b"lime")[0]
955 self.assertEqual(data, b"lime")
956 finally:
957 for h in handles:
958 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400959 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000960
961 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000962 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
963 '"a b c" d e')
964 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
965 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000966 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
967 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000968 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
969 'a\\\\\\b "de fg" h')
970 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
971 'a\\\\\\"b c d')
972 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
973 '"a\\\\b c" d e')
974 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
975 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000976 self.assertEqual(subprocess.list2cmdline(['ab', '']),
977 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000978
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000979 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200980 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200981 "import os; os.read(0, 1)"],
982 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200983 self.addCleanup(p.stdin.close)
984 self.assertIsNone(p.poll())
985 os.write(p.stdin.fileno(), b'A')
986 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000987 # Subsequent invocations should just return the returncode
988 self.assertEqual(p.poll(), 0)
989
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000990 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200991 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000992 self.assertEqual(p.wait(), 0)
993 # Subsequent invocations should just return the returncode
994 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000995
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400996 def test_wait_timeout(self):
997 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200998 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400999 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001000 p.wait(timeout=0.0001)
1001 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001002 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1003 # time to start.
1004 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001005
Peter Astrand738131d2004-11-30 21:04:45 +00001006 def test_invalid_bufsize(self):
1007 # an invalid type of the bufsize argument should raise
1008 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001009 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001010 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001011
Guido van Rossum46a05a72007-06-07 21:56:45 +00001012 def test_bufsize_is_none(self):
1013 # bufsize=None should be the same as bufsize=0.
1014 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1015 self.assertEqual(p.wait(), 0)
1016 # Again with keyword arg
1017 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1018 self.assertEqual(p.wait(), 0)
1019
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001020 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1021 # subprocess may deadlock with bufsize=1, see issue #21332
1022 with subprocess.Popen([sys.executable, "-c", "import sys;"
1023 "sys.stdout.write(sys.stdin.readline());"
1024 "sys.stdout.flush()"],
1025 stdin=subprocess.PIPE,
1026 stdout=subprocess.PIPE,
1027 stderr=subprocess.DEVNULL,
1028 bufsize=1,
1029 universal_newlines=universal_newlines) as p:
1030 p.stdin.write(line) # expect that it flushes the line in text mode
1031 os.close(p.stdin.fileno()) # close it without flushing the buffer
1032 read_line = p.stdout.readline()
1033 try:
1034 p.stdin.close()
1035 except OSError:
1036 pass
1037 p.stdin = None
1038 self.assertEqual(p.returncode, 0)
1039 self.assertEqual(read_line, expected)
1040
1041 def test_bufsize_equal_one_text_mode(self):
1042 # line is flushed in text mode with bufsize=1.
1043 # we should get the full line in return
1044 line = "line\n"
1045 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1046
1047 def test_bufsize_equal_one_binary_mode(self):
1048 # line is not flushed in binary mode with bufsize=1.
1049 # we should get empty response
1050 line = b'line' + os.linesep.encode() # assume ascii-based locale
1051 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1052
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001053 def test_leaking_fds_on_error(self):
1054 # see bug #5179: Popen leaks file descriptors to PIPEs if
1055 # the child fails to execute; this will eventually exhaust
1056 # the maximum number of open fds. 1024 seems a very common
1057 # value for that limit, but Windows has 2048, so we loop
1058 # 1024 times (each call leaked two fds).
1059 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001060 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001061 subprocess.Popen(['nonexisting_i_hope'],
1062 stdout=subprocess.PIPE,
1063 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001064 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001065 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001066 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001067
Antoine Pitroua8392712013-08-30 23:38:13 +02001068 @unittest.skipIf(threading is None, "threading required")
1069 def test_double_close_on_error(self):
1070 # Issue #18851
1071 fds = []
1072 def open_fds():
1073 for i in range(20):
1074 fds.extend(os.pipe())
1075 time.sleep(0.001)
1076 t = threading.Thread(target=open_fds)
1077 t.start()
1078 try:
1079 with self.assertRaises(EnvironmentError):
1080 subprocess.Popen(['nonexisting_i_hope'],
1081 stdin=subprocess.PIPE,
1082 stdout=subprocess.PIPE,
1083 stderr=subprocess.PIPE)
1084 finally:
1085 t.join()
1086 exc = None
1087 for fd in fds:
1088 # If a double close occurred, some of those fds will
1089 # already have been closed by mistake, and os.close()
1090 # here will raise.
1091 try:
1092 os.close(fd)
1093 except OSError as e:
1094 exc = e
1095 if exc is not None:
1096 raise exc
1097
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001098 @unittest.skipIf(threading is None, "threading required")
1099 def test_threadsafe_wait(self):
1100 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1101 proc = subprocess.Popen([sys.executable, '-c',
1102 'import time; time.sleep(12)'])
1103 self.assertEqual(proc.returncode, None)
1104 results = []
1105
1106 def kill_proc_timer_thread():
1107 results.append(('thread-start-poll-result', proc.poll()))
1108 # terminate it from the thread and wait for the result.
1109 proc.kill()
1110 proc.wait()
1111 results.append(('thread-after-kill-and-wait', proc.returncode))
1112 # this wait should be a no-op given the above.
1113 proc.wait()
1114 results.append(('thread-after-second-wait', proc.returncode))
1115
1116 # This is a timing sensitive test, the failure mode is
1117 # triggered when both the main thread and this thread are in
1118 # the wait() call at once. The delay here is to allow the
1119 # main thread to most likely be blocked in its wait() call.
1120 t = threading.Timer(0.2, kill_proc_timer_thread)
1121 t.start()
1122
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001123 if mswindows:
1124 expected_errorcode = 1
1125 else:
1126 # Should be -9 because of the proc.kill() from the thread.
1127 expected_errorcode = -9
1128
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001129 # Wait for the process to finish; the thread should kill it
1130 # long before it finishes on its own. Supplying a timeout
1131 # triggers a different code path for better coverage.
1132 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001133 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001134 msg="unexpected result in wait from main thread")
1135
1136 # This should be a no-op with no change in returncode.
1137 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001138 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001139 msg="unexpected result in second main wait.")
1140
1141 t.join()
1142 # Ensure that all of the thread results are as expected.
1143 # When a race condition occurs in wait(), the returncode could
1144 # be set by the wrong thread that doesn't actually have it
1145 # leading to an incorrect value.
1146 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001147 ('thread-after-kill-and-wait', expected_errorcode),
1148 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001149 results)
1150
Victor Stinnerb3693582010-05-21 20:13:12 +00001151 def test_issue8780(self):
1152 # Ensure that stdout is inherited from the parent
1153 # if stdout=PIPE is not used
1154 code = ';'.join((
1155 'import subprocess, sys',
1156 'retcode = subprocess.call('
1157 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1158 'assert retcode == 0'))
1159 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001160 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001161
Tim Goldenaf5ac392010-08-06 13:03:56 +00001162 def test_handles_closed_on_exception(self):
1163 # If CreateProcess exits with an error, ensure the
1164 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001165 ifhandle, ifname = tempfile.mkstemp()
1166 ofhandle, ofname = tempfile.mkstemp()
1167 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001168 try:
1169 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1170 stderr=efhandle)
1171 except OSError:
1172 os.close(ifhandle)
1173 os.remove(ifname)
1174 os.close(ofhandle)
1175 os.remove(ofname)
1176 os.close(efhandle)
1177 os.remove(efname)
1178 self.assertFalse(os.path.exists(ifname))
1179 self.assertFalse(os.path.exists(ofname))
1180 self.assertFalse(os.path.exists(efname))
1181
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001182 def test_communicate_epipe(self):
1183 # Issue 10963: communicate() should hide EPIPE
1184 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1185 stdin=subprocess.PIPE,
1186 stdout=subprocess.PIPE,
1187 stderr=subprocess.PIPE)
1188 self.addCleanup(p.stdout.close)
1189 self.addCleanup(p.stderr.close)
1190 self.addCleanup(p.stdin.close)
1191 p.communicate(b"x" * 2**20)
1192
1193 def test_communicate_epipe_only_stdin(self):
1194 # Issue 10963: communicate() should hide EPIPE
1195 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1196 stdin=subprocess.PIPE)
1197 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001198 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001199 p.communicate(b"x" * 2**20)
1200
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001201 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1202 "Requires signal.SIGUSR1")
1203 @unittest.skipUnless(hasattr(os, 'kill'),
1204 "Requires os.kill")
1205 @unittest.skipUnless(hasattr(os, 'getppid'),
1206 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001207 def test_communicate_eintr(self):
1208 # Issue #12493: communicate() should handle EINTR
1209 def handler(signum, frame):
1210 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001211 old_handler = signal.signal(signal.SIGUSR1, handler)
1212 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001213
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001214 args = [sys.executable, "-c",
1215 'import os, signal;'
1216 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001217 for stream in ('stdout', 'stderr'):
1218 kw = {stream: subprocess.PIPE}
1219 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001220 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001221 process.communicate()
1222
Tim Peterse718f612004-10-12 21:51:32 +00001223
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001224 # This test is Linux-ish specific for simplicity to at least have
1225 # some coverage. It is not a platform specific bug.
1226 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1227 "Linux specific")
1228 def test_failed_child_execute_fd_leak(self):
1229 """Test for the fork() failure fd leak reported in issue16327."""
1230 fd_directory = '/proc/%d/fd' % os.getpid()
1231 fds_before_popen = os.listdir(fd_directory)
1232 with self.assertRaises(PopenTestException):
1233 PopenExecuteChildRaises(
1234 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1235 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1236
1237 # NOTE: This test doesn't verify that the real _execute_child
1238 # does not close the file descriptors itself on the way out
1239 # during an exception. Code inspection has confirmed that.
1240
1241 fds_after_exception = os.listdir(fd_directory)
1242 self.assertEqual(fds_before_popen, fds_after_exception)
1243
Gregory P. Smith6e730002015-04-14 16:14:25 -07001244
1245class RunFuncTestCase(BaseTestCase):
1246 def run_python(self, code, **kwargs):
1247 """Run Python code in a subprocess using subprocess.run"""
1248 argv = [sys.executable, "-c", code]
1249 return subprocess.run(argv, **kwargs)
1250
1251 def test_returncode(self):
1252 # call() function with sequence argument
1253 cp = self.run_python("import sys; sys.exit(47)")
1254 self.assertEqual(cp.returncode, 47)
1255 with self.assertRaises(subprocess.CalledProcessError):
1256 cp.check_returncode()
1257
1258 def test_check(self):
1259 with self.assertRaises(subprocess.CalledProcessError) as c:
1260 self.run_python("import sys; sys.exit(47)", check=True)
1261 self.assertEqual(c.exception.returncode, 47)
1262
1263 def test_check_zero(self):
1264 # check_returncode shouldn't raise when returncode is zero
1265 cp = self.run_python("import sys; sys.exit(0)", check=True)
1266 self.assertEqual(cp.returncode, 0)
1267
1268 def test_timeout(self):
1269 # run() function with timeout argument; we want to test that the child
1270 # process gets killed when the timeout expires. If the child isn't
1271 # killed, this call will deadlock since subprocess.run waits for the
1272 # child.
1273 with self.assertRaises(subprocess.TimeoutExpired):
1274 self.run_python("while True: pass", timeout=0.0001)
1275
1276 def test_capture_stdout(self):
1277 # capture stdout with zero return code
1278 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1279 self.assertIn(b'BDFL', cp.stdout)
1280
1281 def test_capture_stderr(self):
1282 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1283 stderr=subprocess.PIPE)
1284 self.assertIn(b'BDFL', cp.stderr)
1285
1286 def test_check_output_stdin_arg(self):
1287 # run() can be called with stdin set to a file
1288 tf = tempfile.TemporaryFile()
1289 self.addCleanup(tf.close)
1290 tf.write(b'pear')
1291 tf.seek(0)
1292 cp = self.run_python(
1293 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1294 stdin=tf, stdout=subprocess.PIPE)
1295 self.assertIn(b'PEAR', cp.stdout)
1296
1297 def test_check_output_input_arg(self):
1298 # check_output() can be called with input set to a string
1299 cp = self.run_python(
1300 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1301 input=b'pear', stdout=subprocess.PIPE)
1302 self.assertIn(b'PEAR', cp.stdout)
1303
1304 def test_check_output_stdin_with_input_arg(self):
1305 # run() refuses to accept 'stdin' with 'input'
1306 tf = tempfile.TemporaryFile()
1307 self.addCleanup(tf.close)
1308 tf.write(b'pear')
1309 tf.seek(0)
1310 with self.assertRaises(ValueError,
1311 msg="Expected ValueError when stdin and input args supplied.") as c:
1312 output = self.run_python("print('will not be run')",
1313 stdin=tf, input=b'hare')
1314 self.assertIn('stdin', c.exception.args[0])
1315 self.assertIn('input', c.exception.args[0])
1316
1317 def test_check_output_timeout(self):
1318 with self.assertRaises(subprocess.TimeoutExpired) as c:
1319 cp = self.run_python((
1320 "import sys, time\n"
1321 "sys.stdout.write('BDFL')\n"
1322 "sys.stdout.flush()\n"
1323 "time.sleep(3600)"),
1324 # Some heavily loaded buildbots (sparc Debian 3.x) require
1325 # this much time to start and print.
1326 timeout=3, stdout=subprocess.PIPE)
1327 self.assertEqual(c.exception.output, b'BDFL')
1328 # output is aliased to stdout
1329 self.assertEqual(c.exception.stdout, b'BDFL')
1330
1331 def test_run_kwargs(self):
1332 newenv = os.environ.copy()
1333 newenv["FRUIT"] = "banana"
1334 cp = self.run_python(('import sys, os;'
1335 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1336 env=newenv)
1337 self.assertEqual(cp.returncode, 33)
1338
1339
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001340@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001341class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001342
Gregory P. Smith5591b022012-10-10 03:34:47 -07001343 def setUp(self):
1344 super().setUp()
1345 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1346
1347 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001348 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001349 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001350 except OSError as e:
1351 # This avoids hard coding the errno value or the OS perror()
1352 # string and instead capture the exception that we want to see
1353 # below for comparison.
1354 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001355 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001356 else:
Martin Pantereb995702016-07-28 01:11:04 +00001357 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001358 self._nonexistent_dir)
1359 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001360
Gregory P. Smith5591b022012-10-10 03:34:47 -07001361 def test_exception_cwd(self):
1362 """Test error in the child raised in the parent for a bad cwd."""
1363 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001364 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001365 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001366 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001367 except OSError as e:
1368 # Test that the child process chdir failure actually makes
1369 # it up to the parent process as the correct exception.
1370 self.assertEqual(desired_exception.errno, e.errno)
1371 self.assertEqual(desired_exception.strerror, e.strerror)
1372 else:
1373 self.fail("Expected OSError: %s" % desired_exception)
1374
Gregory P. Smith5591b022012-10-10 03:34:47 -07001375 def test_exception_bad_executable(self):
1376 """Test error in the child raised in the parent for a bad executable."""
1377 desired_exception = self._get_chdir_exception()
1378 try:
1379 p = subprocess.Popen([sys.executable, "-c", ""],
1380 executable=self._nonexistent_dir)
1381 except OSError as e:
1382 # Test that the child process exec failure actually makes
1383 # it up to the parent process as the correct exception.
1384 self.assertEqual(desired_exception.errno, e.errno)
1385 self.assertEqual(desired_exception.strerror, e.strerror)
1386 else:
1387 self.fail("Expected OSError: %s" % desired_exception)
1388
1389 def test_exception_bad_args_0(self):
1390 """Test error in the child raised in the parent for a bad args[0]."""
1391 desired_exception = self._get_chdir_exception()
1392 try:
1393 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1394 except OSError as e:
1395 # Test that the child process exec failure actually makes
1396 # it up to the parent process as the correct exception.
1397 self.assertEqual(desired_exception.errno, e.errno)
1398 self.assertEqual(desired_exception.strerror, e.strerror)
1399 else:
1400 self.fail("Expected OSError: %s" % desired_exception)
1401
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001402 def test_restore_signals(self):
1403 # Code coverage for both values of restore_signals to make sure it
1404 # at least does not blow up.
1405 # A test for behavior would be complex. Contributions welcome.
1406 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1407 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1408
1409 def test_start_new_session(self):
1410 # For code coverage of calling setsid(). We don't care if we get an
1411 # EPERM error from it depending on the test execution environment, that
1412 # still indicates that it was called.
1413 try:
1414 output = subprocess.check_output(
1415 [sys.executable, "-c",
1416 "import os; print(os.getpgid(os.getpid()))"],
1417 start_new_session=True)
1418 except OSError as e:
1419 if e.errno != errno.EPERM:
1420 raise
1421 else:
1422 parent_pgid = os.getpgid(os.getpid())
1423 child_pgid = int(output)
1424 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001425
1426 def test_run_abort(self):
1427 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001428 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001429 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001430 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001431 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001432 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001433
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001434 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001435 # DISCLAIMER: Setting environment variables is *not* a good use
1436 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001437 p = subprocess.Popen([sys.executable, "-c",
1438 'import sys,os;'
1439 'sys.stdout.write(os.getenv("FRUIT"))'],
1440 stdout=subprocess.PIPE,
1441 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001442 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001443 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001444
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001445 def test_preexec_exception(self):
1446 def raise_it():
1447 raise ValueError("What if two swallows carried a coconut?")
1448 try:
1449 p = subprocess.Popen([sys.executable, "-c", ""],
1450 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001451 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001452 self.assertTrue(
1453 subprocess._posixsubprocess,
1454 "Expected a ValueError from the preexec_fn")
1455 except ValueError as e:
1456 self.assertIn("coconut", e.args[0])
1457 else:
1458 self.fail("Exception raised by preexec_fn did not make it "
1459 "to the parent process.")
1460
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001461 class _TestExecuteChildPopen(subprocess.Popen):
1462 """Used to test behavior at the end of _execute_child."""
1463 def __init__(self, testcase, *args, **kwargs):
1464 self._testcase = testcase
1465 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001466
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001467 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001468 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001469 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001470 finally:
1471 # Open a bunch of file descriptors and verify that
1472 # none of them are the same as the ones the Popen
1473 # instance is using for stdin/stdout/stderr.
1474 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1475 for _ in range(8)]
1476 try:
1477 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001478 self._testcase.assertNotIn(
1479 fd, (self.stdin.fileno(), self.stdout.fileno(),
1480 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001481 msg="At least one fd was closed early.")
1482 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001483 for fd in devzero_fds:
1484 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001485
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001486 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1487 def test_preexec_errpipe_does_not_double_close_pipes(self):
1488 """Issue16140: Don't double close pipes on preexec error."""
1489
1490 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001491 raise subprocess.SubprocessError(
1492 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001493
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001494 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001495 self._TestExecuteChildPopen(
1496 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001497 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1498 stderr=subprocess.PIPE, preexec_fn=raise_it)
1499
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001500 def test_preexec_gc_module_failure(self):
1501 # This tests the code that disables garbage collection if the child
1502 # process will execute any Python.
1503 def raise_runtime_error():
1504 raise RuntimeError("this shouldn't escape")
1505 enabled = gc.isenabled()
1506 orig_gc_disable = gc.disable
1507 orig_gc_isenabled = gc.isenabled
1508 try:
1509 gc.disable()
1510 self.assertFalse(gc.isenabled())
1511 subprocess.call([sys.executable, '-c', ''],
1512 preexec_fn=lambda: None)
1513 self.assertFalse(gc.isenabled(),
1514 "Popen enabled gc when it shouldn't.")
1515
1516 gc.enable()
1517 self.assertTrue(gc.isenabled())
1518 subprocess.call([sys.executable, '-c', ''],
1519 preexec_fn=lambda: None)
1520 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1521
1522 gc.disable = raise_runtime_error
1523 self.assertRaises(RuntimeError, subprocess.Popen,
1524 [sys.executable, '-c', ''],
1525 preexec_fn=lambda: None)
1526
1527 del gc.isenabled # force an AttributeError
1528 self.assertRaises(AttributeError, subprocess.Popen,
1529 [sys.executable, '-c', ''],
1530 preexec_fn=lambda: None)
1531 finally:
1532 gc.disable = orig_gc_disable
1533 gc.isenabled = orig_gc_isenabled
1534 if not enabled:
1535 gc.disable()
1536
Martin Panterf7fdbda2015-12-05 09:51:52 +00001537 @unittest.skipIf(
1538 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001539 def test_preexec_fork_failure(self):
1540 # The internal code did not preserve the previous exception when
1541 # re-enabling garbage collection
1542 try:
1543 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1544 except ImportError as err:
1545 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1546 limits = getrlimit(RLIMIT_NPROC)
1547 [_, hard] = limits
1548 setrlimit(RLIMIT_NPROC, (0, hard))
1549 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001550 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001551 subprocess.call([sys.executable, '-c', ''],
1552 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001553 except BlockingIOError:
1554 # Forking should raise EAGAIN, translated to BlockingIOError
1555 pass
1556 else:
1557 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001558
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001559 def test_args_string(self):
1560 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001561 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001562 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001563 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001564 fobj.write("#!/bin/sh\n")
1565 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1566 sys.executable)
1567 os.chmod(fname, 0o700)
1568 p = subprocess.Popen(fname)
1569 p.wait()
1570 os.remove(fname)
1571 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001572
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001573 def test_invalid_args(self):
1574 # invalid arguments should raise ValueError
1575 self.assertRaises(ValueError, subprocess.call,
1576 [sys.executable, "-c",
1577 "import sys; sys.exit(47)"],
1578 startupinfo=47)
1579 self.assertRaises(ValueError, subprocess.call,
1580 [sys.executable, "-c",
1581 "import sys; sys.exit(47)"],
1582 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001583
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001584 def test_shell_sequence(self):
1585 # Run command through the shell (sequence)
1586 newenv = os.environ.copy()
1587 newenv["FRUIT"] = "apple"
1588 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1589 stdout=subprocess.PIPE,
1590 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001591 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001592 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001593
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001594 def test_shell_string(self):
1595 # Run command through the shell (string)
1596 newenv = os.environ.copy()
1597 newenv["FRUIT"] = "apple"
1598 p = subprocess.Popen("echo $FRUIT", shell=1,
1599 stdout=subprocess.PIPE,
1600 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001601 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001602 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001603
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001604 def test_call_string(self):
1605 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001606 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001607 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001608 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001609 fobj.write("#!/bin/sh\n")
1610 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1611 sys.executable)
1612 os.chmod(fname, 0o700)
1613 rc = subprocess.call(fname)
1614 os.remove(fname)
1615 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001616
Stefan Krah9542cc62010-07-19 14:20:53 +00001617 def test_specific_shell(self):
1618 # Issue #9265: Incorrect name passed as arg[0].
1619 shells = []
1620 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1621 for name in ['bash', 'ksh']:
1622 sh = os.path.join(prefix, name)
1623 if os.path.isfile(sh):
1624 shells.append(sh)
1625 if not shells: # Will probably work for any shell but csh.
1626 self.skipTest("bash or ksh required for this test")
1627 sh = '/bin/sh'
1628 if os.path.isfile(sh) and not os.path.islink(sh):
1629 # Test will fail if /bin/sh is a symlink to csh.
1630 shells.append(sh)
1631 for sh in shells:
1632 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1633 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001634 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001635 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1636
Florent Xicluna4886d242010-03-08 13:27:26 +00001637 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001638 # Do not inherit file handles from the parent.
1639 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001640 # Also set the SIGINT handler to the default to make sure it's not
1641 # being ignored (some tests rely on that.)
1642 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1643 try:
1644 p = subprocess.Popen([sys.executable, "-c", """if 1:
1645 import sys, time
1646 sys.stdout.write('x\\n')
1647 sys.stdout.flush()
1648 time.sleep(30)
1649 """],
1650 close_fds=True,
1651 stdin=subprocess.PIPE,
1652 stdout=subprocess.PIPE,
1653 stderr=subprocess.PIPE)
1654 finally:
1655 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001656 # Wait for the interpreter to be completely initialized before
1657 # sending any signal.
1658 p.stdout.read(1)
1659 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001660 return p
1661
Charles-François Natali53221e32013-01-12 16:52:20 +01001662 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1663 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001664 def _kill_dead_process(self, method, *args):
1665 # Do not inherit file handles from the parent.
1666 # It should fix failures on some platforms.
1667 p = subprocess.Popen([sys.executable, "-c", """if 1:
1668 import sys, time
1669 sys.stdout.write('x\\n')
1670 sys.stdout.flush()
1671 """],
1672 close_fds=True,
1673 stdin=subprocess.PIPE,
1674 stdout=subprocess.PIPE,
1675 stderr=subprocess.PIPE)
1676 # Wait for the interpreter to be completely initialized before
1677 # sending any signal.
1678 p.stdout.read(1)
1679 # The process should end after this
1680 time.sleep(1)
1681 # This shouldn't raise even though the child is now dead
1682 getattr(p, method)(*args)
1683 p.communicate()
1684
Florent Xicluna4886d242010-03-08 13:27:26 +00001685 def test_send_signal(self):
1686 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001687 _, stderr = p.communicate()
1688 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001689 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001690
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001691 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001692 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001693 _, stderr = p.communicate()
1694 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001695 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001696
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001697 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001698 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001699 _, stderr = p.communicate()
1700 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001701 self.assertEqual(p.wait(), -signal.SIGTERM)
1702
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001703 def test_send_signal_dead(self):
1704 # Sending a signal to a dead process
1705 self._kill_dead_process('send_signal', signal.SIGINT)
1706
1707 def test_kill_dead(self):
1708 # Killing a dead process
1709 self._kill_dead_process('kill')
1710
1711 def test_terminate_dead(self):
1712 # Terminating a dead process
1713 self._kill_dead_process('terminate')
1714
Victor Stinnerdaf45552013-08-28 00:53:59 +02001715 def _save_fds(self, save_fds):
1716 fds = []
1717 for fd in save_fds:
1718 inheritable = os.get_inheritable(fd)
1719 saved = os.dup(fd)
1720 fds.append((fd, saved, inheritable))
1721 return fds
1722
1723 def _restore_fds(self, fds):
1724 for fd, saved, inheritable in fds:
1725 os.dup2(saved, fd, inheritable=inheritable)
1726 os.close(saved)
1727
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001728 def check_close_std_fds(self, fds):
1729 # Issue #9905: test that subprocess pipes still work properly with
1730 # some standard fds closed
1731 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001732 saved_fds = self._save_fds(fds)
1733 for fd, saved, inheritable in saved_fds:
1734 if fd == 0:
1735 stdin = saved
1736 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001737 try:
1738 for fd in fds:
1739 os.close(fd)
1740 out, err = subprocess.Popen([sys.executable, "-c",
1741 'import sys;'
1742 'sys.stdout.write("apple");'
1743 'sys.stdout.flush();'
1744 'sys.stderr.write("orange")'],
1745 stdin=stdin,
1746 stdout=subprocess.PIPE,
1747 stderr=subprocess.PIPE).communicate()
1748 err = support.strip_python_stderr(err)
1749 self.assertEqual((out, err), (b'apple', b'orange'))
1750 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001751 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001752
1753 def test_close_fd_0(self):
1754 self.check_close_std_fds([0])
1755
1756 def test_close_fd_1(self):
1757 self.check_close_std_fds([1])
1758
1759 def test_close_fd_2(self):
1760 self.check_close_std_fds([2])
1761
1762 def test_close_fds_0_1(self):
1763 self.check_close_std_fds([0, 1])
1764
1765 def test_close_fds_0_2(self):
1766 self.check_close_std_fds([0, 2])
1767
1768 def test_close_fds_1_2(self):
1769 self.check_close_std_fds([1, 2])
1770
1771 def test_close_fds_0_1_2(self):
1772 # Issue #10806: test that subprocess pipes still work properly with
1773 # all standard fds closed.
1774 self.check_close_std_fds([0, 1, 2])
1775
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001776 def test_small_errpipe_write_fd(self):
1777 """Issue #15798: Popen should work when stdio fds are available."""
1778 new_stdin = os.dup(0)
1779 new_stdout = os.dup(1)
1780 try:
1781 os.close(0)
1782 os.close(1)
1783
1784 # Side test: if errpipe_write fails to have its CLOEXEC
1785 # flag set this should cause the parent to think the exec
1786 # failed. Extremely unlikely: everyone supports CLOEXEC.
1787 subprocess.Popen([
1788 sys.executable, "-c",
1789 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1790 finally:
1791 # Restore original stdin and stdout
1792 os.dup2(new_stdin, 0)
1793 os.dup2(new_stdout, 1)
1794 os.close(new_stdin)
1795 os.close(new_stdout)
1796
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001797 def test_remapping_std_fds(self):
1798 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001799 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001800 try:
1801 temp_fds = [fd for fd, fname in temps]
1802
1803 # unlink the files -- we won't need to reopen them
1804 for fd, fname in temps:
1805 os.unlink(fname)
1806
1807 # write some data to what will become stdin, and rewind
1808 os.write(temp_fds[1], b"STDIN")
1809 os.lseek(temp_fds[1], 0, 0)
1810
1811 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001812 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001813 try:
1814 # duplicate the file objects over the standard fd's
1815 for fd, temp_fd in enumerate(temp_fds):
1816 os.dup2(temp_fd, fd)
1817
1818 # now use those files in the "wrong" order, so that subprocess
1819 # has to rearrange them in the child
1820 p = subprocess.Popen([sys.executable, "-c",
1821 'import sys; got = sys.stdin.read();'
1822 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1823 stdin=temp_fds[1],
1824 stdout=temp_fds[2],
1825 stderr=temp_fds[0])
1826 p.wait()
1827 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001828 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001829
1830 for fd in temp_fds:
1831 os.lseek(fd, 0, 0)
1832
1833 out = os.read(temp_fds[2], 1024)
1834 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1835 self.assertEqual(out, b"got STDIN")
1836 self.assertEqual(err, b"err")
1837
1838 finally:
1839 for fd in temp_fds:
1840 os.close(fd)
1841
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001842 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1843 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001844 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001845 temp_fds = [fd for fd, fname in temps]
1846 try:
1847 # unlink the files -- we won't need to reopen them
1848 for fd, fname in temps:
1849 os.unlink(fname)
1850
1851 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001852 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001853 try:
1854 # duplicate the temp files over the standard fd's 0, 1, 2
1855 for fd, temp_fd in enumerate(temp_fds):
1856 os.dup2(temp_fd, fd)
1857
1858 # write some data to what will become stdin, and rewind
1859 os.write(stdin_no, b"STDIN")
1860 os.lseek(stdin_no, 0, 0)
1861
1862 # now use those files in the given order, so that subprocess
1863 # has to rearrange them in the child
1864 p = subprocess.Popen([sys.executable, "-c",
1865 'import sys; got = sys.stdin.read();'
1866 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1867 stdin=stdin_no,
1868 stdout=stdout_no,
1869 stderr=stderr_no)
1870 p.wait()
1871
1872 for fd in temp_fds:
1873 os.lseek(fd, 0, 0)
1874
1875 out = os.read(stdout_no, 1024)
1876 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1877 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001878 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001879
1880 self.assertEqual(out, b"got STDIN")
1881 self.assertEqual(err, b"err")
1882
1883 finally:
1884 for fd in temp_fds:
1885 os.close(fd)
1886
1887 # When duping fds, if there arises a situation where one of the fds is
1888 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1889 # This tests all combinations of this.
1890 def test_swap_fds(self):
1891 self.check_swap_fds(0, 1, 2)
1892 self.check_swap_fds(0, 2, 1)
1893 self.check_swap_fds(1, 0, 2)
1894 self.check_swap_fds(1, 2, 0)
1895 self.check_swap_fds(2, 0, 1)
1896 self.check_swap_fds(2, 1, 0)
1897
Victor Stinner13bb71c2010-04-23 21:41:56 +00001898 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001899 def prepare():
1900 raise ValueError("surrogate:\uDCff")
1901
1902 try:
1903 subprocess.call(
1904 [sys.executable, "-c", "pass"],
1905 preexec_fn=prepare)
1906 except ValueError as err:
1907 # Pure Python implementations keeps the message
1908 self.assertIsNone(subprocess._posixsubprocess)
1909 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001910 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001911 # _posixsubprocess uses a default message
1912 self.assertIsNotNone(subprocess._posixsubprocess)
1913 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1914 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001915 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001916
Victor Stinner13bb71c2010-04-23 21:41:56 +00001917 def test_undecodable_env(self):
1918 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01001919 encoded_value = value.encode("ascii", "surrogateescape")
1920
Victor Stinner13bb71c2010-04-23 21:41:56 +00001921 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001922 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001923 env = os.environ.copy()
1924 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01001925 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00001926 # surrogate-escaping of \xFF in the child process; otherwise it can
1927 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001928 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01001929 if sys.platform.startswith("aix"):
1930 # On AIX, the C locale uses the Latin1 encoding
1931 decoded_value = encoded_value.decode("latin1", "surrogateescape")
1932 else:
1933 # On other UNIXes, the C locale uses the ASCII encoding
1934 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001935 stdout = subprocess.check_output(
1936 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001937 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001938 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001939 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001940
1941 # test bytes
1942 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001943 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001944 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01001945 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001946 stdout = subprocess.check_output(
1947 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001948 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001949 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001950 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001951
Victor Stinnerb745a742010-05-18 17:17:23 +00001952 def test_bytes_program(self):
1953 abs_program = os.fsencode(sys.executable)
1954 path, program = os.path.split(sys.executable)
1955 program = os.fsencode(program)
1956
1957 # absolute bytes path
1958 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001959 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001960
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001961 # absolute bytes path as a string
1962 cmd = b"'" + abs_program + b"' -c pass"
1963 exitcode = subprocess.call(cmd, shell=True)
1964 self.assertEqual(exitcode, 0)
1965
Victor Stinnerb745a742010-05-18 17:17:23 +00001966 # bytes program, unicode PATH
1967 env = os.environ.copy()
1968 env["PATH"] = path
1969 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001970 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001971
1972 # bytes program, bytes PATH
1973 envb = os.environb.copy()
1974 envb[b"PATH"] = os.fsencode(path)
1975 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001976 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001977
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001978 def test_pipe_cloexec(self):
1979 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1980 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1981
1982 p1 = subprocess.Popen([sys.executable, sleeper],
1983 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1984 stderr=subprocess.PIPE, close_fds=False)
1985
1986 self.addCleanup(p1.communicate, b'')
1987
1988 p2 = subprocess.Popen([sys.executable, fd_status],
1989 stdout=subprocess.PIPE, close_fds=False)
1990
1991 output, error = p2.communicate()
1992 result_fds = set(map(int, output.split(b',')))
1993 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1994 p1.stderr.fileno()])
1995
1996 self.assertFalse(result_fds & unwanted_fds,
1997 "Expected no fds from %r to be open in child, "
1998 "found %r" %
1999 (unwanted_fds, result_fds & unwanted_fds))
2000
2001 def test_pipe_cloexec_real_tools(self):
2002 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2003 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2004
2005 subdata = b'zxcvbn'
2006 data = subdata * 4 + b'\n'
2007
2008 p1 = subprocess.Popen([sys.executable, qcat],
2009 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2010 close_fds=False)
2011
2012 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2013 stdin=p1.stdout, stdout=subprocess.PIPE,
2014 close_fds=False)
2015
2016 self.addCleanup(p1.wait)
2017 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002018 def kill_p1():
2019 try:
2020 p1.terminate()
2021 except ProcessLookupError:
2022 pass
2023 def kill_p2():
2024 try:
2025 p2.terminate()
2026 except ProcessLookupError:
2027 pass
2028 self.addCleanup(kill_p1)
2029 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002030
2031 p1.stdin.write(data)
2032 p1.stdin.close()
2033
2034 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2035
2036 self.assertTrue(readfiles, "The child hung")
2037 self.assertEqual(p2.stdout.read(), data)
2038
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002039 p1.stdout.close()
2040 p2.stdout.close()
2041
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002042 def test_close_fds(self):
2043 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2044
2045 fds = os.pipe()
2046 self.addCleanup(os.close, fds[0])
2047 self.addCleanup(os.close, fds[1])
2048
2049 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002050 # add a bunch more fds
2051 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002052 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002053 self.addCleanup(os.close, fd)
2054 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002055
Victor Stinnerdaf45552013-08-28 00:53:59 +02002056 for fd in open_fds:
2057 os.set_inheritable(fd, True)
2058
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002059 p = subprocess.Popen([sys.executable, fd_status],
2060 stdout=subprocess.PIPE, close_fds=False)
2061 output, ignored = p.communicate()
2062 remaining_fds = set(map(int, output.split(b',')))
2063
2064 self.assertEqual(remaining_fds & open_fds, open_fds,
2065 "Some fds were closed")
2066
2067 p = subprocess.Popen([sys.executable, fd_status],
2068 stdout=subprocess.PIPE, close_fds=True)
2069 output, ignored = p.communicate()
2070 remaining_fds = set(map(int, output.split(b',')))
2071
2072 self.assertFalse(remaining_fds & open_fds,
2073 "Some fds were left open")
2074 self.assertIn(1, remaining_fds, "Subprocess failed")
2075
Gregory P. Smith8facece2012-01-21 14:01:08 -08002076 # Keep some of the fd's we opened open in the subprocess.
2077 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2078 fds_to_keep = set(open_fds.pop() for _ in range(8))
2079 p = subprocess.Popen([sys.executable, fd_status],
2080 stdout=subprocess.PIPE, close_fds=True,
2081 pass_fds=())
2082 output, ignored = p.communicate()
2083 remaining_fds = set(map(int, output.split(b',')))
2084
2085 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2086 "Some fds not in pass_fds were left open")
2087 self.assertIn(1, remaining_fds, "Subprocess failed")
2088
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002089
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002090 @unittest.skipIf(sys.platform.startswith("freebsd") and
2091 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2092 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002093 def test_close_fds_when_max_fd_is_lowered(self):
2094 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2095 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2096
Gregory P. Smith634aa682014-06-15 17:51:04 -07002097 # This launches the meat of the test in a child process to
2098 # avoid messing with the larger unittest processes maximum
2099 # number of file descriptors.
2100 # This process launches:
2101 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2102 # a bunch of high open fds above the new lower rlimit.
2103 # Those are reported via stdout before launching a new
2104 # process with close_fds=False to run the actual test:
2105 # +--> The TEST: This one launches a fd_status.py
2106 # subprocess with close_fds=True so we can find out if
2107 # any of the fds above the lowered rlimit are still open.
2108 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2109 '''
2110 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002111 open_fds = set()
2112 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002113 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002114 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002115 open_fds.add(fd)
2116
2117 # Leave a two pairs of low ones available for use by the
2118 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002119 # We also leave 10 more open as some Python buildbots run into
2120 # "too many open files" errors during the test if we do not.
2121 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002122 os.close(fd)
2123 open_fds.remove(fd)
2124
2125 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002126 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002127 os.set_inheritable(fd, True)
2128
2129 max_fd_open = max(open_fds)
2130
Gregory P. Smith634aa682014-06-15 17:51:04 -07002131 # Communicate the open_fds to the parent unittest.TestCase process.
2132 print(','.join(map(str, sorted(open_fds))))
2133 sys.stdout.flush()
2134
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002135 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2136 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002137 # 29 is lower than the highest fds we are leaving open.
2138 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002139 # Launch a new Python interpreter with our low fd rlim_cur that
2140 # inherits open fds above that limit. It then uses subprocess
2141 # with close_fds=True to get a report of open fds in the child.
2142 # An explicit list of fds to check is passed to fd_status.py as
2143 # letting fd_status rely on its default logic would miss the
2144 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002145 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002146 [sys.executable, '-c',
2147 textwrap.dedent("""
2148 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002149 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002150 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002151 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002152 """.format(max_fd=max_fd_open+1))],
2153 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002154 finally:
2155 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002156 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002157
2158 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002159 output_lines = output.splitlines()
2160 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002161 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002162 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2163 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002164
Gregory P. Smith634aa682014-06-15 17:51:04 -07002165 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002166 msg="Some fds were left open.")
2167
2168
Victor Stinner88701e22011-06-01 13:13:04 +02002169 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2170 # descriptor of a pipe closed in the parent process is valid in the
2171 # child process according to fstat(), but the mode of the file
2172 # descriptor is invalid, and read or write raise an error.
2173 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002174 def test_pass_fds(self):
2175 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2176
2177 open_fds = set()
2178
2179 for x in range(5):
2180 fds = os.pipe()
2181 self.addCleanup(os.close, fds[0])
2182 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002183 os.set_inheritable(fds[0], True)
2184 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002185 open_fds.update(fds)
2186
2187 for fd in open_fds:
2188 p = subprocess.Popen([sys.executable, fd_status],
2189 stdout=subprocess.PIPE, close_fds=True,
2190 pass_fds=(fd, ))
2191 output, ignored = p.communicate()
2192
2193 remaining_fds = set(map(int, output.split(b',')))
2194 to_be_closed = open_fds - {fd}
2195
2196 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2197 self.assertFalse(remaining_fds & to_be_closed,
2198 "fd to be closed passed")
2199
2200 # pass_fds overrides close_fds with a warning.
2201 with self.assertWarns(RuntimeWarning) as context:
2202 self.assertFalse(subprocess.call(
2203 [sys.executable, "-c", "import sys; sys.exit(0)"],
2204 close_fds=False, pass_fds=(fd, )))
2205 self.assertIn('overriding close_fds', str(context.warning))
2206
Victor Stinnerdaf45552013-08-28 00:53:59 +02002207 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002208 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002209
2210 inheritable, non_inheritable = os.pipe()
2211 self.addCleanup(os.close, inheritable)
2212 self.addCleanup(os.close, non_inheritable)
2213 os.set_inheritable(inheritable, True)
2214 os.set_inheritable(non_inheritable, False)
2215 pass_fds = (inheritable, non_inheritable)
2216 args = [sys.executable, script]
2217 args += list(map(str, pass_fds))
2218
2219 p = subprocess.Popen(args,
2220 stdout=subprocess.PIPE, close_fds=True,
2221 pass_fds=pass_fds)
2222 output, ignored = p.communicate()
2223 fds = set(map(int, output.split(b',')))
2224
2225 # the inheritable file descriptor must be inherited, so its inheritable
2226 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002227 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002228
2229 # inheritable flag must not be changed in the parent process
2230 self.assertEqual(os.get_inheritable(inheritable), True)
2231 self.assertEqual(os.get_inheritable(non_inheritable), False)
2232
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002233 def test_stdout_stdin_are_single_inout_fd(self):
2234 with io.open(os.devnull, "r+") as inout:
2235 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2236 stdout=inout, stdin=inout)
2237 p.wait()
2238
2239 def test_stdout_stderr_are_single_inout_fd(self):
2240 with io.open(os.devnull, "r+") as inout:
2241 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2242 stdout=inout, stderr=inout)
2243 p.wait()
2244
2245 def test_stderr_stdin_are_single_inout_fd(self):
2246 with io.open(os.devnull, "r+") as inout:
2247 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2248 stderr=inout, stdin=inout)
2249 p.wait()
2250
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002251 def test_wait_when_sigchild_ignored(self):
2252 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2253 sigchild_ignore = support.findfile("sigchild_ignore.py",
2254 subdir="subprocessdata")
2255 p = subprocess.Popen([sys.executable, sigchild_ignore],
2256 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2257 stdout, stderr = p.communicate()
2258 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002259 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002260 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002261
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002262 def test_select_unbuffered(self):
2263 # Issue #11459: bufsize=0 should really set the pipes as
2264 # unbuffered (and therefore let select() work properly).
2265 select = support.import_module("select")
2266 p = subprocess.Popen([sys.executable, "-c",
2267 'import sys;'
2268 'sys.stdout.write("apple")'],
2269 stdout=subprocess.PIPE,
2270 bufsize=0)
2271 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002272 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002273 try:
2274 self.assertEqual(f.read(4), b"appl")
2275 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2276 finally:
2277 p.wait()
2278
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002279 def test_zombie_fast_process_del(self):
2280 # Issue #12650: on Unix, if Popen.__del__() was called before the
2281 # process exited, it wouldn't be added to subprocess._active, and would
2282 # remain a zombie.
2283 # spawn a Popen, and delete its reference before it exits
2284 p = subprocess.Popen([sys.executable, "-c",
2285 'import sys, time;'
2286 'time.sleep(0.2)'],
2287 stdout=subprocess.PIPE,
2288 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002289 self.addCleanup(p.stdout.close)
2290 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002291 ident = id(p)
2292 pid = p.pid
2293 del p
2294 # check that p is in the active processes list
2295 self.assertIn(ident, [id(o) for o in subprocess._active])
2296
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002297 def test_leak_fast_process_del_killed(self):
2298 # Issue #12650: on Unix, if Popen.__del__() was called before the
2299 # process exited, and the process got killed by a signal, it would never
2300 # be removed from subprocess._active, which triggered a FD and memory
2301 # leak.
2302 # spawn a Popen, delete its reference and kill it
2303 p = subprocess.Popen([sys.executable, "-c",
2304 'import time;'
2305 'time.sleep(3)'],
2306 stdout=subprocess.PIPE,
2307 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002308 self.addCleanup(p.stdout.close)
2309 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002310 ident = id(p)
2311 pid = p.pid
2312 del p
2313 os.kill(pid, signal.SIGKILL)
2314 # check that p is in the active processes list
2315 self.assertIn(ident, [id(o) for o in subprocess._active])
2316
2317 # let some time for the process to exit, and create a new Popen: this
2318 # should trigger the wait() of p
2319 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002320 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002321 with subprocess.Popen(['nonexisting_i_hope'],
2322 stdout=subprocess.PIPE,
2323 stderr=subprocess.PIPE) as proc:
2324 pass
2325 # p should have been wait()ed on, and removed from the _active list
2326 self.assertRaises(OSError, os.waitpid, pid, 0)
2327 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2328
Charles-François Natali249cdc32013-08-25 18:24:45 +02002329 def test_close_fds_after_preexec(self):
2330 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2331
2332 # this FD is used as dup2() target by preexec_fn, and should be closed
2333 # in the child process
2334 fd = os.dup(1)
2335 self.addCleanup(os.close, fd)
2336
2337 p = subprocess.Popen([sys.executable, fd_status],
2338 stdout=subprocess.PIPE, close_fds=True,
2339 preexec_fn=lambda: os.dup2(1, fd))
2340 output, ignored = p.communicate()
2341
2342 remaining_fds = set(map(int, output.split(b',')))
2343
2344 self.assertNotIn(fd, remaining_fds)
2345
Victor Stinner8f437aa2014-10-05 17:25:19 +02002346 @support.cpython_only
2347 def test_fork_exec(self):
2348 # Issue #22290: fork_exec() must not crash on memory allocation failure
2349 # or other errors
2350 import _posixsubprocess
2351 gc_enabled = gc.isenabled()
2352 try:
2353 # Use a preexec function and enable the garbage collector
2354 # to force fork_exec() to re-enable the garbage collector
2355 # on error.
2356 func = lambda: None
2357 gc.enable()
2358
Victor Stinner8f437aa2014-10-05 17:25:19 +02002359 for args, exe_list, cwd, env_list in (
2360 (123, [b"exe"], None, [b"env"]),
2361 ([b"arg"], 123, None, [b"env"]),
2362 ([b"arg"], [b"exe"], 123, [b"env"]),
2363 ([b"arg"], [b"exe"], None, 123),
2364 ):
2365 with self.assertRaises(TypeError):
2366 _posixsubprocess.fork_exec(
2367 args, exe_list,
2368 True, [], cwd, env_list,
2369 -1, -1, -1, -1,
2370 1, 2, 3, 4,
2371 True, True, func)
2372 finally:
2373 if not gc_enabled:
2374 gc.disable()
2375
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002376 @support.cpython_only
2377 def test_fork_exec_sorted_fd_sanity_check(self):
2378 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2379 import _posixsubprocess
2380 gc_enabled = gc.isenabled()
2381 try:
2382 gc.enable()
2383
2384 for fds_to_keep in (
2385 (-1, 2, 3, 4, 5), # Negative number.
2386 ('str', 4), # Not an int.
2387 (18, 23, 42, 2**63), # Out of range.
2388 (5, 4), # Not sorted.
2389 (6, 7, 7, 8), # Duplicate.
2390 ):
2391 with self.assertRaises(
2392 ValueError,
2393 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2394 _posixsubprocess.fork_exec(
2395 [b"false"], [b"false"],
2396 True, fds_to_keep, None, [b"env"],
2397 -1, -1, -1, -1,
2398 1, 2, 3, 4,
2399 True, True, None)
2400 self.assertIn('fds_to_keep', str(c.exception))
2401 finally:
2402 if not gc_enabled:
2403 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002404
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002405 def test_communicate_BrokenPipeError_stdin_close(self):
2406 # By not setting stdout or stderr or a timeout we force the fast path
2407 # that just calls _stdin_write() internally due to our mock.
2408 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2409 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2410 mock_proc_stdin.close.side_effect = BrokenPipeError
2411 proc.communicate() # Should swallow BrokenPipeError from close.
2412 mock_proc_stdin.close.assert_called_with()
2413
2414 def test_communicate_BrokenPipeError_stdin_write(self):
2415 # By not setting stdout or stderr or a timeout we force the fast path
2416 # that just calls _stdin_write() internally due to our mock.
2417 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2418 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2419 mock_proc_stdin.write.side_effect = BrokenPipeError
2420 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2421 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2422 mock_proc_stdin.close.assert_called_once_with()
2423
2424 def test_communicate_BrokenPipeError_stdin_flush(self):
2425 # Setting stdin and stdout forces the ._communicate() code path.
2426 # python -h exits faster than python -c pass (but spams stdout).
2427 proc = subprocess.Popen([sys.executable, '-h'],
2428 stdin=subprocess.PIPE,
2429 stdout=subprocess.PIPE)
2430 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2431 open(os.devnull, 'wb') as dev_null:
2432 mock_proc_stdin.flush.side_effect = BrokenPipeError
2433 # because _communicate registers a selector using proc.stdin...
2434 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2435 # _communicate() should swallow BrokenPipeError from flush.
2436 proc.communicate(b'stuff')
2437 mock_proc_stdin.flush.assert_called_once_with()
2438
2439 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2440 # Setting stdin and stdout forces the ._communicate() code path.
2441 # python -h exits faster than python -c pass (but spams stdout).
2442 proc = subprocess.Popen([sys.executable, '-h'],
2443 stdin=subprocess.PIPE,
2444 stdout=subprocess.PIPE)
2445 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2446 mock_proc_stdin.close.side_effect = BrokenPipeError
2447 # _communicate() should swallow BrokenPipeError from close.
2448 proc.communicate(timeout=999)
2449 mock_proc_stdin.close.assert_called_once_with()
2450
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002451
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002452@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002453class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002454
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002455 def test_startupinfo(self):
2456 # startupinfo argument
2457 # We uses hardcoded constants, because we do not want to
2458 # depend on win32all.
2459 STARTF_USESHOWWINDOW = 1
2460 SW_MAXIMIZE = 3
2461 startupinfo = subprocess.STARTUPINFO()
2462 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2463 startupinfo.wShowWindow = SW_MAXIMIZE
2464 # Since Python is a console process, it won't be affected
2465 # by wShowWindow, but the argument should be silently
2466 # ignored
2467 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002468 startupinfo=startupinfo)
2469
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002470 def test_creationflags(self):
2471 # creationflags argument
2472 CREATE_NEW_CONSOLE = 16
2473 sys.stderr.write(" a DOS box should flash briefly ...\n")
2474 subprocess.call(sys.executable +
2475 ' -c "import time; time.sleep(0.25)"',
2476 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002477
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002478 def test_invalid_args(self):
2479 # invalid arguments should raise ValueError
2480 self.assertRaises(ValueError, subprocess.call,
2481 [sys.executable, "-c",
2482 "import sys; sys.exit(47)"],
2483 preexec_fn=lambda: 1)
2484 self.assertRaises(ValueError, subprocess.call,
2485 [sys.executable, "-c",
2486 "import sys; sys.exit(47)"],
2487 stdout=subprocess.PIPE,
2488 close_fds=True)
2489
2490 def test_close_fds(self):
2491 # close file descriptors
2492 rc = subprocess.call([sys.executable, "-c",
2493 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002494 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002495 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002496
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002497 def test_shell_sequence(self):
2498 # Run command through the shell (sequence)
2499 newenv = os.environ.copy()
2500 newenv["FRUIT"] = "physalis"
2501 p = subprocess.Popen(["set"], shell=1,
2502 stdout=subprocess.PIPE,
2503 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002504 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002505 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002506
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002507 def test_shell_string(self):
2508 # Run command through the shell (string)
2509 newenv = os.environ.copy()
2510 newenv["FRUIT"] = "physalis"
2511 p = subprocess.Popen("set", shell=1,
2512 stdout=subprocess.PIPE,
2513 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002514 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002515 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002516
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002517 def test_call_string(self):
2518 # call() function with string argument on Windows
2519 rc = subprocess.call(sys.executable +
2520 ' -c "import sys; sys.exit(47)"')
2521 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002522
Florent Xicluna4886d242010-03-08 13:27:26 +00002523 def _kill_process(self, method, *args):
2524 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002525 p = subprocess.Popen([sys.executable, "-c", """if 1:
2526 import sys, time
2527 sys.stdout.write('x\\n')
2528 sys.stdout.flush()
2529 time.sleep(30)
2530 """],
2531 stdin=subprocess.PIPE,
2532 stdout=subprocess.PIPE,
2533 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00002534 self.addCleanup(p.stdout.close)
2535 self.addCleanup(p.stderr.close)
2536 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00002537 # Wait for the interpreter to be completely initialized before
2538 # sending any signal.
2539 p.stdout.read(1)
2540 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00002541 _, stderr = p.communicate()
2542 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00002543 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002544 self.assertNotEqual(returncode, 0)
2545
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002546 def _kill_dead_process(self, method, *args):
2547 p = subprocess.Popen([sys.executable, "-c", """if 1:
2548 import sys, time
2549 sys.stdout.write('x\\n')
2550 sys.stdout.flush()
2551 sys.exit(42)
2552 """],
2553 stdin=subprocess.PIPE,
2554 stdout=subprocess.PIPE,
2555 stderr=subprocess.PIPE)
2556 self.addCleanup(p.stdout.close)
2557 self.addCleanup(p.stderr.close)
2558 self.addCleanup(p.stdin.close)
2559 # Wait for the interpreter to be completely initialized before
2560 # sending any signal.
2561 p.stdout.read(1)
2562 # The process should end after this
2563 time.sleep(1)
2564 # This shouldn't raise even though the child is now dead
2565 getattr(p, method)(*args)
2566 _, stderr = p.communicate()
2567 self.assertStderrEqual(stderr, b'')
2568 rc = p.wait()
2569 self.assertEqual(rc, 42)
2570
Florent Xicluna4886d242010-03-08 13:27:26 +00002571 def test_send_signal(self):
2572 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002573
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002574 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002575 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002576
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002577 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002578 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002579
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002580 def test_send_signal_dead(self):
2581 self._kill_dead_process('send_signal', signal.SIGTERM)
2582
2583 def test_kill_dead(self):
2584 self._kill_dead_process('kill')
2585
2586 def test_terminate_dead(self):
2587 self._kill_dead_process('terminate')
2588
Martin Panter23172bd2016-04-16 11:28:10 +00002589class MiscTests(unittest.TestCase):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002590 def test_getoutput(self):
2591 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2592 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2593 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002594
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002595 # we use mkdtemp in the next line to create an empty directory
2596 # under our exclusive control; from that, we can invent a pathname
2597 # that we _know_ won't exist. This is guaranteed to fail.
2598 dir = None
2599 try:
2600 dir = tempfile.mkdtemp()
2601 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002602 status, output = subprocess.getstatusoutput(
2603 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002604 self.assertNotEqual(status, 0)
2605 finally:
2606 if dir is not None:
2607 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002608
Gregory P. Smithace55862015-04-07 15:57:54 -07002609 def test__all__(self):
2610 """Ensure that __all__ is populated properly."""
Martin Panter06172e72016-04-16 23:38:25 +00002611 # STARTUPINFO added to __all__ in 3.6
2612 intentionally_excluded = {"list2cmdline", "STARTUPINFO", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07002613 exported = set(subprocess.__all__)
2614 possible_exports = set()
2615 import types
2616 for name, value in subprocess.__dict__.items():
2617 if name.startswith('_'):
2618 continue
2619 if isinstance(value, (types.ModuleType,)):
2620 continue
2621 possible_exports.add(name)
2622 self.assertEqual(exported, possible_exports - intentionally_excluded)
2623
2624
Martin Panter23172bd2016-04-16 11:28:10 +00002625@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2626 "Test needs selectors.PollSelector")
2627class ProcessTestCaseNoPoll(ProcessTestCase):
2628 def setUp(self):
2629 self.orig_selector = subprocess._PopenSelector
2630 subprocess._PopenSelector = selectors.SelectSelector
2631 ProcessTestCase.setUp(self)
2632
2633 def tearDown(self):
2634 subprocess._PopenSelector = self.orig_selector
2635 ProcessTestCase.tearDown(self)
2636
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002637
Tim Golden126c2962010-08-11 14:20:40 +00002638@unittest.skipUnless(mswindows, "Windows-specific tests")
2639class CommandsWithSpaces (BaseTestCase):
2640
2641 def setUp(self):
2642 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002643 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002644 self.fname = fname.lower ()
2645 os.write(f, b"import sys;"
2646 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2647 )
2648 os.close(f)
2649
2650 def tearDown(self):
2651 os.remove(self.fname)
2652 super().tearDown()
2653
2654 def with_spaces(self, *args, **kwargs):
2655 kwargs['stdout'] = subprocess.PIPE
2656 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002657 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002658 self.assertEqual(
2659 p.stdout.read ().decode("mbcs"),
2660 "2 [%r, 'ab cd']" % self.fname
2661 )
2662
2663 def test_shell_string_with_spaces(self):
2664 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002665 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2666 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002667
2668 def test_shell_sequence_with_spaces(self):
2669 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002670 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002671
2672 def test_noshell_string_with_spaces(self):
2673 # call() function with string argument with spaces on Windows
2674 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2675 "ab cd"))
2676
2677 def test_noshell_sequence_with_spaces(self):
2678 # call() function with sequence argument with spaces on Windows
2679 self.with_spaces([sys.executable, self.fname, "ab cd"])
2680
Brian Curtin79cdb662010-12-03 02:46:02 +00002681
Georg Brandla86b2622012-02-20 21:34:57 +01002682class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002683
2684 def test_pipe(self):
2685 with subprocess.Popen([sys.executable, "-c",
2686 "import sys;"
2687 "sys.stdout.write('stdout');"
2688 "sys.stderr.write('stderr');"],
2689 stdout=subprocess.PIPE,
2690 stderr=subprocess.PIPE) as proc:
2691 self.assertEqual(proc.stdout.read(), b"stdout")
2692 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2693
2694 self.assertTrue(proc.stdout.closed)
2695 self.assertTrue(proc.stderr.closed)
2696
2697 def test_returncode(self):
2698 with subprocess.Popen([sys.executable, "-c",
2699 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002700 pass
2701 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002702 self.assertEqual(proc.returncode, 100)
2703
2704 def test_communicate_stdin(self):
2705 with subprocess.Popen([sys.executable, "-c",
2706 "import sys;"
2707 "sys.exit(sys.stdin.read() == 'context')"],
2708 stdin=subprocess.PIPE) as proc:
2709 proc.communicate(b"context")
2710 self.assertEqual(proc.returncode, 1)
2711
2712 def test_invalid_args(self):
Andrew Svetlovb1726972012-12-26 23:34:54 +02002713 with self.assertRaises(FileNotFoundError) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002714 with subprocess.Popen(['nonexisting_i_hope'],
2715 stdout=subprocess.PIPE,
2716 stderr=subprocess.PIPE) as proc:
2717 pass
2718
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002719 def test_broken_pipe_cleanup(self):
2720 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002721 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002722 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002723 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002724 proc = proc.__enter__()
2725 # Prepare to send enough data to overflow any OS pipe buffering and
2726 # guarantee a broken pipe error. Data is held in BufferedWriter
2727 # buffer until closed.
2728 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002729 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002730 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002731 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002732 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002733 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002734
Brian Curtin79cdb662010-12-03 02:46:02 +00002735
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002736def test_main():
2737 unit_tests = (ProcessTestCase,
2738 POSIXProcessTestCase,
2739 Win32ProcessTestCase,
Martin Panter23172bd2016-04-16 11:28:10 +00002740 MiscTests,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002741 ProcessTestCaseNoPoll,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002742 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002743 ContextManagerTests,
Gregory P. Smith6e730002015-04-14 16:14:25 -07002744 RunFuncTestCase,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002745 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002746
2747 support.run_unittest(*unit_tests)
2748 support.reap_children()
2749
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002750if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002751 unittest.main()