blob: ff2010d612d44f2d9b94c992af532f562047b044 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Berker Peksagce643912015-05-06 06:33:17 +03002from test.support import script_helper
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
6import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04007import io
Andrew Svetlov82860712012-08-19 22:13:41 +03008import locale
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Tim Peters3761e8d2004-10-13 04:07:12 +000013import re
Charles-François Natali3a4586a2013-11-08 19:56:59 +010014import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000015import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000016import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000017import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040018import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050019import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030020import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050021
22try:
Antoine Pitroua8392712013-08-30 23:38:13 +020023 import threading
24except ImportError:
25 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050026
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000027mswindows = (sys.platform == "win32")
28
29#
30# Depends on the following external programs: Python
31#
32
33if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000034 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
35 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000036else:
37 SETBINARY = ''
38
Florent Xiclunab1e94e82010-02-27 22:12:37 +000039
40try:
41 mkstemp = tempfile.mkstemp
42except AttributeError:
43 # tempfile.mkstemp is not available
44 def mkstemp():
45 """Replacement for mkstemp, calling mktemp."""
46 fname = tempfile.mktemp()
47 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
48
Tim Peters3761e8d2004-10-13 04:07:12 +000049
Florent Xiclunac049d872010-03-27 22:47:23 +000050class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000051 def setUp(self):
52 # Try to minimize the number of children we have so this test
53 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000054 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000055
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000056 def tearDown(self):
57 for inst in subprocess._active:
58 inst.wait()
59 subprocess._cleanup()
60 self.assertFalse(subprocess._active, "subprocess._active not empty")
61
Florent Xiclunab1e94e82010-02-27 22:12:37 +000062 def assertStderrEqual(self, stderr, expected, msg=None):
63 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
64 # shutdown time. That frustrates tests trying to check stderr produced
65 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000066 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040067 # strip_python_stderr also strips whitespace, so we do too.
68 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000069 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000070
Florent Xiclunac049d872010-03-27 22:47:23 +000071
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080072class PopenTestException(Exception):
73 pass
74
75
76class PopenExecuteChildRaises(subprocess.Popen):
77 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
78 _execute_child fails.
79 """
80 def _execute_child(self, *args, **kwargs):
81 raise PopenTestException("Forced Exception for Test")
82
83
Florent Xiclunac049d872010-03-27 22:47:23 +000084class ProcessTestCase(BaseTestCase):
85
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070086 def test_io_buffered_by_default(self):
87 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
88 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
89 stderr=subprocess.PIPE)
90 try:
91 self.assertIsInstance(p.stdin, io.BufferedIOBase)
92 self.assertIsInstance(p.stdout, io.BufferedIOBase)
93 self.assertIsInstance(p.stderr, io.BufferedIOBase)
94 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070095 p.stdin.close()
96 p.stdout.close()
97 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070098 p.wait()
99
100 def test_io_unbuffered_works(self):
101 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
102 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
103 stderr=subprocess.PIPE, bufsize=0)
104 try:
105 self.assertIsInstance(p.stdin, io.RawIOBase)
106 self.assertIsInstance(p.stdout, io.RawIOBase)
107 self.assertIsInstance(p.stderr, io.RawIOBase)
108 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700109 p.stdin.close()
110 p.stdout.close()
111 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700112 p.wait()
113
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000115 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000116 rc = subprocess.call([sys.executable, "-c",
117 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000118 self.assertEqual(rc, 47)
119
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400120 def test_call_timeout(self):
121 # call() function with timeout argument; we want to test that the child
122 # process gets killed when the timeout expires. If the child isn't
123 # killed, this call will deadlock since subprocess.call waits for the
124 # child.
125 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
126 [sys.executable, "-c", "while True: pass"],
127 timeout=0.1)
128
Peter Astrand454f7672005-01-01 09:36:35 +0000129 def test_check_call_zero(self):
130 # check_call() function with zero return code
131 rc = subprocess.check_call([sys.executable, "-c",
132 "import sys; sys.exit(0)"])
133 self.assertEqual(rc, 0)
134
135 def test_check_call_nonzero(self):
136 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000137 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000138 subprocess.check_call([sys.executable, "-c",
139 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000140 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000141
Georg Brandlf9734072008-12-07 15:30:06 +0000142 def test_check_output(self):
143 # check_output() function with zero return code
144 output = subprocess.check_output(
145 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000146 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000147
148 def test_check_output_nonzero(self):
149 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000150 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000151 subprocess.check_output(
152 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000153 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000154
155 def test_check_output_stderr(self):
156 # check_output() function stderr redirected to stdout
157 output = subprocess.check_output(
158 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
159 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000160 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000161
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300162 def test_check_output_stdin_arg(self):
163 # check_output() can be called with stdin set to a file
164 tf = tempfile.TemporaryFile()
165 self.addCleanup(tf.close)
166 tf.write(b'pear')
167 tf.seek(0)
168 output = subprocess.check_output(
169 [sys.executable, "-c",
170 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
171 stdin=tf)
172 self.assertIn(b'PEAR', output)
173
174 def test_check_output_input_arg(self):
175 # check_output() can be called with input set to a string
176 output = subprocess.check_output(
177 [sys.executable, "-c",
178 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
179 input=b'pear')
180 self.assertIn(b'PEAR', output)
181
Georg Brandlf9734072008-12-07 15:30:06 +0000182 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300183 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000184 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000185 output = subprocess.check_output(
186 [sys.executable, "-c", "print('will not be run')"],
187 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000188 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000189 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000190
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300191 def test_check_output_stdin_with_input_arg(self):
192 # check_output() refuses to accept 'stdin' with 'input'
193 tf = tempfile.TemporaryFile()
194 self.addCleanup(tf.close)
195 tf.write(b'pear')
196 tf.seek(0)
197 with self.assertRaises(ValueError) as c:
198 output = subprocess.check_output(
199 [sys.executable, "-c", "print('will not be run')"],
200 stdin=tf, input=b'hare')
201 self.fail("Expected ValueError when stdin and input args supplied.")
202 self.assertIn('stdin', c.exception.args[0])
203 self.assertIn('input', c.exception.args[0])
204
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400205 def test_check_output_timeout(self):
206 # check_output() function with timeout arg
207 with self.assertRaises(subprocess.TimeoutExpired) as c:
208 output = subprocess.check_output(
209 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200210 "import sys, time\n"
211 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400212 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200213 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400214 # Some heavily loaded buildbots (sparc Debian 3.x) require
215 # this much time to start and print.
216 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400217 self.fail("Expected TimeoutExpired.")
218 self.assertEqual(c.exception.output, b'BDFL')
219
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000220 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000221 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000222 newenv = os.environ.copy()
223 newenv["FRUIT"] = "banana"
224 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000225 'import sys, os;'
226 'sys.exit(os.getenv("FRUIT")=="banana")'],
227 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000228 self.assertEqual(rc, 1)
229
Victor Stinner87b9bc32011-06-01 00:57:47 +0200230 def test_invalid_args(self):
231 # Popen() called with invalid arguments should raise TypeError
232 # but Popen.__del__ should not complain (issue #12085)
233 with support.captured_stderr() as s:
234 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
235 argcount = subprocess.Popen.__init__.__code__.co_argcount
236 too_many_args = [0] * (argcount + 1)
237 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
238 self.assertEqual(s.getvalue(), '')
239
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000240 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000241 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000242 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000243 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000244 self.addCleanup(p.stdout.close)
245 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000246 p.wait()
247 self.assertEqual(p.stdin, None)
248
249 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200250 # .stdout is None when not redirected, and the child's stdout will
251 # be inherited from the parent. In order to test this we run a
252 # subprocess in a subprocess:
253 # this_test
254 # \-- subprocess created by this test (parent)
255 # \-- subprocess created by the parent subprocess (child)
256 # The parent doesn't specify stdout, so the child will use the
257 # parent's stdout. This test checks that the message printed by the
258 # child goes to the parent stdout. The parent also checks that the
259 # child's stdout is None. See #11963.
260 code = ('import sys; from subprocess import Popen, PIPE;'
261 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
262 ' stdin=PIPE, stderr=PIPE);'
263 'p.wait(); assert p.stdout is None;')
264 p = subprocess.Popen([sys.executable, "-c", code],
265 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
266 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000267 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200268 out, err = p.communicate()
269 self.assertEqual(p.returncode, 0, err)
270 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271
272 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000273 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000274 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000275 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000276 self.addCleanup(p.stdout.close)
277 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000278 p.wait()
279 self.assertEqual(p.stderr, None)
280
Chris Jerdonek776cb192012-10-08 15:56:43 -0700281 def _assert_python(self, pre_args, **kwargs):
282 # We include sys.exit() to prevent the test runner from hanging
283 # whenever python is found.
284 args = pre_args + ["import sys; sys.exit(47)"]
285 p = subprocess.Popen(args, **kwargs)
286 p.wait()
287 self.assertEqual(47, p.returncode)
288
289 def test_executable(self):
290 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700291 #
292 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
293 # determine where its standard library is, so we need the directory
294 # of args[0] to be valid for the Popen() call to Python to succeed.
295 # See also issue #16170 and issue #7774.
296 doesnotexist = os.path.join(os.path.dirname(sys.executable),
297 "doesnotexist")
298 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700299
300 def test_executable_takes_precedence(self):
301 # Check that the executable argument takes precedence over args[0].
302 #
303 # Verify first that the call succeeds without the executable arg.
304 pre_args = [sys.executable, "-c"]
305 self._assert_python(pre_args)
306 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
307 executable="doesnotexist")
308
309 @unittest.skipIf(mswindows, "executable argument replaces shell")
310 def test_executable_replaces_shell(self):
311 # Check that the executable argument replaces the default shell
312 # when shell=True.
313 self._assert_python([], executable=sys.executable, shell=True)
314
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700315 # For use in the test_cwd* tests below.
316 def _normalize_cwd(self, cwd):
317 # Normalize an expected cwd (for Tru64 support).
318 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
319 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300320 with support.change_cwd(cwd):
321 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700322
323 # For use in the test_cwd* tests below.
324 def _split_python_path(self):
325 # Return normalized (python_dir, python_base).
326 python_path = os.path.realpath(sys.executable)
327 return os.path.split(python_path)
328
329 # For use in the test_cwd* tests below.
330 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
331 # Invoke Python via Popen, and assert that (1) the call succeeds,
332 # and that (2) the current working directory of the child process
333 # matches *expected_cwd*.
334 p = subprocess.Popen([python_arg, "-c",
335 "import os, sys; "
336 "sys.stdout.write(os.getcwd()); "
337 "sys.exit(47)"],
338 stdout=subprocess.PIPE,
339 **kwargs)
340 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000341 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700342 self.assertEqual(47, p.returncode)
343 normcase = os.path.normcase
344 self.assertEqual(normcase(expected_cwd),
345 normcase(p.stdout.read().decode("utf-8")))
346
347 def test_cwd(self):
348 # Check that cwd changes the cwd for the child process.
349 temp_dir = tempfile.gettempdir()
350 temp_dir = self._normalize_cwd(temp_dir)
351 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
352
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700353 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700354 def test_cwd_with_relative_arg(self):
355 # Check that Popen looks for args[0] relative to cwd if args[0]
356 # is relative.
357 python_dir, python_base = self._split_python_path()
358 rel_python = os.path.join(os.curdir, python_base)
359 with support.temp_cwd() as wrong_dir:
360 # Before calling with the correct cwd, confirm that the call fails
361 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700362 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700363 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700364 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700365 [rel_python], cwd=wrong_dir)
366 python_dir = self._normalize_cwd(python_dir)
367 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
368
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700369 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700370 def test_cwd_with_relative_executable(self):
371 # Check that Popen looks for executable relative to cwd if executable
372 # is relative (and that executable takes precedence over args[0]).
373 python_dir, python_base = self._split_python_path()
374 rel_python = os.path.join(os.curdir, python_base)
375 doesntexist = "somethingyoudonthave"
376 with support.temp_cwd() as wrong_dir:
377 # Before calling with the correct cwd, confirm that the call fails
378 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700379 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700380 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700381 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700382 [doesntexist], executable=rel_python,
383 cwd=wrong_dir)
384 python_dir = self._normalize_cwd(python_dir)
385 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
386 cwd=python_dir)
387
388 def test_cwd_with_absolute_arg(self):
389 # Check that Popen can find the executable when the cwd is wrong
390 # if args[0] is an absolute path.
391 python_dir, python_base = self._split_python_path()
392 abs_python = os.path.join(python_dir, python_base)
393 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300394 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700395 # Before calling with an absolute path, confirm that using a
396 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700397 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700398 [rel_python], cwd=wrong_dir)
399 wrong_dir = self._normalize_cwd(wrong_dir)
400 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
401
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100402 @unittest.skipIf(sys.base_prefix != sys.prefix,
403 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000404 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700405 python_dir, python_base = self._split_python_path()
406 python_dir = self._normalize_cwd(python_dir)
407 self._assert_cwd(python_dir, "somethingyoudonthave",
408 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000409
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100410 @unittest.skipIf(sys.base_prefix != sys.prefix,
411 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000412 @unittest.skipIf(sysconfig.is_python_build(),
413 "need an installed Python. See #7774")
414 def test_executable_without_cwd(self):
415 # For a normal installation, it should work without 'cwd'
416 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700417 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
418 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000419
420 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000421 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000422 p = subprocess.Popen([sys.executable, "-c",
423 'import sys; sys.exit(sys.stdin.read() == "pear")'],
424 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000425 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426 p.stdin.close()
427 p.wait()
428 self.assertEqual(p.returncode, 1)
429
430 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000431 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000432 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000433 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000434 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000435 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000436 os.lseek(d, 0, 0)
437 p = subprocess.Popen([sys.executable, "-c",
438 'import sys; sys.exit(sys.stdin.read() == "pear")'],
439 stdin=d)
440 p.wait()
441 self.assertEqual(p.returncode, 1)
442
443 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000444 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000445 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000446 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000447 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000448 tf.seek(0)
449 p = subprocess.Popen([sys.executable, "-c",
450 'import sys; sys.exit(sys.stdin.read() == "pear")'],
451 stdin=tf)
452 p.wait()
453 self.assertEqual(p.returncode, 1)
454
455 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000456 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000457 p = subprocess.Popen([sys.executable, "-c",
458 'import sys; sys.stdout.write("orange")'],
459 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000460 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000461 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000462
463 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000464 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000465 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000466 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000467 d = tf.fileno()
468 p = subprocess.Popen([sys.executable, "-c",
469 'import sys; sys.stdout.write("orange")'],
470 stdout=d)
471 p.wait()
472 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000473 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474
475 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000476 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000477 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000478 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479 p = subprocess.Popen([sys.executable, "-c",
480 'import sys; sys.stdout.write("orange")'],
481 stdout=tf)
482 p.wait()
483 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000484 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485
486 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000487 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488 p = subprocess.Popen([sys.executable, "-c",
489 'import sys; sys.stderr.write("strawberry")'],
490 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000491 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000492 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000493
494 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000495 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000496 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000497 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000498 d = tf.fileno()
499 p = subprocess.Popen([sys.executable, "-c",
500 'import sys; sys.stderr.write("strawberry")'],
501 stderr=d)
502 p.wait()
503 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000504 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000505
506 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000507 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000508 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000509 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000510 p = subprocess.Popen([sys.executable, "-c",
511 'import sys; sys.stderr.write("strawberry")'],
512 stderr=tf)
513 p.wait()
514 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000515 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516
517 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000518 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000519 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000520 'import sys;'
521 'sys.stdout.write("apple");'
522 'sys.stdout.flush();'
523 'sys.stderr.write("orange")'],
524 stdout=subprocess.PIPE,
525 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000526 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000527 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528
529 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000530 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000532 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000533 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000534 'import sys;'
535 'sys.stdout.write("apple");'
536 'sys.stdout.flush();'
537 'sys.stderr.write("orange")'],
538 stdout=tf,
539 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540 p.wait()
541 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000542 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543
Thomas Wouters89f507f2006-12-13 04:49:30 +0000544 def test_stdout_filedes_of_stdout(self):
545 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200546 # To avoid printing the text on stdout, we do something similar to
547 # test_stdout_none (see above). The parent subprocess calls the child
548 # subprocess passing stdout=1, and this test uses stdout=PIPE in
549 # order to capture and check the output of the parent. See #11963.
550 code = ('import sys, subprocess; '
551 'rc = subprocess.call([sys.executable, "-c", '
552 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
553 'b\'test with stdout=1\'))"], stdout=1); '
554 'assert rc == 18')
555 p = subprocess.Popen([sys.executable, "-c", code],
556 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
557 self.addCleanup(p.stdout.close)
558 self.addCleanup(p.stderr.close)
559 out, err = p.communicate()
560 self.assertEqual(p.returncode, 0, err)
561 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000562
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200563 def test_stdout_devnull(self):
564 p = subprocess.Popen([sys.executable, "-c",
565 'for i in range(10240):'
566 'print("x" * 1024)'],
567 stdout=subprocess.DEVNULL)
568 p.wait()
569 self.assertEqual(p.stdout, None)
570
571 def test_stderr_devnull(self):
572 p = subprocess.Popen([sys.executable, "-c",
573 'import sys\n'
574 'for i in range(10240):'
575 'sys.stderr.write("x" * 1024)'],
576 stderr=subprocess.DEVNULL)
577 p.wait()
578 self.assertEqual(p.stderr, None)
579
580 def test_stdin_devnull(self):
581 p = subprocess.Popen([sys.executable, "-c",
582 'import sys;'
583 'sys.stdin.read(1)'],
584 stdin=subprocess.DEVNULL)
585 p.wait()
586 self.assertEqual(p.stdin, None)
587
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000588 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589 newenv = os.environ.copy()
590 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200591 with subprocess.Popen([sys.executable, "-c",
592 'import sys,os;'
593 'sys.stdout.write(os.getenv("FRUIT"))'],
594 stdout=subprocess.PIPE,
595 env=newenv) as p:
596 stdout, stderr = p.communicate()
597 self.assertEqual(stdout, b"orange")
598
Victor Stinner62d51182011-06-23 01:02:25 +0200599 # Windows requires at least the SYSTEMROOT environment variable to start
600 # Python
601 @unittest.skipIf(sys.platform == 'win32',
602 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200603 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200604 'the python library cannot be loaded '
605 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200606 def test_empty_env(self):
607 with subprocess.Popen([sys.executable, "-c",
608 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200609 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200610 stdout=subprocess.PIPE,
611 env={}) as p:
612 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200613 self.assertIn(stdout.strip(),
614 (b"[]",
615 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
616 # environment
617 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000618
Peter Astrandcbac93c2005-03-03 20:24:28 +0000619 def test_communicate_stdin(self):
620 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000621 'import sys;'
622 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000623 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000624 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000625 self.assertEqual(p.returncode, 1)
626
627 def test_communicate_stdout(self):
628 p = subprocess.Popen([sys.executable, "-c",
629 'import sys; sys.stdout.write("pineapple")'],
630 stdout=subprocess.PIPE)
631 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000632 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000633 self.assertEqual(stderr, None)
634
635 def test_communicate_stderr(self):
636 p = subprocess.Popen([sys.executable, "-c",
637 'import sys; sys.stderr.write("pineapple")'],
638 stderr=subprocess.PIPE)
639 (stdout, stderr) = p.communicate()
640 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000641 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000642
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000644 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000645 'import sys,os;'
646 'sys.stderr.write("pineapple");'
647 'sys.stdout.write(sys.stdin.read())'],
648 stdin=subprocess.PIPE,
649 stdout=subprocess.PIPE,
650 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000651 self.addCleanup(p.stdout.close)
652 self.addCleanup(p.stderr.close)
653 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000654 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000655 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000656 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000657
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400658 def test_communicate_timeout(self):
659 p = subprocess.Popen([sys.executable, "-c",
660 'import sys,os,time;'
661 'sys.stderr.write("pineapple\\n");'
662 'time.sleep(1);'
663 'sys.stderr.write("pear\\n");'
664 'sys.stdout.write(sys.stdin.read())'],
665 universal_newlines=True,
666 stdin=subprocess.PIPE,
667 stdout=subprocess.PIPE,
668 stderr=subprocess.PIPE)
669 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
670 timeout=0.3)
671 # Make sure we can keep waiting for it, and that we get the whole output
672 # after it completes.
673 (stdout, stderr) = p.communicate()
674 self.assertEqual(stdout, "banana")
675 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
676
677 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200678 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400679 p = subprocess.Popen([sys.executable, "-c",
680 'import sys,os,time;'
681 'sys.stdout.write("a" * (64 * 1024));'
682 'time.sleep(0.2);'
683 'sys.stdout.write("a" * (64 * 1024));'
684 'time.sleep(0.2);'
685 'sys.stdout.write("a" * (64 * 1024));'
686 'time.sleep(0.2);'
687 'sys.stdout.write("a" * (64 * 1024));'],
688 stdout=subprocess.PIPE)
689 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
690 (stdout, _) = p.communicate()
691 self.assertEqual(len(stdout), 4 * 64 * 1024)
692
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000693 # Test for the fd leak reported in http://bugs.python.org/issue2791.
694 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000695 for stdin_pipe in (False, True):
696 for stdout_pipe in (False, True):
697 for stderr_pipe in (False, True):
698 options = {}
699 if stdin_pipe:
700 options['stdin'] = subprocess.PIPE
701 if stdout_pipe:
702 options['stdout'] = subprocess.PIPE
703 if stderr_pipe:
704 options['stderr'] = subprocess.PIPE
705 if not options:
706 continue
707 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
708 p.communicate()
709 if p.stdin is not None:
710 self.assertTrue(p.stdin.closed)
711 if p.stdout is not None:
712 self.assertTrue(p.stdout.closed)
713 if p.stderr is not None:
714 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000715
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000716 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000717 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000718 p = subprocess.Popen([sys.executable, "-c",
719 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000720 (stdout, stderr) = p.communicate()
721 self.assertEqual(stdout, None)
722 self.assertEqual(stderr, None)
723
724 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000725 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000726 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000727 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000728 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000729 os.close(x)
730 os.close(y)
731 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000732 'import sys,os;'
733 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200734 'sys.stderr.write("x" * %d);'
735 'sys.stdout.write(sys.stdin.read())' %
736 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000737 stdin=subprocess.PIPE,
738 stdout=subprocess.PIPE,
739 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000740 self.addCleanup(p.stdout.close)
741 self.addCleanup(p.stderr.close)
742 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200743 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000744 (stdout, stderr) = p.communicate(string_to_write)
745 self.assertEqual(stdout, string_to_write)
746
747 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000748 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000749 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000750 'import sys,os;'
751 'sys.stdout.write(sys.stdin.read())'],
752 stdin=subprocess.PIPE,
753 stdout=subprocess.PIPE,
754 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000755 self.addCleanup(p.stdout.close)
756 self.addCleanup(p.stderr.close)
757 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000758 p.stdin.write(b"banana")
759 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000760 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000761 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000762
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000763 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000765 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200766 'buf = sys.stdout.buffer;'
767 'buf.write(sys.stdin.readline().encode());'
768 'buf.flush();'
769 'buf.write(b"line2\\n");'
770 'buf.flush();'
771 'buf.write(sys.stdin.read().encode());'
772 'buf.flush();'
773 'buf.write(b"line4\\n");'
774 'buf.flush();'
775 'buf.write(b"line5\\r\\n");'
776 'buf.flush();'
777 'buf.write(b"line6\\r");'
778 'buf.flush();'
779 'buf.write(b"\\nline7");'
780 'buf.flush();'
781 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200782 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000783 stdout=subprocess.PIPE,
784 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200785 p.stdin.write("line1\n")
Antoine Pitrouc644e7c2014-05-09 00:24:50 +0200786 p.stdin.flush()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200787 self.assertEqual(p.stdout.readline(), "line1\n")
788 p.stdin.write("line3\n")
789 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000790 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200791 self.assertEqual(p.stdout.readline(),
792 "line2\n")
793 self.assertEqual(p.stdout.read(6),
794 "line3\n")
795 self.assertEqual(p.stdout.read(),
796 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000797
798 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000799 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000800 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000801 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200802 'buf = sys.stdout.buffer;'
803 'buf.write(b"line2\\n");'
804 'buf.flush();'
805 'buf.write(b"line4\\n");'
806 'buf.flush();'
807 'buf.write(b"line5\\r\\n");'
808 'buf.flush();'
809 'buf.write(b"line6\\r");'
810 'buf.flush();'
811 'buf.write(b"\\nline7");'
812 'buf.flush();'
813 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200814 stderr=subprocess.PIPE,
815 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000816 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000817 self.addCleanup(p.stdout.close)
818 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000819 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200820 self.assertEqual(stdout,
821 "line2\nline4\nline5\nline6\nline7\nline8")
822
823 def test_universal_newlines_communicate_stdin(self):
824 # universal newlines through communicate(), with only stdin
825 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300826 'import sys,os;' + SETBINARY + textwrap.dedent('''
827 s = sys.stdin.readline()
828 assert s == "line1\\n", repr(s)
829 s = sys.stdin.read()
830 assert s == "line3\\n", repr(s)
831 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200832 stdin=subprocess.PIPE,
833 universal_newlines=1)
834 (stdout, stderr) = p.communicate("line1\nline3\n")
835 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000836
Andrew Svetlovf3765072012-08-14 18:35:17 +0300837 def test_universal_newlines_communicate_input_none(self):
838 # Test communicate(input=None) with universal newlines.
839 #
840 # We set stdout to PIPE because, as of this writing, a different
841 # code path is tested when the number of pipes is zero or one.
842 p = subprocess.Popen([sys.executable, "-c", "pass"],
843 stdin=subprocess.PIPE,
844 stdout=subprocess.PIPE,
845 universal_newlines=True)
846 p.communicate()
847 self.assertEqual(p.returncode, 0)
848
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300849 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300850 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300851 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300852 'import sys,os;' + SETBINARY + textwrap.dedent('''
853 s = sys.stdin.buffer.readline()
854 sys.stdout.buffer.write(s)
855 sys.stdout.buffer.write(b"line2\\r")
856 sys.stderr.buffer.write(b"eline2\\n")
857 s = sys.stdin.buffer.read()
858 sys.stdout.buffer.write(s)
859 sys.stdout.buffer.write(b"line4\\n")
860 sys.stdout.buffer.write(b"line5\\r\\n")
861 sys.stderr.buffer.write(b"eline6\\r")
862 sys.stderr.buffer.write(b"eline7\\r\\nz")
863 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300864 stdin=subprocess.PIPE,
865 stderr=subprocess.PIPE,
866 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300867 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300868 self.addCleanup(p.stdout.close)
869 self.addCleanup(p.stderr.close)
870 (stdout, stderr) = p.communicate("line1\nline3\n")
871 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300872 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300873 # Python debug build push something like "[42442 refs]\n"
874 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300875 # Don't use assertStderrEqual because it strips CR and LF from output.
876 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300877
Andrew Svetlov82860712012-08-19 22:13:41 +0300878 def test_universal_newlines_communicate_encodings(self):
879 # Check that universal newlines mode works for various encodings,
880 # in particular for encodings in the UTF-16 and UTF-32 families.
881 # See issue #15595.
882 #
883 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
884 # without, and UTF-16 and UTF-32.
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200885 import _bootlocale
Andrew Svetlov82860712012-08-19 22:13:41 +0300886 for encoding in ['utf-16', 'utf-32-be']:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200887 old_getpreferredencoding = _bootlocale.getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300888 # Indirectly via io.TextIOWrapper, Popen() defaults to
889 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
890 # locale.getpreferredencoding().
891 def getpreferredencoding(do_setlocale=True):
892 return encoding
893 code = ("import sys; "
894 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
895 encoding)
896 args = [sys.executable, '-c', code]
897 try:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200898 _bootlocale.getpreferredencoding = getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300899 # We set stdin to be non-None because, as of this writing,
900 # a different code path is used when the number of pipes is
901 # zero or one.
902 popen = subprocess.Popen(args, universal_newlines=True,
903 stdin=subprocess.PIPE,
904 stdout=subprocess.PIPE)
905 stdout, stderr = popen.communicate(input='')
906 finally:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200907 _bootlocale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300908 self.assertEqual(stdout, '1\n2\n3\n4')
909
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000910 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000911 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000912 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000913 max_handles = 1026 # too much for most UNIX systems
914 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000915 max_handles = 2050 # too much for (at least some) Windows setups
916 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400917 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000918 try:
919 for i in range(max_handles):
920 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400921 tmpfile = os.path.join(tmpdir, support.TESTFN)
922 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000923 except OSError as e:
924 if e.errno != errno.EMFILE:
925 raise
926 break
927 else:
928 self.skipTest("failed to reach the file descriptor limit "
929 "(tried %d)" % max_handles)
930 # Close a couple of them (should be enough for a subprocess)
931 for i in range(10):
932 os.close(handles.pop())
933 # Loop creating some subprocesses. If one of them leaks some fds,
934 # the next loop iteration will fail by reaching the max fd limit.
935 for i in range(15):
936 p = subprocess.Popen([sys.executable, "-c",
937 "import sys;"
938 "sys.stdout.write(sys.stdin.read())"],
939 stdin=subprocess.PIPE,
940 stdout=subprocess.PIPE,
941 stderr=subprocess.PIPE)
942 data = p.communicate(b"lime")[0]
943 self.assertEqual(data, b"lime")
944 finally:
945 for h in handles:
946 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400947 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000948
949 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000950 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
951 '"a b c" d e')
952 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
953 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000954 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
955 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000956 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
957 'a\\\\\\b "de fg" h')
958 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
959 'a\\\\\\"b c d')
960 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
961 '"a\\\\b c" d e')
962 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
963 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000964 self.assertEqual(subprocess.list2cmdline(['ab', '']),
965 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000966
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000967 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200968 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200969 "import os; os.read(0, 1)"],
970 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200971 self.addCleanup(p.stdin.close)
972 self.assertIsNone(p.poll())
973 os.write(p.stdin.fileno(), b'A')
974 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000975 # Subsequent invocations should just return the returncode
976 self.assertEqual(p.poll(), 0)
977
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000978 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200979 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000980 self.assertEqual(p.wait(), 0)
981 # Subsequent invocations should just return the returncode
982 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000983
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400984 def test_wait_timeout(self):
985 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200986 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400987 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200988 p.wait(timeout=0.0001)
989 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400990 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
991 # time to start.
992 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400993
Peter Astrand738131d2004-11-30 21:04:45 +0000994 def test_invalid_bufsize(self):
995 # an invalid type of the bufsize argument should raise
996 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000997 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000998 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000999
Guido van Rossum46a05a72007-06-07 21:56:45 +00001000 def test_bufsize_is_none(self):
1001 # bufsize=None should be the same as bufsize=0.
1002 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1003 self.assertEqual(p.wait(), 0)
1004 # Again with keyword arg
1005 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1006 self.assertEqual(p.wait(), 0)
1007
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001008 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1009 # subprocess may deadlock with bufsize=1, see issue #21332
1010 with subprocess.Popen([sys.executable, "-c", "import sys;"
1011 "sys.stdout.write(sys.stdin.readline());"
1012 "sys.stdout.flush()"],
1013 stdin=subprocess.PIPE,
1014 stdout=subprocess.PIPE,
1015 stderr=subprocess.DEVNULL,
1016 bufsize=1,
1017 universal_newlines=universal_newlines) as p:
1018 p.stdin.write(line) # expect that it flushes the line in text mode
1019 os.close(p.stdin.fileno()) # close it without flushing the buffer
1020 read_line = p.stdout.readline()
1021 try:
1022 p.stdin.close()
1023 except OSError:
1024 pass
1025 p.stdin = None
1026 self.assertEqual(p.returncode, 0)
1027 self.assertEqual(read_line, expected)
1028
1029 def test_bufsize_equal_one_text_mode(self):
1030 # line is flushed in text mode with bufsize=1.
1031 # we should get the full line in return
1032 line = "line\n"
1033 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1034
1035 def test_bufsize_equal_one_binary_mode(self):
1036 # line is not flushed in binary mode with bufsize=1.
1037 # we should get empty response
1038 line = b'line' + os.linesep.encode() # assume ascii-based locale
1039 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1040
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001041 def test_leaking_fds_on_error(self):
1042 # see bug #5179: Popen leaks file descriptors to PIPEs if
1043 # the child fails to execute; this will eventually exhaust
1044 # the maximum number of open fds. 1024 seems a very common
1045 # value for that limit, but Windows has 2048, so we loop
1046 # 1024 times (each call leaked two fds).
1047 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001048 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001049 subprocess.Popen(['nonexisting_i_hope'],
1050 stdout=subprocess.PIPE,
1051 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001052 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001053 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001054 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001055
Antoine Pitroua8392712013-08-30 23:38:13 +02001056 @unittest.skipIf(threading is None, "threading required")
1057 def test_double_close_on_error(self):
1058 # Issue #18851
1059 fds = []
1060 def open_fds():
1061 for i in range(20):
1062 fds.extend(os.pipe())
1063 time.sleep(0.001)
1064 t = threading.Thread(target=open_fds)
1065 t.start()
1066 try:
1067 with self.assertRaises(EnvironmentError):
1068 subprocess.Popen(['nonexisting_i_hope'],
1069 stdin=subprocess.PIPE,
1070 stdout=subprocess.PIPE,
1071 stderr=subprocess.PIPE)
1072 finally:
1073 t.join()
1074 exc = None
1075 for fd in fds:
1076 # If a double close occurred, some of those fds will
1077 # already have been closed by mistake, and os.close()
1078 # here will raise.
1079 try:
1080 os.close(fd)
1081 except OSError as e:
1082 exc = e
1083 if exc is not None:
1084 raise exc
1085
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001086 @unittest.skipIf(threading is None, "threading required")
1087 def test_threadsafe_wait(self):
1088 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1089 proc = subprocess.Popen([sys.executable, '-c',
1090 'import time; time.sleep(12)'])
1091 self.assertEqual(proc.returncode, None)
1092 results = []
1093
1094 def kill_proc_timer_thread():
1095 results.append(('thread-start-poll-result', proc.poll()))
1096 # terminate it from the thread and wait for the result.
1097 proc.kill()
1098 proc.wait()
1099 results.append(('thread-after-kill-and-wait', proc.returncode))
1100 # this wait should be a no-op given the above.
1101 proc.wait()
1102 results.append(('thread-after-second-wait', proc.returncode))
1103
1104 # This is a timing sensitive test, the failure mode is
1105 # triggered when both the main thread and this thread are in
1106 # the wait() call at once. The delay here is to allow the
1107 # main thread to most likely be blocked in its wait() call.
1108 t = threading.Timer(0.2, kill_proc_timer_thread)
1109 t.start()
1110
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001111 if mswindows:
1112 expected_errorcode = 1
1113 else:
1114 # Should be -9 because of the proc.kill() from the thread.
1115 expected_errorcode = -9
1116
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001117 # Wait for the process to finish; the thread should kill it
1118 # long before it finishes on its own. Supplying a timeout
1119 # triggers a different code path for better coverage.
1120 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001121 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001122 msg="unexpected result in wait from main thread")
1123
1124 # This should be a no-op with no change in returncode.
1125 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001126 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001127 msg="unexpected result in second main wait.")
1128
1129 t.join()
1130 # Ensure that all of the thread results are as expected.
1131 # When a race condition occurs in wait(), the returncode could
1132 # be set by the wrong thread that doesn't actually have it
1133 # leading to an incorrect value.
1134 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001135 ('thread-after-kill-and-wait', expected_errorcode),
1136 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001137 results)
1138
Victor Stinnerb3693582010-05-21 20:13:12 +00001139 def test_issue8780(self):
1140 # Ensure that stdout is inherited from the parent
1141 # if stdout=PIPE is not used
1142 code = ';'.join((
1143 'import subprocess, sys',
1144 'retcode = subprocess.call('
1145 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1146 'assert retcode == 0'))
1147 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001148 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001149
Tim Goldenaf5ac392010-08-06 13:03:56 +00001150 def test_handles_closed_on_exception(self):
1151 # If CreateProcess exits with an error, ensure the
1152 # duplicate output handles are released
1153 ifhandle, ifname = mkstemp()
1154 ofhandle, ofname = mkstemp()
1155 efhandle, efname = mkstemp()
1156 try:
1157 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1158 stderr=efhandle)
1159 except OSError:
1160 os.close(ifhandle)
1161 os.remove(ifname)
1162 os.close(ofhandle)
1163 os.remove(ofname)
1164 os.close(efhandle)
1165 os.remove(efname)
1166 self.assertFalse(os.path.exists(ifname))
1167 self.assertFalse(os.path.exists(ofname))
1168 self.assertFalse(os.path.exists(efname))
1169
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001170 def test_communicate_epipe(self):
1171 # Issue 10963: communicate() should hide EPIPE
1172 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1173 stdin=subprocess.PIPE,
1174 stdout=subprocess.PIPE,
1175 stderr=subprocess.PIPE)
1176 self.addCleanup(p.stdout.close)
1177 self.addCleanup(p.stderr.close)
1178 self.addCleanup(p.stdin.close)
1179 p.communicate(b"x" * 2**20)
1180
1181 def test_communicate_epipe_only_stdin(self):
1182 # Issue 10963: communicate() should hide EPIPE
1183 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1184 stdin=subprocess.PIPE)
1185 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001186 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001187 p.communicate(b"x" * 2**20)
1188
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001189 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1190 "Requires signal.SIGUSR1")
1191 @unittest.skipUnless(hasattr(os, 'kill'),
1192 "Requires os.kill")
1193 @unittest.skipUnless(hasattr(os, 'getppid'),
1194 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001195 def test_communicate_eintr(self):
1196 # Issue #12493: communicate() should handle EINTR
1197 def handler(signum, frame):
1198 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001199 old_handler = signal.signal(signal.SIGUSR1, handler)
1200 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001201
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001202 args = [sys.executable, "-c",
1203 'import os, signal;'
1204 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001205 for stream in ('stdout', 'stderr'):
1206 kw = {stream: subprocess.PIPE}
1207 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001208 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001209 process.communicate()
1210
Tim Peterse718f612004-10-12 21:51:32 +00001211
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001212 # This test is Linux-ish specific for simplicity to at least have
1213 # some coverage. It is not a platform specific bug.
1214 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1215 "Linux specific")
1216 def test_failed_child_execute_fd_leak(self):
1217 """Test for the fork() failure fd leak reported in issue16327."""
1218 fd_directory = '/proc/%d/fd' % os.getpid()
1219 fds_before_popen = os.listdir(fd_directory)
1220 with self.assertRaises(PopenTestException):
1221 PopenExecuteChildRaises(
1222 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1223 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1224
1225 # NOTE: This test doesn't verify that the real _execute_child
1226 # does not close the file descriptors itself on the way out
1227 # during an exception. Code inspection has confirmed that.
1228
1229 fds_after_exception = os.listdir(fd_directory)
1230 self.assertEqual(fds_before_popen, fds_after_exception)
1231
Gregory P. Smith6e730002015-04-14 16:14:25 -07001232
1233class RunFuncTestCase(BaseTestCase):
1234 def run_python(self, code, **kwargs):
1235 """Run Python code in a subprocess using subprocess.run"""
1236 argv = [sys.executable, "-c", code]
1237 return subprocess.run(argv, **kwargs)
1238
1239 def test_returncode(self):
1240 # call() function with sequence argument
1241 cp = self.run_python("import sys; sys.exit(47)")
1242 self.assertEqual(cp.returncode, 47)
1243 with self.assertRaises(subprocess.CalledProcessError):
1244 cp.check_returncode()
1245
1246 def test_check(self):
1247 with self.assertRaises(subprocess.CalledProcessError) as c:
1248 self.run_python("import sys; sys.exit(47)", check=True)
1249 self.assertEqual(c.exception.returncode, 47)
1250
1251 def test_check_zero(self):
1252 # check_returncode shouldn't raise when returncode is zero
1253 cp = self.run_python("import sys; sys.exit(0)", check=True)
1254 self.assertEqual(cp.returncode, 0)
1255
1256 def test_timeout(self):
1257 # run() function with timeout argument; we want to test that the child
1258 # process gets killed when the timeout expires. If the child isn't
1259 # killed, this call will deadlock since subprocess.run waits for the
1260 # child.
1261 with self.assertRaises(subprocess.TimeoutExpired):
1262 self.run_python("while True: pass", timeout=0.0001)
1263
1264 def test_capture_stdout(self):
1265 # capture stdout with zero return code
1266 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1267 self.assertIn(b'BDFL', cp.stdout)
1268
1269 def test_capture_stderr(self):
1270 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1271 stderr=subprocess.PIPE)
1272 self.assertIn(b'BDFL', cp.stderr)
1273
1274 def test_check_output_stdin_arg(self):
1275 # run() can be called with stdin set to a file
1276 tf = tempfile.TemporaryFile()
1277 self.addCleanup(tf.close)
1278 tf.write(b'pear')
1279 tf.seek(0)
1280 cp = self.run_python(
1281 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1282 stdin=tf, stdout=subprocess.PIPE)
1283 self.assertIn(b'PEAR', cp.stdout)
1284
1285 def test_check_output_input_arg(self):
1286 # check_output() can be called with input set to a string
1287 cp = self.run_python(
1288 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1289 input=b'pear', stdout=subprocess.PIPE)
1290 self.assertIn(b'PEAR', cp.stdout)
1291
1292 def test_check_output_stdin_with_input_arg(self):
1293 # run() refuses to accept 'stdin' with 'input'
1294 tf = tempfile.TemporaryFile()
1295 self.addCleanup(tf.close)
1296 tf.write(b'pear')
1297 tf.seek(0)
1298 with self.assertRaises(ValueError,
1299 msg="Expected ValueError when stdin and input args supplied.") as c:
1300 output = self.run_python("print('will not be run')",
1301 stdin=tf, input=b'hare')
1302 self.assertIn('stdin', c.exception.args[0])
1303 self.assertIn('input', c.exception.args[0])
1304
1305 def test_check_output_timeout(self):
1306 with self.assertRaises(subprocess.TimeoutExpired) as c:
1307 cp = self.run_python((
1308 "import sys, time\n"
1309 "sys.stdout.write('BDFL')\n"
1310 "sys.stdout.flush()\n"
1311 "time.sleep(3600)"),
1312 # Some heavily loaded buildbots (sparc Debian 3.x) require
1313 # this much time to start and print.
1314 timeout=3, stdout=subprocess.PIPE)
1315 self.assertEqual(c.exception.output, b'BDFL')
1316 # output is aliased to stdout
1317 self.assertEqual(c.exception.stdout, b'BDFL')
1318
1319 def test_run_kwargs(self):
1320 newenv = os.environ.copy()
1321 newenv["FRUIT"] = "banana"
1322 cp = self.run_python(('import sys, os;'
1323 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1324 env=newenv)
1325 self.assertEqual(cp.returncode, 33)
1326
1327
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001328@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001329class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001330
Gregory P. Smith5591b022012-10-10 03:34:47 -07001331 def setUp(self):
1332 super().setUp()
1333 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1334
1335 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001336 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001337 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001338 except OSError as e:
1339 # This avoids hard coding the errno value or the OS perror()
1340 # string and instead capture the exception that we want to see
1341 # below for comparison.
1342 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001343 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001344 else:
1345 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001346 self._nonexistent_dir)
1347 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001348
Gregory P. Smith5591b022012-10-10 03:34:47 -07001349 def test_exception_cwd(self):
1350 """Test error in the child raised in the parent for a bad cwd."""
1351 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001352 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001353 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001354 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001355 except OSError as e:
1356 # Test that the child process chdir failure actually makes
1357 # it up to the parent process as the correct exception.
1358 self.assertEqual(desired_exception.errno, e.errno)
1359 self.assertEqual(desired_exception.strerror, e.strerror)
1360 else:
1361 self.fail("Expected OSError: %s" % desired_exception)
1362
Gregory P. Smith5591b022012-10-10 03:34:47 -07001363 def test_exception_bad_executable(self):
1364 """Test error in the child raised in the parent for a bad executable."""
1365 desired_exception = self._get_chdir_exception()
1366 try:
1367 p = subprocess.Popen([sys.executable, "-c", ""],
1368 executable=self._nonexistent_dir)
1369 except OSError as e:
1370 # Test that the child process exec failure actually makes
1371 # it up to the parent process as the correct exception.
1372 self.assertEqual(desired_exception.errno, e.errno)
1373 self.assertEqual(desired_exception.strerror, e.strerror)
1374 else:
1375 self.fail("Expected OSError: %s" % desired_exception)
1376
1377 def test_exception_bad_args_0(self):
1378 """Test error in the child raised in the parent for a bad args[0]."""
1379 desired_exception = self._get_chdir_exception()
1380 try:
1381 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1382 except OSError as e:
1383 # Test that the child process exec failure actually makes
1384 # it up to the parent process as the correct exception.
1385 self.assertEqual(desired_exception.errno, e.errno)
1386 self.assertEqual(desired_exception.strerror, e.strerror)
1387 else:
1388 self.fail("Expected OSError: %s" % desired_exception)
1389
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001390 def test_restore_signals(self):
1391 # Code coverage for both values of restore_signals to make sure it
1392 # at least does not blow up.
1393 # A test for behavior would be complex. Contributions welcome.
1394 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1395 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1396
1397 def test_start_new_session(self):
1398 # For code coverage of calling setsid(). We don't care if we get an
1399 # EPERM error from it depending on the test execution environment, that
1400 # still indicates that it was called.
1401 try:
1402 output = subprocess.check_output(
1403 [sys.executable, "-c",
1404 "import os; print(os.getpgid(os.getpid()))"],
1405 start_new_session=True)
1406 except OSError as e:
1407 if e.errno != errno.EPERM:
1408 raise
1409 else:
1410 parent_pgid = os.getpgid(os.getpid())
1411 child_pgid = int(output)
1412 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001413
1414 def test_run_abort(self):
1415 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001416 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001417 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001418 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001419 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001420 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001421
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001422 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001423 # DISCLAIMER: Setting environment variables is *not* a good use
1424 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001425 p = subprocess.Popen([sys.executable, "-c",
1426 'import sys,os;'
1427 'sys.stdout.write(os.getenv("FRUIT"))'],
1428 stdout=subprocess.PIPE,
1429 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001430 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001431 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001432
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001433 def test_preexec_exception(self):
1434 def raise_it():
1435 raise ValueError("What if two swallows carried a coconut?")
1436 try:
1437 p = subprocess.Popen([sys.executable, "-c", ""],
1438 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001439 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001440 self.assertTrue(
1441 subprocess._posixsubprocess,
1442 "Expected a ValueError from the preexec_fn")
1443 except ValueError as e:
1444 self.assertIn("coconut", e.args[0])
1445 else:
1446 self.fail("Exception raised by preexec_fn did not make it "
1447 "to the parent process.")
1448
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001449 class _TestExecuteChildPopen(subprocess.Popen):
1450 """Used to test behavior at the end of _execute_child."""
1451 def __init__(self, testcase, *args, **kwargs):
1452 self._testcase = testcase
1453 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001454
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001455 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001456 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001457 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001458 finally:
1459 # Open a bunch of file descriptors and verify that
1460 # none of them are the same as the ones the Popen
1461 # instance is using for stdin/stdout/stderr.
1462 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1463 for _ in range(8)]
1464 try:
1465 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001466 self._testcase.assertNotIn(
1467 fd, (self.stdin.fileno(), self.stdout.fileno(),
1468 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001469 msg="At least one fd was closed early.")
1470 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001471 for fd in devzero_fds:
1472 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001473
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001474 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1475 def test_preexec_errpipe_does_not_double_close_pipes(self):
1476 """Issue16140: Don't double close pipes on preexec error."""
1477
1478 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001479 raise subprocess.SubprocessError(
1480 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001481
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001482 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001483 self._TestExecuteChildPopen(
1484 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001485 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1486 stderr=subprocess.PIPE, preexec_fn=raise_it)
1487
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001488 def test_preexec_gc_module_failure(self):
1489 # This tests the code that disables garbage collection if the child
1490 # process will execute any Python.
1491 def raise_runtime_error():
1492 raise RuntimeError("this shouldn't escape")
1493 enabled = gc.isenabled()
1494 orig_gc_disable = gc.disable
1495 orig_gc_isenabled = gc.isenabled
1496 try:
1497 gc.disable()
1498 self.assertFalse(gc.isenabled())
1499 subprocess.call([sys.executable, '-c', ''],
1500 preexec_fn=lambda: None)
1501 self.assertFalse(gc.isenabled(),
1502 "Popen enabled gc when it shouldn't.")
1503
1504 gc.enable()
1505 self.assertTrue(gc.isenabled())
1506 subprocess.call([sys.executable, '-c', ''],
1507 preexec_fn=lambda: None)
1508 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1509
1510 gc.disable = raise_runtime_error
1511 self.assertRaises(RuntimeError, subprocess.Popen,
1512 [sys.executable, '-c', ''],
1513 preexec_fn=lambda: None)
1514
1515 del gc.isenabled # force an AttributeError
1516 self.assertRaises(AttributeError, subprocess.Popen,
1517 [sys.executable, '-c', ''],
1518 preexec_fn=lambda: None)
1519 finally:
1520 gc.disable = orig_gc_disable
1521 gc.isenabled = orig_gc_isenabled
1522 if not enabled:
1523 gc.disable()
1524
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001525 def test_args_string(self):
1526 # args is a string
1527 fd, fname = mkstemp()
1528 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001529 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001530 fobj.write("#!/bin/sh\n")
1531 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1532 sys.executable)
1533 os.chmod(fname, 0o700)
1534 p = subprocess.Popen(fname)
1535 p.wait()
1536 os.remove(fname)
1537 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001538
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001539 def test_invalid_args(self):
1540 # invalid arguments should raise ValueError
1541 self.assertRaises(ValueError, subprocess.call,
1542 [sys.executable, "-c",
1543 "import sys; sys.exit(47)"],
1544 startupinfo=47)
1545 self.assertRaises(ValueError, subprocess.call,
1546 [sys.executable, "-c",
1547 "import sys; sys.exit(47)"],
1548 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001549
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001550 def test_shell_sequence(self):
1551 # Run command through the shell (sequence)
1552 newenv = os.environ.copy()
1553 newenv["FRUIT"] = "apple"
1554 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1555 stdout=subprocess.PIPE,
1556 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001557 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001558 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001559
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001560 def test_shell_string(self):
1561 # Run command through the shell (string)
1562 newenv = os.environ.copy()
1563 newenv["FRUIT"] = "apple"
1564 p = subprocess.Popen("echo $FRUIT", shell=1,
1565 stdout=subprocess.PIPE,
1566 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001567 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001568 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001569
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001570 def test_call_string(self):
1571 # call() function with string argument on UNIX
1572 fd, fname = mkstemp()
1573 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001574 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001575 fobj.write("#!/bin/sh\n")
1576 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1577 sys.executable)
1578 os.chmod(fname, 0o700)
1579 rc = subprocess.call(fname)
1580 os.remove(fname)
1581 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001582
Stefan Krah9542cc62010-07-19 14:20:53 +00001583 def test_specific_shell(self):
1584 # Issue #9265: Incorrect name passed as arg[0].
1585 shells = []
1586 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1587 for name in ['bash', 'ksh']:
1588 sh = os.path.join(prefix, name)
1589 if os.path.isfile(sh):
1590 shells.append(sh)
1591 if not shells: # Will probably work for any shell but csh.
1592 self.skipTest("bash or ksh required for this test")
1593 sh = '/bin/sh'
1594 if os.path.isfile(sh) and not os.path.islink(sh):
1595 # Test will fail if /bin/sh is a symlink to csh.
1596 shells.append(sh)
1597 for sh in shells:
1598 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1599 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001600 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001601 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1602
Florent Xicluna4886d242010-03-08 13:27:26 +00001603 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001604 # Do not inherit file handles from the parent.
1605 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001606 # Also set the SIGINT handler to the default to make sure it's not
1607 # being ignored (some tests rely on that.)
1608 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1609 try:
1610 p = subprocess.Popen([sys.executable, "-c", """if 1:
1611 import sys, time
1612 sys.stdout.write('x\\n')
1613 sys.stdout.flush()
1614 time.sleep(30)
1615 """],
1616 close_fds=True,
1617 stdin=subprocess.PIPE,
1618 stdout=subprocess.PIPE,
1619 stderr=subprocess.PIPE)
1620 finally:
1621 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001622 # Wait for the interpreter to be completely initialized before
1623 # sending any signal.
1624 p.stdout.read(1)
1625 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001626 return p
1627
Charles-François Natali53221e32013-01-12 16:52:20 +01001628 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1629 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001630 def _kill_dead_process(self, method, *args):
1631 # Do not inherit file handles from the parent.
1632 # It should fix failures on some platforms.
1633 p = subprocess.Popen([sys.executable, "-c", """if 1:
1634 import sys, time
1635 sys.stdout.write('x\\n')
1636 sys.stdout.flush()
1637 """],
1638 close_fds=True,
1639 stdin=subprocess.PIPE,
1640 stdout=subprocess.PIPE,
1641 stderr=subprocess.PIPE)
1642 # Wait for the interpreter to be completely initialized before
1643 # sending any signal.
1644 p.stdout.read(1)
1645 # The process should end after this
1646 time.sleep(1)
1647 # This shouldn't raise even though the child is now dead
1648 getattr(p, method)(*args)
1649 p.communicate()
1650
Florent Xicluna4886d242010-03-08 13:27:26 +00001651 def test_send_signal(self):
1652 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001653 _, stderr = p.communicate()
1654 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001655 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001656
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001657 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001658 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001659 _, stderr = p.communicate()
1660 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001661 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001662
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001663 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001664 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001665 _, stderr = p.communicate()
1666 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001667 self.assertEqual(p.wait(), -signal.SIGTERM)
1668
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001669 def test_send_signal_dead(self):
1670 # Sending a signal to a dead process
1671 self._kill_dead_process('send_signal', signal.SIGINT)
1672
1673 def test_kill_dead(self):
1674 # Killing a dead process
1675 self._kill_dead_process('kill')
1676
1677 def test_terminate_dead(self):
1678 # Terminating a dead process
1679 self._kill_dead_process('terminate')
1680
Victor Stinnerdaf45552013-08-28 00:53:59 +02001681 def _save_fds(self, save_fds):
1682 fds = []
1683 for fd in save_fds:
1684 inheritable = os.get_inheritable(fd)
1685 saved = os.dup(fd)
1686 fds.append((fd, saved, inheritable))
1687 return fds
1688
1689 def _restore_fds(self, fds):
1690 for fd, saved, inheritable in fds:
1691 os.dup2(saved, fd, inheritable=inheritable)
1692 os.close(saved)
1693
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001694 def check_close_std_fds(self, fds):
1695 # Issue #9905: test that subprocess pipes still work properly with
1696 # some standard fds closed
1697 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001698 saved_fds = self._save_fds(fds)
1699 for fd, saved, inheritable in saved_fds:
1700 if fd == 0:
1701 stdin = saved
1702 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001703 try:
1704 for fd in fds:
1705 os.close(fd)
1706 out, err = subprocess.Popen([sys.executable, "-c",
1707 'import sys;'
1708 'sys.stdout.write("apple");'
1709 'sys.stdout.flush();'
1710 'sys.stderr.write("orange")'],
1711 stdin=stdin,
1712 stdout=subprocess.PIPE,
1713 stderr=subprocess.PIPE).communicate()
1714 err = support.strip_python_stderr(err)
1715 self.assertEqual((out, err), (b'apple', b'orange'))
1716 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001717 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001718
1719 def test_close_fd_0(self):
1720 self.check_close_std_fds([0])
1721
1722 def test_close_fd_1(self):
1723 self.check_close_std_fds([1])
1724
1725 def test_close_fd_2(self):
1726 self.check_close_std_fds([2])
1727
1728 def test_close_fds_0_1(self):
1729 self.check_close_std_fds([0, 1])
1730
1731 def test_close_fds_0_2(self):
1732 self.check_close_std_fds([0, 2])
1733
1734 def test_close_fds_1_2(self):
1735 self.check_close_std_fds([1, 2])
1736
1737 def test_close_fds_0_1_2(self):
1738 # Issue #10806: test that subprocess pipes still work properly with
1739 # all standard fds closed.
1740 self.check_close_std_fds([0, 1, 2])
1741
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001742 def test_small_errpipe_write_fd(self):
1743 """Issue #15798: Popen should work when stdio fds are available."""
1744 new_stdin = os.dup(0)
1745 new_stdout = os.dup(1)
1746 try:
1747 os.close(0)
1748 os.close(1)
1749
1750 # Side test: if errpipe_write fails to have its CLOEXEC
1751 # flag set this should cause the parent to think the exec
1752 # failed. Extremely unlikely: everyone supports CLOEXEC.
1753 subprocess.Popen([
1754 sys.executable, "-c",
1755 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1756 finally:
1757 # Restore original stdin and stdout
1758 os.dup2(new_stdin, 0)
1759 os.dup2(new_stdout, 1)
1760 os.close(new_stdin)
1761 os.close(new_stdout)
1762
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001763 def test_remapping_std_fds(self):
1764 # open up some temporary files
1765 temps = [mkstemp() for i in range(3)]
1766 try:
1767 temp_fds = [fd for fd, fname in temps]
1768
1769 # unlink the files -- we won't need to reopen them
1770 for fd, fname in temps:
1771 os.unlink(fname)
1772
1773 # write some data to what will become stdin, and rewind
1774 os.write(temp_fds[1], b"STDIN")
1775 os.lseek(temp_fds[1], 0, 0)
1776
1777 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001778 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001779 try:
1780 # duplicate the file objects over the standard fd's
1781 for fd, temp_fd in enumerate(temp_fds):
1782 os.dup2(temp_fd, fd)
1783
1784 # now use those files in the "wrong" order, so that subprocess
1785 # has to rearrange them in the child
1786 p = subprocess.Popen([sys.executable, "-c",
1787 'import sys; got = sys.stdin.read();'
1788 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1789 stdin=temp_fds[1],
1790 stdout=temp_fds[2],
1791 stderr=temp_fds[0])
1792 p.wait()
1793 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001794 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001795
1796 for fd in temp_fds:
1797 os.lseek(fd, 0, 0)
1798
1799 out = os.read(temp_fds[2], 1024)
1800 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1801 self.assertEqual(out, b"got STDIN")
1802 self.assertEqual(err, b"err")
1803
1804 finally:
1805 for fd in temp_fds:
1806 os.close(fd)
1807
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001808 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1809 # open up some temporary files
1810 temps = [mkstemp() for i in range(3)]
1811 temp_fds = [fd for fd, fname in temps]
1812 try:
1813 # unlink the files -- we won't need to reopen them
1814 for fd, fname in temps:
1815 os.unlink(fname)
1816
1817 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001818 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001819 try:
1820 # duplicate the temp files over the standard fd's 0, 1, 2
1821 for fd, temp_fd in enumerate(temp_fds):
1822 os.dup2(temp_fd, fd)
1823
1824 # write some data to what will become stdin, and rewind
1825 os.write(stdin_no, b"STDIN")
1826 os.lseek(stdin_no, 0, 0)
1827
1828 # now use those files in the given order, so that subprocess
1829 # has to rearrange them in the child
1830 p = subprocess.Popen([sys.executable, "-c",
1831 'import sys; got = sys.stdin.read();'
1832 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1833 stdin=stdin_no,
1834 stdout=stdout_no,
1835 stderr=stderr_no)
1836 p.wait()
1837
1838 for fd in temp_fds:
1839 os.lseek(fd, 0, 0)
1840
1841 out = os.read(stdout_no, 1024)
1842 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1843 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001844 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001845
1846 self.assertEqual(out, b"got STDIN")
1847 self.assertEqual(err, b"err")
1848
1849 finally:
1850 for fd in temp_fds:
1851 os.close(fd)
1852
1853 # When duping fds, if there arises a situation where one of the fds is
1854 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1855 # This tests all combinations of this.
1856 def test_swap_fds(self):
1857 self.check_swap_fds(0, 1, 2)
1858 self.check_swap_fds(0, 2, 1)
1859 self.check_swap_fds(1, 0, 2)
1860 self.check_swap_fds(1, 2, 0)
1861 self.check_swap_fds(2, 0, 1)
1862 self.check_swap_fds(2, 1, 0)
1863
Victor Stinner13bb71c2010-04-23 21:41:56 +00001864 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001865 def prepare():
1866 raise ValueError("surrogate:\uDCff")
1867
1868 try:
1869 subprocess.call(
1870 [sys.executable, "-c", "pass"],
1871 preexec_fn=prepare)
1872 except ValueError as err:
1873 # Pure Python implementations keeps the message
1874 self.assertIsNone(subprocess._posixsubprocess)
1875 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001876 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001877 # _posixsubprocess uses a default message
1878 self.assertIsNotNone(subprocess._posixsubprocess)
1879 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1880 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001881 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001882
Victor Stinner13bb71c2010-04-23 21:41:56 +00001883 def test_undecodable_env(self):
1884 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01001885 encoded_value = value.encode("ascii", "surrogateescape")
1886
Victor Stinner13bb71c2010-04-23 21:41:56 +00001887 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001888 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001889 env = os.environ.copy()
1890 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01001891 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00001892 # surrogate-escaping of \xFF in the child process; otherwise it can
1893 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001894 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01001895 if sys.platform.startswith("aix"):
1896 # On AIX, the C locale uses the Latin1 encoding
1897 decoded_value = encoded_value.decode("latin1", "surrogateescape")
1898 else:
1899 # On other UNIXes, the C locale uses the ASCII encoding
1900 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001901 stdout = subprocess.check_output(
1902 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001903 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001904 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001905 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001906
1907 # test bytes
1908 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001909 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001910 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01001911 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001912 stdout = subprocess.check_output(
1913 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001914 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001915 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001916 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001917
Victor Stinnerb745a742010-05-18 17:17:23 +00001918 def test_bytes_program(self):
1919 abs_program = os.fsencode(sys.executable)
1920 path, program = os.path.split(sys.executable)
1921 program = os.fsencode(program)
1922
1923 # absolute bytes path
1924 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001925 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001926
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001927 # absolute bytes path as a string
1928 cmd = b"'" + abs_program + b"' -c pass"
1929 exitcode = subprocess.call(cmd, shell=True)
1930 self.assertEqual(exitcode, 0)
1931
Victor Stinnerb745a742010-05-18 17:17:23 +00001932 # bytes program, unicode PATH
1933 env = os.environ.copy()
1934 env["PATH"] = path
1935 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001936 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001937
1938 # bytes program, bytes PATH
1939 envb = os.environb.copy()
1940 envb[b"PATH"] = os.fsencode(path)
1941 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001942 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001943
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001944 def test_pipe_cloexec(self):
1945 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1946 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1947
1948 p1 = subprocess.Popen([sys.executable, sleeper],
1949 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1950 stderr=subprocess.PIPE, close_fds=False)
1951
1952 self.addCleanup(p1.communicate, b'')
1953
1954 p2 = subprocess.Popen([sys.executable, fd_status],
1955 stdout=subprocess.PIPE, close_fds=False)
1956
1957 output, error = p2.communicate()
1958 result_fds = set(map(int, output.split(b',')))
1959 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1960 p1.stderr.fileno()])
1961
1962 self.assertFalse(result_fds & unwanted_fds,
1963 "Expected no fds from %r to be open in child, "
1964 "found %r" %
1965 (unwanted_fds, result_fds & unwanted_fds))
1966
1967 def test_pipe_cloexec_real_tools(self):
1968 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1969 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1970
1971 subdata = b'zxcvbn'
1972 data = subdata * 4 + b'\n'
1973
1974 p1 = subprocess.Popen([sys.executable, qcat],
1975 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1976 close_fds=False)
1977
1978 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1979 stdin=p1.stdout, stdout=subprocess.PIPE,
1980 close_fds=False)
1981
1982 self.addCleanup(p1.wait)
1983 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001984 def kill_p1():
1985 try:
1986 p1.terminate()
1987 except ProcessLookupError:
1988 pass
1989 def kill_p2():
1990 try:
1991 p2.terminate()
1992 except ProcessLookupError:
1993 pass
1994 self.addCleanup(kill_p1)
1995 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001996
1997 p1.stdin.write(data)
1998 p1.stdin.close()
1999
2000 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2001
2002 self.assertTrue(readfiles, "The child hung")
2003 self.assertEqual(p2.stdout.read(), data)
2004
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002005 p1.stdout.close()
2006 p2.stdout.close()
2007
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002008 def test_close_fds(self):
2009 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2010
2011 fds = os.pipe()
2012 self.addCleanup(os.close, fds[0])
2013 self.addCleanup(os.close, fds[1])
2014
2015 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002016 # add a bunch more fds
2017 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002018 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002019 self.addCleanup(os.close, fd)
2020 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002021
Victor Stinnerdaf45552013-08-28 00:53:59 +02002022 for fd in open_fds:
2023 os.set_inheritable(fd, True)
2024
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002025 p = subprocess.Popen([sys.executable, fd_status],
2026 stdout=subprocess.PIPE, close_fds=False)
2027 output, ignored = p.communicate()
2028 remaining_fds = set(map(int, output.split(b',')))
2029
2030 self.assertEqual(remaining_fds & open_fds, open_fds,
2031 "Some fds were closed")
2032
2033 p = subprocess.Popen([sys.executable, fd_status],
2034 stdout=subprocess.PIPE, close_fds=True)
2035 output, ignored = p.communicate()
2036 remaining_fds = set(map(int, output.split(b',')))
2037
2038 self.assertFalse(remaining_fds & open_fds,
2039 "Some fds were left open")
2040 self.assertIn(1, remaining_fds, "Subprocess failed")
2041
Gregory P. Smith8facece2012-01-21 14:01:08 -08002042 # Keep some of the fd's we opened open in the subprocess.
2043 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2044 fds_to_keep = set(open_fds.pop() for _ in range(8))
2045 p = subprocess.Popen([sys.executable, fd_status],
2046 stdout=subprocess.PIPE, close_fds=True,
2047 pass_fds=())
2048 output, ignored = p.communicate()
2049 remaining_fds = set(map(int, output.split(b',')))
2050
2051 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2052 "Some fds not in pass_fds were left open")
2053 self.assertIn(1, remaining_fds, "Subprocess failed")
2054
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002055
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002056 @unittest.skipIf(sys.platform.startswith("freebsd") and
2057 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2058 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002059 def test_close_fds_when_max_fd_is_lowered(self):
2060 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2061 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2062
Gregory P. Smith634aa682014-06-15 17:51:04 -07002063 # This launches the meat of the test in a child process to
2064 # avoid messing with the larger unittest processes maximum
2065 # number of file descriptors.
2066 # This process launches:
2067 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2068 # a bunch of high open fds above the new lower rlimit.
2069 # Those are reported via stdout before launching a new
2070 # process with close_fds=False to run the actual test:
2071 # +--> The TEST: This one launches a fd_status.py
2072 # subprocess with close_fds=True so we can find out if
2073 # any of the fds above the lowered rlimit are still open.
2074 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2075 '''
2076 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002077 open_fds = set()
2078 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002079 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002080 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002081 open_fds.add(fd)
2082
2083 # Leave a two pairs of low ones available for use by the
2084 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002085 # We also leave 10 more open as some Python buildbots run into
2086 # "too many open files" errors during the test if we do not.
2087 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002088 os.close(fd)
2089 open_fds.remove(fd)
2090
2091 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002092 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002093 os.set_inheritable(fd, True)
2094
2095 max_fd_open = max(open_fds)
2096
Gregory P. Smith634aa682014-06-15 17:51:04 -07002097 # Communicate the open_fds to the parent unittest.TestCase process.
2098 print(','.join(map(str, sorted(open_fds))))
2099 sys.stdout.flush()
2100
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002101 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2102 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002103 # 29 is lower than the highest fds we are leaving open.
2104 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002105 # Launch a new Python interpreter with our low fd rlim_cur that
2106 # inherits open fds above that limit. It then uses subprocess
2107 # with close_fds=True to get a report of open fds in the child.
2108 # An explicit list of fds to check is passed to fd_status.py as
2109 # letting fd_status rely on its default logic would miss the
2110 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002111 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002112 [sys.executable, '-c',
2113 textwrap.dedent("""
2114 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002115 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002116 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002117 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002118 """.format(max_fd=max_fd_open+1))],
2119 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002120 finally:
2121 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002122 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002123
2124 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002125 output_lines = output.splitlines()
2126 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002127 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002128 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2129 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002130
Gregory P. Smith634aa682014-06-15 17:51:04 -07002131 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002132 msg="Some fds were left open.")
2133
2134
Victor Stinner88701e22011-06-01 13:13:04 +02002135 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2136 # descriptor of a pipe closed in the parent process is valid in the
2137 # child process according to fstat(), but the mode of the file
2138 # descriptor is invalid, and read or write raise an error.
2139 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002140 def test_pass_fds(self):
2141 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2142
2143 open_fds = set()
2144
2145 for x in range(5):
2146 fds = os.pipe()
2147 self.addCleanup(os.close, fds[0])
2148 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002149 os.set_inheritable(fds[0], True)
2150 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002151 open_fds.update(fds)
2152
2153 for fd in open_fds:
2154 p = subprocess.Popen([sys.executable, fd_status],
2155 stdout=subprocess.PIPE, close_fds=True,
2156 pass_fds=(fd, ))
2157 output, ignored = p.communicate()
2158
2159 remaining_fds = set(map(int, output.split(b',')))
2160 to_be_closed = open_fds - {fd}
2161
2162 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2163 self.assertFalse(remaining_fds & to_be_closed,
2164 "fd to be closed passed")
2165
2166 # pass_fds overrides close_fds with a warning.
2167 with self.assertWarns(RuntimeWarning) as context:
2168 self.assertFalse(subprocess.call(
2169 [sys.executable, "-c", "import sys; sys.exit(0)"],
2170 close_fds=False, pass_fds=(fd, )))
2171 self.assertIn('overriding close_fds', str(context.warning))
2172
Victor Stinnerdaf45552013-08-28 00:53:59 +02002173 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002174 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002175
2176 inheritable, non_inheritable = os.pipe()
2177 self.addCleanup(os.close, inheritable)
2178 self.addCleanup(os.close, non_inheritable)
2179 os.set_inheritable(inheritable, True)
2180 os.set_inheritable(non_inheritable, False)
2181 pass_fds = (inheritable, non_inheritable)
2182 args = [sys.executable, script]
2183 args += list(map(str, pass_fds))
2184
2185 p = subprocess.Popen(args,
2186 stdout=subprocess.PIPE, close_fds=True,
2187 pass_fds=pass_fds)
2188 output, ignored = p.communicate()
2189 fds = set(map(int, output.split(b',')))
2190
2191 # the inheritable file descriptor must be inherited, so its inheritable
2192 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002193 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002194
2195 # inheritable flag must not be changed in the parent process
2196 self.assertEqual(os.get_inheritable(inheritable), True)
2197 self.assertEqual(os.get_inheritable(non_inheritable), False)
2198
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002199 def test_stdout_stdin_are_single_inout_fd(self):
2200 with io.open(os.devnull, "r+") as inout:
2201 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2202 stdout=inout, stdin=inout)
2203 p.wait()
2204
2205 def test_stdout_stderr_are_single_inout_fd(self):
2206 with io.open(os.devnull, "r+") as inout:
2207 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2208 stdout=inout, stderr=inout)
2209 p.wait()
2210
2211 def test_stderr_stdin_are_single_inout_fd(self):
2212 with io.open(os.devnull, "r+") as inout:
2213 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2214 stderr=inout, stdin=inout)
2215 p.wait()
2216
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002217 def test_wait_when_sigchild_ignored(self):
2218 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2219 sigchild_ignore = support.findfile("sigchild_ignore.py",
2220 subdir="subprocessdata")
2221 p = subprocess.Popen([sys.executable, sigchild_ignore],
2222 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2223 stdout, stderr = p.communicate()
2224 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002225 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002226 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002227
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002228 def test_select_unbuffered(self):
2229 # Issue #11459: bufsize=0 should really set the pipes as
2230 # unbuffered (and therefore let select() work properly).
2231 select = support.import_module("select")
2232 p = subprocess.Popen([sys.executable, "-c",
2233 'import sys;'
2234 'sys.stdout.write("apple")'],
2235 stdout=subprocess.PIPE,
2236 bufsize=0)
2237 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002238 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002239 try:
2240 self.assertEqual(f.read(4), b"appl")
2241 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2242 finally:
2243 p.wait()
2244
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002245 def test_zombie_fast_process_del(self):
2246 # Issue #12650: on Unix, if Popen.__del__() was called before the
2247 # process exited, it wouldn't be added to subprocess._active, and would
2248 # remain a zombie.
2249 # spawn a Popen, and delete its reference before it exits
2250 p = subprocess.Popen([sys.executable, "-c",
2251 'import sys, time;'
2252 'time.sleep(0.2)'],
2253 stdout=subprocess.PIPE,
2254 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002255 self.addCleanup(p.stdout.close)
2256 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002257 ident = id(p)
2258 pid = p.pid
2259 del p
2260 # check that p is in the active processes list
2261 self.assertIn(ident, [id(o) for o in subprocess._active])
2262
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002263 def test_leak_fast_process_del_killed(self):
2264 # Issue #12650: on Unix, if Popen.__del__() was called before the
2265 # process exited, and the process got killed by a signal, it would never
2266 # be removed from subprocess._active, which triggered a FD and memory
2267 # leak.
2268 # spawn a Popen, delete its reference and kill it
2269 p = subprocess.Popen([sys.executable, "-c",
2270 'import time;'
2271 'time.sleep(3)'],
2272 stdout=subprocess.PIPE,
2273 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002274 self.addCleanup(p.stdout.close)
2275 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002276 ident = id(p)
2277 pid = p.pid
2278 del p
2279 os.kill(pid, signal.SIGKILL)
2280 # check that p is in the active processes list
2281 self.assertIn(ident, [id(o) for o in subprocess._active])
2282
2283 # let some time for the process to exit, and create a new Popen: this
2284 # should trigger the wait() of p
2285 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002286 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002287 with subprocess.Popen(['nonexisting_i_hope'],
2288 stdout=subprocess.PIPE,
2289 stderr=subprocess.PIPE) as proc:
2290 pass
2291 # p should have been wait()ed on, and removed from the _active list
2292 self.assertRaises(OSError, os.waitpid, pid, 0)
2293 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2294
Charles-François Natali249cdc32013-08-25 18:24:45 +02002295 def test_close_fds_after_preexec(self):
2296 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2297
2298 # this FD is used as dup2() target by preexec_fn, and should be closed
2299 # in the child process
2300 fd = os.dup(1)
2301 self.addCleanup(os.close, fd)
2302
2303 p = subprocess.Popen([sys.executable, fd_status],
2304 stdout=subprocess.PIPE, close_fds=True,
2305 preexec_fn=lambda: os.dup2(1, fd))
2306 output, ignored = p.communicate()
2307
2308 remaining_fds = set(map(int, output.split(b',')))
2309
2310 self.assertNotIn(fd, remaining_fds)
2311
Victor Stinner8f437aa2014-10-05 17:25:19 +02002312 @support.cpython_only
2313 def test_fork_exec(self):
2314 # Issue #22290: fork_exec() must not crash on memory allocation failure
2315 # or other errors
2316 import _posixsubprocess
2317 gc_enabled = gc.isenabled()
2318 try:
2319 # Use a preexec function and enable the garbage collector
2320 # to force fork_exec() to re-enable the garbage collector
2321 # on error.
2322 func = lambda: None
2323 gc.enable()
2324
2325 executable_list = "exec" # error: must be a sequence
2326
2327 for args, exe_list, cwd, env_list in (
2328 (123, [b"exe"], None, [b"env"]),
2329 ([b"arg"], 123, None, [b"env"]),
2330 ([b"arg"], [b"exe"], 123, [b"env"]),
2331 ([b"arg"], [b"exe"], None, 123),
2332 ):
2333 with self.assertRaises(TypeError):
2334 _posixsubprocess.fork_exec(
2335 args, exe_list,
2336 True, [], cwd, env_list,
2337 -1, -1, -1, -1,
2338 1, 2, 3, 4,
2339 True, True, func)
2340 finally:
2341 if not gc_enabled:
2342 gc.disable()
2343
2344
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002345
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002346@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002347class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002348
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002349 def test_startupinfo(self):
2350 # startupinfo argument
2351 # We uses hardcoded constants, because we do not want to
2352 # depend on win32all.
2353 STARTF_USESHOWWINDOW = 1
2354 SW_MAXIMIZE = 3
2355 startupinfo = subprocess.STARTUPINFO()
2356 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2357 startupinfo.wShowWindow = SW_MAXIMIZE
2358 # Since Python is a console process, it won't be affected
2359 # by wShowWindow, but the argument should be silently
2360 # ignored
2361 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002362 startupinfo=startupinfo)
2363
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002364 def test_creationflags(self):
2365 # creationflags argument
2366 CREATE_NEW_CONSOLE = 16
2367 sys.stderr.write(" a DOS box should flash briefly ...\n")
2368 subprocess.call(sys.executable +
2369 ' -c "import time; time.sleep(0.25)"',
2370 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002371
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002372 def test_invalid_args(self):
2373 # invalid arguments should raise ValueError
2374 self.assertRaises(ValueError, subprocess.call,
2375 [sys.executable, "-c",
2376 "import sys; sys.exit(47)"],
2377 preexec_fn=lambda: 1)
2378 self.assertRaises(ValueError, subprocess.call,
2379 [sys.executable, "-c",
2380 "import sys; sys.exit(47)"],
2381 stdout=subprocess.PIPE,
2382 close_fds=True)
2383
2384 def test_close_fds(self):
2385 # close file descriptors
2386 rc = subprocess.call([sys.executable, "-c",
2387 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002388 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002389 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002390
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002391 def test_shell_sequence(self):
2392 # Run command through the shell (sequence)
2393 newenv = os.environ.copy()
2394 newenv["FRUIT"] = "physalis"
2395 p = subprocess.Popen(["set"], shell=1,
2396 stdout=subprocess.PIPE,
2397 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002398 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002399 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002400
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002401 def test_shell_string(self):
2402 # Run command through the shell (string)
2403 newenv = os.environ.copy()
2404 newenv["FRUIT"] = "physalis"
2405 p = subprocess.Popen("set", shell=1,
2406 stdout=subprocess.PIPE,
2407 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002408 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002409 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002410
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002411 def test_call_string(self):
2412 # call() function with string argument on Windows
2413 rc = subprocess.call(sys.executable +
2414 ' -c "import sys; sys.exit(47)"')
2415 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002416
Florent Xicluna4886d242010-03-08 13:27:26 +00002417 def _kill_process(self, method, *args):
2418 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002419 p = subprocess.Popen([sys.executable, "-c", """if 1:
2420 import sys, time
2421 sys.stdout.write('x\\n')
2422 sys.stdout.flush()
2423 time.sleep(30)
2424 """],
2425 stdin=subprocess.PIPE,
2426 stdout=subprocess.PIPE,
2427 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00002428 self.addCleanup(p.stdout.close)
2429 self.addCleanup(p.stderr.close)
2430 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00002431 # Wait for the interpreter to be completely initialized before
2432 # sending any signal.
2433 p.stdout.read(1)
2434 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00002435 _, stderr = p.communicate()
2436 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00002437 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002438 self.assertNotEqual(returncode, 0)
2439
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002440 def _kill_dead_process(self, method, *args):
2441 p = subprocess.Popen([sys.executable, "-c", """if 1:
2442 import sys, time
2443 sys.stdout.write('x\\n')
2444 sys.stdout.flush()
2445 sys.exit(42)
2446 """],
2447 stdin=subprocess.PIPE,
2448 stdout=subprocess.PIPE,
2449 stderr=subprocess.PIPE)
2450 self.addCleanup(p.stdout.close)
2451 self.addCleanup(p.stderr.close)
2452 self.addCleanup(p.stdin.close)
2453 # Wait for the interpreter to be completely initialized before
2454 # sending any signal.
2455 p.stdout.read(1)
2456 # The process should end after this
2457 time.sleep(1)
2458 # This shouldn't raise even though the child is now dead
2459 getattr(p, method)(*args)
2460 _, stderr = p.communicate()
2461 self.assertStderrEqual(stderr, b'')
2462 rc = p.wait()
2463 self.assertEqual(rc, 42)
2464
Florent Xicluna4886d242010-03-08 13:27:26 +00002465 def test_send_signal(self):
2466 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002467
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002468 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002469 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002470
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002471 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002472 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002473
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002474 def test_send_signal_dead(self):
2475 self._kill_dead_process('send_signal', signal.SIGTERM)
2476
2477 def test_kill_dead(self):
2478 self._kill_dead_process('kill')
2479
2480 def test_terminate_dead(self):
2481 self._kill_dead_process('terminate')
2482
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002483class CommandTests(unittest.TestCase):
2484 def test_getoutput(self):
2485 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2486 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2487 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002488
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002489 # we use mkdtemp in the next line to create an empty directory
2490 # under our exclusive control; from that, we can invent a pathname
2491 # that we _know_ won't exist. This is guaranteed to fail.
2492 dir = None
2493 try:
2494 dir = tempfile.mkdtemp()
2495 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002496 status, output = subprocess.getstatusoutput(
2497 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002498 self.assertNotEqual(status, 0)
2499 finally:
2500 if dir is not None:
2501 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002502
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002503
Charles-François Natali3a4586a2013-11-08 19:56:59 +01002504@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2505 "Test needs selectors.PollSelector")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002506class ProcessTestCaseNoPoll(ProcessTestCase):
2507 def setUp(self):
Charles-François Natali3a4586a2013-11-08 19:56:59 +01002508 self.orig_selector = subprocess._PopenSelector
2509 subprocess._PopenSelector = selectors.SelectSelector
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002510 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002511
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002512 def tearDown(self):
Charles-François Natali3a4586a2013-11-08 19:56:59 +01002513 subprocess._PopenSelector = self.orig_selector
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002514 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002515
Gregory P. Smithace55862015-04-07 15:57:54 -07002516 def test__all__(self):
2517 """Ensure that __all__ is populated properly."""
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -07002518 intentionally_excluded = set(("list2cmdline",))
Gregory P. Smithace55862015-04-07 15:57:54 -07002519 exported = set(subprocess.__all__)
2520 possible_exports = set()
2521 import types
2522 for name, value in subprocess.__dict__.items():
2523 if name.startswith('_'):
2524 continue
2525 if isinstance(value, (types.ModuleType,)):
2526 continue
2527 possible_exports.add(name)
2528 self.assertEqual(exported, possible_exports - intentionally_excluded)
2529
2530
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002531
Tim Golden126c2962010-08-11 14:20:40 +00002532@unittest.skipUnless(mswindows, "Windows-specific tests")
2533class CommandsWithSpaces (BaseTestCase):
2534
2535 def setUp(self):
2536 super().setUp()
2537 f, fname = mkstemp(".py", "te st")
2538 self.fname = fname.lower ()
2539 os.write(f, b"import sys;"
2540 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2541 )
2542 os.close(f)
2543
2544 def tearDown(self):
2545 os.remove(self.fname)
2546 super().tearDown()
2547
2548 def with_spaces(self, *args, **kwargs):
2549 kwargs['stdout'] = subprocess.PIPE
2550 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002551 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002552 self.assertEqual(
2553 p.stdout.read ().decode("mbcs"),
2554 "2 [%r, 'ab cd']" % self.fname
2555 )
2556
2557 def test_shell_string_with_spaces(self):
2558 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002559 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2560 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002561
2562 def test_shell_sequence_with_spaces(self):
2563 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002564 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002565
2566 def test_noshell_string_with_spaces(self):
2567 # call() function with string argument with spaces on Windows
2568 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2569 "ab cd"))
2570
2571 def test_noshell_sequence_with_spaces(self):
2572 # call() function with sequence argument with spaces on Windows
2573 self.with_spaces([sys.executable, self.fname, "ab cd"])
2574
Brian Curtin79cdb662010-12-03 02:46:02 +00002575
Georg Brandla86b2622012-02-20 21:34:57 +01002576class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002577
2578 def test_pipe(self):
2579 with subprocess.Popen([sys.executable, "-c",
2580 "import sys;"
2581 "sys.stdout.write('stdout');"
2582 "sys.stderr.write('stderr');"],
2583 stdout=subprocess.PIPE,
2584 stderr=subprocess.PIPE) as proc:
2585 self.assertEqual(proc.stdout.read(), b"stdout")
2586 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2587
2588 self.assertTrue(proc.stdout.closed)
2589 self.assertTrue(proc.stderr.closed)
2590
2591 def test_returncode(self):
2592 with subprocess.Popen([sys.executable, "-c",
2593 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002594 pass
2595 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002596 self.assertEqual(proc.returncode, 100)
2597
2598 def test_communicate_stdin(self):
2599 with subprocess.Popen([sys.executable, "-c",
2600 "import sys;"
2601 "sys.exit(sys.stdin.read() == 'context')"],
2602 stdin=subprocess.PIPE) as proc:
2603 proc.communicate(b"context")
2604 self.assertEqual(proc.returncode, 1)
2605
2606 def test_invalid_args(self):
Andrew Svetlovb1726972012-12-26 23:34:54 +02002607 with self.assertRaises(FileNotFoundError) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002608 with subprocess.Popen(['nonexisting_i_hope'],
2609 stdout=subprocess.PIPE,
2610 stderr=subprocess.PIPE) as proc:
2611 pass
2612
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002613 def test_broken_pipe_cleanup(self):
2614 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002615 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002616 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002617 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002618 proc = proc.__enter__()
2619 # Prepare to send enough data to overflow any OS pipe buffering and
2620 # guarantee a broken pipe error. Data is held in BufferedWriter
2621 # buffer until closed.
2622 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002623 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002624 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002625 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002626 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002627 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002628
Brian Curtin79cdb662010-12-03 02:46:02 +00002629
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002630def test_main():
2631 unit_tests = (ProcessTestCase,
2632 POSIXProcessTestCase,
2633 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002634 CommandTests,
2635 ProcessTestCaseNoPoll,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002636 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002637 ContextManagerTests,
Gregory P. Smith6e730002015-04-14 16:14:25 -07002638 RunFuncTestCase,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002639 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002640
2641 support.run_unittest(*unit_tests)
2642 support.reap_children()
2643
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002644if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002645 unittest.main()