blob: 637b1bff8563897d86a91524575feecbc996325a [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Chris Jerdonekec3ea942012-09-30 00:10:28 -07002from test 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
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000015import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000016import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040017import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050018import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030019import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050020
21try:
Antoine Pitroua8392712013-08-30 23:38:13 +020022 import threading
23except ImportError:
24 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050025
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000026mswindows = (sys.platform == "win32")
27
28#
29# Depends on the following external programs: Python
30#
31
32if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000033 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
34 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000035else:
36 SETBINARY = ''
37
Florent Xiclunab1e94e82010-02-27 22:12:37 +000038
39try:
40 mkstemp = tempfile.mkstemp
41except AttributeError:
42 # tempfile.mkstemp is not available
43 def mkstemp():
44 """Replacement for mkstemp, calling mktemp."""
45 fname = tempfile.mktemp()
46 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
47
Tim Peters3761e8d2004-10-13 04:07:12 +000048
Florent Xiclunac049d872010-03-27 22:47:23 +000049class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000050 def setUp(self):
51 # Try to minimize the number of children we have so this test
52 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000053 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000055 def tearDown(self):
56 for inst in subprocess._active:
57 inst.wait()
58 subprocess._cleanup()
59 self.assertFalse(subprocess._active, "subprocess._active not empty")
60
Florent Xiclunab1e94e82010-02-27 22:12:37 +000061 def assertStderrEqual(self, stderr, expected, msg=None):
62 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
63 # shutdown time. That frustrates tests trying to check stderr produced
64 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000065 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040066 # strip_python_stderr also strips whitespace, so we do too.
67 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000068 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069
Florent Xiclunac049d872010-03-27 22:47:23 +000070
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080071class PopenTestException(Exception):
72 pass
73
74
75class PopenExecuteChildRaises(subprocess.Popen):
76 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
77 _execute_child fails.
78 """
79 def _execute_child(self, *args, **kwargs):
80 raise PopenTestException("Forced Exception for Test")
81
82
Florent Xiclunac049d872010-03-27 22:47:23 +000083class ProcessTestCase(BaseTestCase):
84
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070085 def test_io_buffered_by_default(self):
86 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
87 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
88 stderr=subprocess.PIPE)
89 try:
90 self.assertIsInstance(p.stdin, io.BufferedIOBase)
91 self.assertIsInstance(p.stdout, io.BufferedIOBase)
92 self.assertIsInstance(p.stderr, io.BufferedIOBase)
93 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070094 p.stdin.close()
95 p.stdout.close()
96 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070097 p.wait()
98
99 def test_io_unbuffered_works(self):
100 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
101 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
102 stderr=subprocess.PIPE, bufsize=0)
103 try:
104 self.assertIsInstance(p.stdin, io.RawIOBase)
105 self.assertIsInstance(p.stdout, io.RawIOBase)
106 self.assertIsInstance(p.stderr, io.RawIOBase)
107 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700108 p.stdin.close()
109 p.stdout.close()
110 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700111 p.wait()
112
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000113 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000114 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000115 rc = subprocess.call([sys.executable, "-c",
116 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000117 self.assertEqual(rc, 47)
118
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400119 def test_call_timeout(self):
120 # call() function with timeout argument; we want to test that the child
121 # process gets killed when the timeout expires. If the child isn't
122 # killed, this call will deadlock since subprocess.call waits for the
123 # child.
124 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
125 [sys.executable, "-c", "while True: pass"],
126 timeout=0.1)
127
Peter Astrand454f7672005-01-01 09:36:35 +0000128 def test_check_call_zero(self):
129 # check_call() function with zero return code
130 rc = subprocess.check_call([sys.executable, "-c",
131 "import sys; sys.exit(0)"])
132 self.assertEqual(rc, 0)
133
134 def test_check_call_nonzero(self):
135 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000136 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000137 subprocess.check_call([sys.executable, "-c",
138 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000139 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000140
Georg Brandlf9734072008-12-07 15:30:06 +0000141 def test_check_output(self):
142 # check_output() function with zero return code
143 output = subprocess.check_output(
144 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000145 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000146
147 def test_check_output_nonzero(self):
148 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000149 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000150 subprocess.check_output(
151 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000152 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000153
154 def test_check_output_stderr(self):
155 # check_output() function stderr redirected to stdout
156 output = subprocess.check_output(
157 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
158 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000159 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000160
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300161 def test_check_output_stdin_arg(self):
162 # check_output() can be called with stdin set to a file
163 tf = tempfile.TemporaryFile()
164 self.addCleanup(tf.close)
165 tf.write(b'pear')
166 tf.seek(0)
167 output = subprocess.check_output(
168 [sys.executable, "-c",
169 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
170 stdin=tf)
171 self.assertIn(b'PEAR', output)
172
173 def test_check_output_input_arg(self):
174 # check_output() can be called with input set to a string
175 output = subprocess.check_output(
176 [sys.executable, "-c",
177 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
178 input=b'pear')
179 self.assertIn(b'PEAR', output)
180
Georg Brandlf9734072008-12-07 15:30:06 +0000181 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300182 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000183 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000184 output = subprocess.check_output(
185 [sys.executable, "-c", "print('will not be run')"],
186 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000187 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000188 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000189
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300190 def test_check_output_stdin_with_input_arg(self):
191 # check_output() refuses to accept 'stdin' with 'input'
192 tf = tempfile.TemporaryFile()
193 self.addCleanup(tf.close)
194 tf.write(b'pear')
195 tf.seek(0)
196 with self.assertRaises(ValueError) as c:
197 output = subprocess.check_output(
198 [sys.executable, "-c", "print('will not be run')"],
199 stdin=tf, input=b'hare')
200 self.fail("Expected ValueError when stdin and input args supplied.")
201 self.assertIn('stdin', c.exception.args[0])
202 self.assertIn('input', c.exception.args[0])
203
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400204 def test_check_output_timeout(self):
205 # check_output() function with timeout arg
206 with self.assertRaises(subprocess.TimeoutExpired) as c:
207 output = subprocess.check_output(
208 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200209 "import sys, time\n"
210 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400211 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200212 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400213 # Some heavily loaded buildbots (sparc Debian 3.x) require
214 # this much time to start and print.
215 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400216 self.fail("Expected TimeoutExpired.")
217 self.assertEqual(c.exception.output, b'BDFL')
218
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000219 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000220 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000221 newenv = os.environ.copy()
222 newenv["FRUIT"] = "banana"
223 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000224 'import sys, os;'
225 'sys.exit(os.getenv("FRUIT")=="banana")'],
226 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 self.assertEqual(rc, 1)
228
Victor Stinner87b9bc32011-06-01 00:57:47 +0200229 def test_invalid_args(self):
230 # Popen() called with invalid arguments should raise TypeError
231 # but Popen.__del__ should not complain (issue #12085)
232 with support.captured_stderr() as s:
233 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
234 argcount = subprocess.Popen.__init__.__code__.co_argcount
235 too_many_args = [0] * (argcount + 1)
236 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
237 self.assertEqual(s.getvalue(), '')
238
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000240 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000241 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000243 self.addCleanup(p.stdout.close)
244 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 p.wait()
246 self.assertEqual(p.stdin, None)
247
248 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200249 # .stdout is None when not redirected, and the child's stdout will
250 # be inherited from the parent. In order to test this we run a
251 # subprocess in a subprocess:
252 # this_test
253 # \-- subprocess created by this test (parent)
254 # \-- subprocess created by the parent subprocess (child)
255 # The parent doesn't specify stdout, so the child will use the
256 # parent's stdout. This test checks that the message printed by the
257 # child goes to the parent stdout. The parent also checks that the
258 # child's stdout is None. See #11963.
259 code = ('import sys; from subprocess import Popen, PIPE;'
260 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
261 ' stdin=PIPE, stderr=PIPE);'
262 'p.wait(); assert p.stdout is None;')
263 p = subprocess.Popen([sys.executable, "-c", code],
264 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
265 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000266 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200267 out, err = p.communicate()
268 self.assertEqual(p.returncode, 0, err)
269 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270
271 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000272 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000273 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000275 self.addCleanup(p.stdout.close)
276 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000277 p.wait()
278 self.assertEqual(p.stderr, None)
279
Chris Jerdonek776cb192012-10-08 15:56:43 -0700280 def _assert_python(self, pre_args, **kwargs):
281 # We include sys.exit() to prevent the test runner from hanging
282 # whenever python is found.
283 args = pre_args + ["import sys; sys.exit(47)"]
284 p = subprocess.Popen(args, **kwargs)
285 p.wait()
286 self.assertEqual(47, p.returncode)
287
288 def test_executable(self):
289 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700290 #
291 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
292 # determine where its standard library is, so we need the directory
293 # of args[0] to be valid for the Popen() call to Python to succeed.
294 # See also issue #16170 and issue #7774.
295 doesnotexist = os.path.join(os.path.dirname(sys.executable),
296 "doesnotexist")
297 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700298
299 def test_executable_takes_precedence(self):
300 # Check that the executable argument takes precedence over args[0].
301 #
302 # Verify first that the call succeeds without the executable arg.
303 pre_args = [sys.executable, "-c"]
304 self._assert_python(pre_args)
305 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
306 executable="doesnotexist")
307
308 @unittest.skipIf(mswindows, "executable argument replaces shell")
309 def test_executable_replaces_shell(self):
310 # Check that the executable argument replaces the default shell
311 # when shell=True.
312 self._assert_python([], executable=sys.executable, shell=True)
313
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700314 # For use in the test_cwd* tests below.
315 def _normalize_cwd(self, cwd):
316 # Normalize an expected cwd (for Tru64 support).
317 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
318 # strings. See bug #1063571.
319 original_cwd = os.getcwd()
320 os.chdir(cwd)
321 cwd = os.getcwd()
322 os.chdir(original_cwd)
323 return cwd
324
325 # For use in the test_cwd* tests below.
326 def _split_python_path(self):
327 # Return normalized (python_dir, python_base).
328 python_path = os.path.realpath(sys.executable)
329 return os.path.split(python_path)
330
331 # For use in the test_cwd* tests below.
332 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
333 # Invoke Python via Popen, and assert that (1) the call succeeds,
334 # and that (2) the current working directory of the child process
335 # matches *expected_cwd*.
336 p = subprocess.Popen([python_arg, "-c",
337 "import os, sys; "
338 "sys.stdout.write(os.getcwd()); "
339 "sys.exit(47)"],
340 stdout=subprocess.PIPE,
341 **kwargs)
342 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000343 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700344 self.assertEqual(47, p.returncode)
345 normcase = os.path.normcase
346 self.assertEqual(normcase(expected_cwd),
347 normcase(p.stdout.read().decode("utf-8")))
348
349 def test_cwd(self):
350 # Check that cwd changes the cwd for the child process.
351 temp_dir = tempfile.gettempdir()
352 temp_dir = self._normalize_cwd(temp_dir)
353 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
354
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700355 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700356 def test_cwd_with_relative_arg(self):
357 # Check that Popen looks for args[0] relative to cwd if args[0]
358 # is relative.
359 python_dir, python_base = self._split_python_path()
360 rel_python = os.path.join(os.curdir, python_base)
361 with support.temp_cwd() as wrong_dir:
362 # Before calling with the correct cwd, confirm that the call fails
363 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700364 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700365 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700366 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700367 [rel_python], cwd=wrong_dir)
368 python_dir = self._normalize_cwd(python_dir)
369 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
370
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700371 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700372 def test_cwd_with_relative_executable(self):
373 # Check that Popen looks for executable relative to cwd if executable
374 # is relative (and that executable takes precedence over args[0]).
375 python_dir, python_base = self._split_python_path()
376 rel_python = os.path.join(os.curdir, python_base)
377 doesntexist = "somethingyoudonthave"
378 with support.temp_cwd() as wrong_dir:
379 # Before calling with the correct cwd, confirm that the call fails
380 # without cwd and with the wrong cwd.
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)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700383 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700384 [doesntexist], executable=rel_python,
385 cwd=wrong_dir)
386 python_dir = self._normalize_cwd(python_dir)
387 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
388 cwd=python_dir)
389
390 def test_cwd_with_absolute_arg(self):
391 # Check that Popen can find the executable when the cwd is wrong
392 # if args[0] is an absolute path.
393 python_dir, python_base = self._split_python_path()
394 abs_python = os.path.join(python_dir, python_base)
395 rel_python = os.path.join(os.curdir, python_base)
396 with script_helper.temp_dir() as wrong_dir:
397 # Before calling with an absolute path, confirm that using a
398 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700399 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700400 [rel_python], cwd=wrong_dir)
401 wrong_dir = self._normalize_cwd(wrong_dir)
402 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
403
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100404 @unittest.skipIf(sys.base_prefix != sys.prefix,
405 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000406 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700407 python_dir, python_base = self._split_python_path()
408 python_dir = self._normalize_cwd(python_dir)
409 self._assert_cwd(python_dir, "somethingyoudonthave",
410 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000411
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100412 @unittest.skipIf(sys.base_prefix != sys.prefix,
413 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000414 @unittest.skipIf(sysconfig.is_python_build(),
415 "need an installed Python. See #7774")
416 def test_executable_without_cwd(self):
417 # For a normal installation, it should work without 'cwd'
418 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700419 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
420 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000421
422 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000423 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424 p = subprocess.Popen([sys.executable, "-c",
425 'import sys; sys.exit(sys.stdin.read() == "pear")'],
426 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000427 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000428 p.stdin.close()
429 p.wait()
430 self.assertEqual(p.returncode, 1)
431
432 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000433 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000434 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000435 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000436 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000437 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438 os.lseek(d, 0, 0)
439 p = subprocess.Popen([sys.executable, "-c",
440 'import sys; sys.exit(sys.stdin.read() == "pear")'],
441 stdin=d)
442 p.wait()
443 self.assertEqual(p.returncode, 1)
444
445 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000446 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000447 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000448 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000449 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000450 tf.seek(0)
451 p = subprocess.Popen([sys.executable, "-c",
452 'import sys; sys.exit(sys.stdin.read() == "pear")'],
453 stdin=tf)
454 p.wait()
455 self.assertEqual(p.returncode, 1)
456
457 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000458 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459 p = subprocess.Popen([sys.executable, "-c",
460 'import sys; sys.stdout.write("orange")'],
461 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000462 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000463 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464
465 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000466 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000467 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000468 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000469 d = tf.fileno()
470 p = subprocess.Popen([sys.executable, "-c",
471 'import sys; sys.stdout.write("orange")'],
472 stdout=d)
473 p.wait()
474 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000475 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476
477 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000478 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000479 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000480 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481 p = subprocess.Popen([sys.executable, "-c",
482 'import sys; sys.stdout.write("orange")'],
483 stdout=tf)
484 p.wait()
485 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000486 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000487
488 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000489 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490 p = subprocess.Popen([sys.executable, "-c",
491 'import sys; sys.stderr.write("strawberry")'],
492 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000493 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000494 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495
496 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000497 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000498 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000499 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500 d = tf.fileno()
501 p = subprocess.Popen([sys.executable, "-c",
502 'import sys; sys.stderr.write("strawberry")'],
503 stderr=d)
504 p.wait()
505 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000506 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507
508 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000509 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000510 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000511 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 p = subprocess.Popen([sys.executable, "-c",
513 'import sys; sys.stderr.write("strawberry")'],
514 stderr=tf)
515 p.wait()
516 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000517 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518
519 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000520 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000521 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000522 'import sys;'
523 'sys.stdout.write("apple");'
524 'sys.stdout.flush();'
525 'sys.stderr.write("orange")'],
526 stdout=subprocess.PIPE,
527 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000528 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000529 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530
531 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000532 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000533 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000534 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000535 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000536 'import sys;'
537 'sys.stdout.write("apple");'
538 'sys.stdout.flush();'
539 'sys.stderr.write("orange")'],
540 stdout=tf,
541 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542 p.wait()
543 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000544 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545
Thomas Wouters89f507f2006-12-13 04:49:30 +0000546 def test_stdout_filedes_of_stdout(self):
547 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200548 # To avoid printing the text on stdout, we do something similar to
549 # test_stdout_none (see above). The parent subprocess calls the child
550 # subprocess passing stdout=1, and this test uses stdout=PIPE in
551 # order to capture and check the output of the parent. See #11963.
552 code = ('import sys, subprocess; '
553 'rc = subprocess.call([sys.executable, "-c", '
554 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
555 'b\'test with stdout=1\'))"], stdout=1); '
556 'assert rc == 18')
557 p = subprocess.Popen([sys.executable, "-c", code],
558 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
559 self.addCleanup(p.stdout.close)
560 self.addCleanup(p.stderr.close)
561 out, err = p.communicate()
562 self.assertEqual(p.returncode, 0, err)
563 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000564
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200565 def test_stdout_devnull(self):
566 p = subprocess.Popen([sys.executable, "-c",
567 'for i in range(10240):'
568 'print("x" * 1024)'],
569 stdout=subprocess.DEVNULL)
570 p.wait()
571 self.assertEqual(p.stdout, None)
572
573 def test_stderr_devnull(self):
574 p = subprocess.Popen([sys.executable, "-c",
575 'import sys\n'
576 'for i in range(10240):'
577 'sys.stderr.write("x" * 1024)'],
578 stderr=subprocess.DEVNULL)
579 p.wait()
580 self.assertEqual(p.stderr, None)
581
582 def test_stdin_devnull(self):
583 p = subprocess.Popen([sys.executable, "-c",
584 'import sys;'
585 'sys.stdin.read(1)'],
586 stdin=subprocess.DEVNULL)
587 p.wait()
588 self.assertEqual(p.stdin, None)
589
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000590 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000591 newenv = os.environ.copy()
592 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200593 with subprocess.Popen([sys.executable, "-c",
594 'import sys,os;'
595 'sys.stdout.write(os.getenv("FRUIT"))'],
596 stdout=subprocess.PIPE,
597 env=newenv) as p:
598 stdout, stderr = p.communicate()
599 self.assertEqual(stdout, b"orange")
600
Victor Stinner62d51182011-06-23 01:02:25 +0200601 # Windows requires at least the SYSTEMROOT environment variable to start
602 # Python
603 @unittest.skipIf(sys.platform == 'win32',
604 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200605 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200606 'the python library cannot be loaded '
607 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200608 def test_empty_env(self):
609 with subprocess.Popen([sys.executable, "-c",
610 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200611 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200612 stdout=subprocess.PIPE,
613 env={}) as p:
614 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200615 self.assertIn(stdout.strip(),
616 (b"[]",
617 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
618 # environment
619 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000620
Peter Astrandcbac93c2005-03-03 20:24:28 +0000621 def test_communicate_stdin(self):
622 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000623 'import sys;'
624 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000625 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000626 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000627 self.assertEqual(p.returncode, 1)
628
629 def test_communicate_stdout(self):
630 p = subprocess.Popen([sys.executable, "-c",
631 'import sys; sys.stdout.write("pineapple")'],
632 stdout=subprocess.PIPE)
633 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000634 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000635 self.assertEqual(stderr, None)
636
637 def test_communicate_stderr(self):
638 p = subprocess.Popen([sys.executable, "-c",
639 'import sys; sys.stderr.write("pineapple")'],
640 stderr=subprocess.PIPE)
641 (stdout, stderr) = p.communicate()
642 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000643 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000644
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000645 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000647 'import sys,os;'
648 'sys.stderr.write("pineapple");'
649 'sys.stdout.write(sys.stdin.read())'],
650 stdin=subprocess.PIPE,
651 stdout=subprocess.PIPE,
652 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000653 self.addCleanup(p.stdout.close)
654 self.addCleanup(p.stderr.close)
655 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000656 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000657 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000658 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400660 def test_communicate_timeout(self):
661 p = subprocess.Popen([sys.executable, "-c",
662 'import sys,os,time;'
663 'sys.stderr.write("pineapple\\n");'
664 'time.sleep(1);'
665 'sys.stderr.write("pear\\n");'
666 'sys.stdout.write(sys.stdin.read())'],
667 universal_newlines=True,
668 stdin=subprocess.PIPE,
669 stdout=subprocess.PIPE,
670 stderr=subprocess.PIPE)
671 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
672 timeout=0.3)
673 # Make sure we can keep waiting for it, and that we get the whole output
674 # after it completes.
675 (stdout, stderr) = p.communicate()
676 self.assertEqual(stdout, "banana")
677 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
678
679 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200680 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400681 p = subprocess.Popen([sys.executable, "-c",
682 'import sys,os,time;'
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 'time.sleep(0.2);'
689 'sys.stdout.write("a" * (64 * 1024));'],
690 stdout=subprocess.PIPE)
691 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
692 (stdout, _) = p.communicate()
693 self.assertEqual(len(stdout), 4 * 64 * 1024)
694
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000695 # Test for the fd leak reported in http://bugs.python.org/issue2791.
696 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000697 for stdin_pipe in (False, True):
698 for stdout_pipe in (False, True):
699 for stderr_pipe in (False, True):
700 options = {}
701 if stdin_pipe:
702 options['stdin'] = subprocess.PIPE
703 if stdout_pipe:
704 options['stdout'] = subprocess.PIPE
705 if stderr_pipe:
706 options['stderr'] = subprocess.PIPE
707 if not options:
708 continue
709 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
710 p.communicate()
711 if p.stdin is not None:
712 self.assertTrue(p.stdin.closed)
713 if p.stdout is not None:
714 self.assertTrue(p.stdout.closed)
715 if p.stderr is not None:
716 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000717
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000718 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000719 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000720 p = subprocess.Popen([sys.executable, "-c",
721 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000722 (stdout, stderr) = p.communicate()
723 self.assertEqual(stdout, None)
724 self.assertEqual(stderr, None)
725
726 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000727 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000728 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000729 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 os.close(x)
732 os.close(y)
733 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000734 'import sys,os;'
735 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200736 'sys.stderr.write("x" * %d);'
737 'sys.stdout.write(sys.stdin.read())' %
738 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000739 stdin=subprocess.PIPE,
740 stdout=subprocess.PIPE,
741 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000742 self.addCleanup(p.stdout.close)
743 self.addCleanup(p.stderr.close)
744 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200745 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000746 (stdout, stderr) = p.communicate(string_to_write)
747 self.assertEqual(stdout, string_to_write)
748
749 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000750 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000751 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000752 'import sys,os;'
753 'sys.stdout.write(sys.stdin.read())'],
754 stdin=subprocess.PIPE,
755 stdout=subprocess.PIPE,
756 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000757 self.addCleanup(p.stdout.close)
758 self.addCleanup(p.stderr.close)
759 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000760 p.stdin.write(b"banana")
761 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000762 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000763 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000764
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000765 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000767 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200768 'buf = sys.stdout.buffer;'
769 'buf.write(sys.stdin.readline().encode());'
770 'buf.flush();'
771 'buf.write(b"line2\\n");'
772 'buf.flush();'
773 'buf.write(sys.stdin.read().encode());'
774 'buf.flush();'
775 'buf.write(b"line4\\n");'
776 'buf.flush();'
777 'buf.write(b"line5\\r\\n");'
778 'buf.flush();'
779 'buf.write(b"line6\\r");'
780 'buf.flush();'
781 'buf.write(b"\\nline7");'
782 'buf.flush();'
783 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200784 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000785 stdout=subprocess.PIPE,
786 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200787 p.stdin.write("line1\n")
788 self.assertEqual(p.stdout.readline(), "line1\n")
789 p.stdin.write("line3\n")
790 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000791 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200792 self.assertEqual(p.stdout.readline(),
793 "line2\n")
794 self.assertEqual(p.stdout.read(6),
795 "line3\n")
796 self.assertEqual(p.stdout.read(),
797 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000798
799 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000800 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000801 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000802 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200803 'buf = sys.stdout.buffer;'
804 'buf.write(b"line2\\n");'
805 'buf.flush();'
806 'buf.write(b"line4\\n");'
807 'buf.flush();'
808 'buf.write(b"line5\\r\\n");'
809 'buf.flush();'
810 'buf.write(b"line6\\r");'
811 'buf.flush();'
812 'buf.write(b"\\nline7");'
813 'buf.flush();'
814 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200815 stderr=subprocess.PIPE,
816 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000817 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000818 self.addCleanup(p.stdout.close)
819 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000820 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200821 self.assertEqual(stdout,
822 "line2\nline4\nline5\nline6\nline7\nline8")
823
824 def test_universal_newlines_communicate_stdin(self):
825 # universal newlines through communicate(), with only stdin
826 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300827 'import sys,os;' + SETBINARY + textwrap.dedent('''
828 s = sys.stdin.readline()
829 assert s == "line1\\n", repr(s)
830 s = sys.stdin.read()
831 assert s == "line3\\n", repr(s)
832 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200833 stdin=subprocess.PIPE,
834 universal_newlines=1)
835 (stdout, stderr) = p.communicate("line1\nline3\n")
836 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000837
Andrew Svetlovf3765072012-08-14 18:35:17 +0300838 def test_universal_newlines_communicate_input_none(self):
839 # Test communicate(input=None) with universal newlines.
840 #
841 # We set stdout to PIPE because, as of this writing, a different
842 # code path is tested when the number of pipes is zero or one.
843 p = subprocess.Popen([sys.executable, "-c", "pass"],
844 stdin=subprocess.PIPE,
845 stdout=subprocess.PIPE,
846 universal_newlines=True)
847 p.communicate()
848 self.assertEqual(p.returncode, 0)
849
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300850 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300851 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300852 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300853 'import sys,os;' + SETBINARY + textwrap.dedent('''
854 s = sys.stdin.buffer.readline()
855 sys.stdout.buffer.write(s)
856 sys.stdout.buffer.write(b"line2\\r")
857 sys.stderr.buffer.write(b"eline2\\n")
858 s = sys.stdin.buffer.read()
859 sys.stdout.buffer.write(s)
860 sys.stdout.buffer.write(b"line4\\n")
861 sys.stdout.buffer.write(b"line5\\r\\n")
862 sys.stderr.buffer.write(b"eline6\\r")
863 sys.stderr.buffer.write(b"eline7\\r\\nz")
864 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300865 stdin=subprocess.PIPE,
866 stderr=subprocess.PIPE,
867 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300868 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300869 self.addCleanup(p.stdout.close)
870 self.addCleanup(p.stderr.close)
871 (stdout, stderr) = p.communicate("line1\nline3\n")
872 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300873 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300874 # Python debug build push something like "[42442 refs]\n"
875 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300876 # Don't use assertStderrEqual because it strips CR and LF from output.
877 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300878
Andrew Svetlov82860712012-08-19 22:13:41 +0300879 def test_universal_newlines_communicate_encodings(self):
880 # Check that universal newlines mode works for various encodings,
881 # in particular for encodings in the UTF-16 and UTF-32 families.
882 # See issue #15595.
883 #
884 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
885 # without, and UTF-16 and UTF-32.
886 for encoding in ['utf-16', 'utf-32-be']:
887 old_getpreferredencoding = locale.getpreferredencoding
888 # 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:
898 locale.getpreferredencoding = getpreferredencoding
899 # 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:
907 locale.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
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001008 def test_leaking_fds_on_error(self):
1009 # see bug #5179: Popen leaks file descriptors to PIPEs if
1010 # the child fails to execute; this will eventually exhaust
1011 # the maximum number of open fds. 1024 seems a very common
1012 # value for that limit, but Windows has 2048, so we loop
1013 # 1024 times (each call leaked two fds).
1014 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001015 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001016 subprocess.Popen(['nonexisting_i_hope'],
1017 stdout=subprocess.PIPE,
1018 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001019 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001020 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001021 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001022
Antoine Pitroua8392712013-08-30 23:38:13 +02001023 @unittest.skipIf(threading is None, "threading required")
1024 def test_double_close_on_error(self):
1025 # Issue #18851
1026 fds = []
1027 def open_fds():
1028 for i in range(20):
1029 fds.extend(os.pipe())
1030 time.sleep(0.001)
1031 t = threading.Thread(target=open_fds)
1032 t.start()
1033 try:
1034 with self.assertRaises(EnvironmentError):
1035 subprocess.Popen(['nonexisting_i_hope'],
1036 stdin=subprocess.PIPE,
1037 stdout=subprocess.PIPE,
1038 stderr=subprocess.PIPE)
1039 finally:
1040 t.join()
1041 exc = None
1042 for fd in fds:
1043 # If a double close occurred, some of those fds will
1044 # already have been closed by mistake, and os.close()
1045 # here will raise.
1046 try:
1047 os.close(fd)
1048 except OSError as e:
1049 exc = e
1050 if exc is not None:
1051 raise exc
1052
Victor Stinnerb3693582010-05-21 20:13:12 +00001053 def test_issue8780(self):
1054 # Ensure that stdout is inherited from the parent
1055 # if stdout=PIPE is not used
1056 code = ';'.join((
1057 'import subprocess, sys',
1058 'retcode = subprocess.call('
1059 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1060 'assert retcode == 0'))
1061 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001062 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001063
Tim Goldenaf5ac392010-08-06 13:03:56 +00001064 def test_handles_closed_on_exception(self):
1065 # If CreateProcess exits with an error, ensure the
1066 # duplicate output handles are released
1067 ifhandle, ifname = mkstemp()
1068 ofhandle, ofname = mkstemp()
1069 efhandle, efname = mkstemp()
1070 try:
1071 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1072 stderr=efhandle)
1073 except OSError:
1074 os.close(ifhandle)
1075 os.remove(ifname)
1076 os.close(ofhandle)
1077 os.remove(ofname)
1078 os.close(efhandle)
1079 os.remove(efname)
1080 self.assertFalse(os.path.exists(ifname))
1081 self.assertFalse(os.path.exists(ofname))
1082 self.assertFalse(os.path.exists(efname))
1083
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001084 def test_communicate_epipe(self):
1085 # Issue 10963: communicate() should hide EPIPE
1086 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1087 stdin=subprocess.PIPE,
1088 stdout=subprocess.PIPE,
1089 stderr=subprocess.PIPE)
1090 self.addCleanup(p.stdout.close)
1091 self.addCleanup(p.stderr.close)
1092 self.addCleanup(p.stdin.close)
1093 p.communicate(b"x" * 2**20)
1094
1095 def test_communicate_epipe_only_stdin(self):
1096 # Issue 10963: communicate() should hide EPIPE
1097 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1098 stdin=subprocess.PIPE)
1099 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001100 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001101 p.communicate(b"x" * 2**20)
1102
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001103 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1104 "Requires signal.SIGUSR1")
1105 @unittest.skipUnless(hasattr(os, 'kill'),
1106 "Requires os.kill")
1107 @unittest.skipUnless(hasattr(os, 'getppid'),
1108 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001109 def test_communicate_eintr(self):
1110 # Issue #12493: communicate() should handle EINTR
1111 def handler(signum, frame):
1112 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001113 old_handler = signal.signal(signal.SIGUSR1, handler)
1114 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001115
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001116 args = [sys.executable, "-c",
1117 'import os, signal;'
1118 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001119 for stream in ('stdout', 'stderr'):
1120 kw = {stream: subprocess.PIPE}
1121 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001122 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001123 process.communicate()
1124
Tim Peterse718f612004-10-12 21:51:32 +00001125
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001126 # This test is Linux-ish specific for simplicity to at least have
1127 # some coverage. It is not a platform specific bug.
1128 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1129 "Linux specific")
1130 def test_failed_child_execute_fd_leak(self):
1131 """Test for the fork() failure fd leak reported in issue16327."""
1132 fd_directory = '/proc/%d/fd' % os.getpid()
1133 fds_before_popen = os.listdir(fd_directory)
1134 with self.assertRaises(PopenTestException):
1135 PopenExecuteChildRaises(
1136 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1137 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1138
1139 # NOTE: This test doesn't verify that the real _execute_child
1140 # does not close the file descriptors itself on the way out
1141 # during an exception. Code inspection has confirmed that.
1142
1143 fds_after_exception = os.listdir(fd_directory)
1144 self.assertEqual(fds_before_popen, fds_after_exception)
1145
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001146@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001147class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001148
Gregory P. Smith5591b022012-10-10 03:34:47 -07001149 def setUp(self):
1150 super().setUp()
1151 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1152
1153 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001154 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001155 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001156 except OSError as e:
1157 # This avoids hard coding the errno value or the OS perror()
1158 # string and instead capture the exception that we want to see
1159 # below for comparison.
1160 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001161 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001162 else:
1163 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001164 self._nonexistent_dir)
1165 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001166
Gregory P. Smith5591b022012-10-10 03:34:47 -07001167 def test_exception_cwd(self):
1168 """Test error in the child raised in the parent for a bad cwd."""
1169 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001170 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001171 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001172 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001173 except OSError as e:
1174 # Test that the child process chdir failure actually makes
1175 # it up to the parent process as the correct exception.
1176 self.assertEqual(desired_exception.errno, e.errno)
1177 self.assertEqual(desired_exception.strerror, e.strerror)
1178 else:
1179 self.fail("Expected OSError: %s" % desired_exception)
1180
Gregory P. Smith5591b022012-10-10 03:34:47 -07001181 def test_exception_bad_executable(self):
1182 """Test error in the child raised in the parent for a bad executable."""
1183 desired_exception = self._get_chdir_exception()
1184 try:
1185 p = subprocess.Popen([sys.executable, "-c", ""],
1186 executable=self._nonexistent_dir)
1187 except OSError as e:
1188 # Test that the child process exec failure actually makes
1189 # it up to the parent process as the correct exception.
1190 self.assertEqual(desired_exception.errno, e.errno)
1191 self.assertEqual(desired_exception.strerror, e.strerror)
1192 else:
1193 self.fail("Expected OSError: %s" % desired_exception)
1194
1195 def test_exception_bad_args_0(self):
1196 """Test error in the child raised in the parent for a bad args[0]."""
1197 desired_exception = self._get_chdir_exception()
1198 try:
1199 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1200 except OSError as e:
1201 # Test that the child process exec failure actually makes
1202 # it up to the parent process as the correct exception.
1203 self.assertEqual(desired_exception.errno, e.errno)
1204 self.assertEqual(desired_exception.strerror, e.strerror)
1205 else:
1206 self.fail("Expected OSError: %s" % desired_exception)
1207
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001208 def test_restore_signals(self):
1209 # Code coverage for both values of restore_signals to make sure it
1210 # at least does not blow up.
1211 # A test for behavior would be complex. Contributions welcome.
1212 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1213 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1214
1215 def test_start_new_session(self):
1216 # For code coverage of calling setsid(). We don't care if we get an
1217 # EPERM error from it depending on the test execution environment, that
1218 # still indicates that it was called.
1219 try:
1220 output = subprocess.check_output(
1221 [sys.executable, "-c",
1222 "import os; print(os.getpgid(os.getpid()))"],
1223 start_new_session=True)
1224 except OSError as e:
1225 if e.errno != errno.EPERM:
1226 raise
1227 else:
1228 parent_pgid = os.getpgid(os.getpid())
1229 child_pgid = int(output)
1230 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001231
1232 def test_run_abort(self):
1233 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001234 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001235 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001236 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001237 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001238 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001239
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001240 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001241 # DISCLAIMER: Setting environment variables is *not* a good use
1242 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001243 p = subprocess.Popen([sys.executable, "-c",
1244 'import sys,os;'
1245 'sys.stdout.write(os.getenv("FRUIT"))'],
1246 stdout=subprocess.PIPE,
1247 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001248 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001249 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001250
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001251 def test_preexec_exception(self):
1252 def raise_it():
1253 raise ValueError("What if two swallows carried a coconut?")
1254 try:
1255 p = subprocess.Popen([sys.executable, "-c", ""],
1256 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001257 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001258 self.assertTrue(
1259 subprocess._posixsubprocess,
1260 "Expected a ValueError from the preexec_fn")
1261 except ValueError as e:
1262 self.assertIn("coconut", e.args[0])
1263 else:
1264 self.fail("Exception raised by preexec_fn did not make it "
1265 "to the parent process.")
1266
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001267 class _TestExecuteChildPopen(subprocess.Popen):
1268 """Used to test behavior at the end of _execute_child."""
1269 def __init__(self, testcase, *args, **kwargs):
1270 self._testcase = testcase
1271 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001272
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001273 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001274 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001275 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001276 finally:
1277 # Open a bunch of file descriptors and verify that
1278 # none of them are the same as the ones the Popen
1279 # instance is using for stdin/stdout/stderr.
1280 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1281 for _ in range(8)]
1282 try:
1283 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001284 self._testcase.assertNotIn(
1285 fd, (self.stdin.fileno(), self.stdout.fileno(),
1286 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001287 msg="At least one fd was closed early.")
1288 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001289 for fd in devzero_fds:
1290 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001291
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001292 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1293 def test_preexec_errpipe_does_not_double_close_pipes(self):
1294 """Issue16140: Don't double close pipes on preexec error."""
1295
1296 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001297 raise subprocess.SubprocessError(
1298 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001299
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001300 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001301 self._TestExecuteChildPopen(
1302 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001303 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1304 stderr=subprocess.PIPE, preexec_fn=raise_it)
1305
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001306 def test_preexec_gc_module_failure(self):
1307 # This tests the code that disables garbage collection if the child
1308 # process will execute any Python.
1309 def raise_runtime_error():
1310 raise RuntimeError("this shouldn't escape")
1311 enabled = gc.isenabled()
1312 orig_gc_disable = gc.disable
1313 orig_gc_isenabled = gc.isenabled
1314 try:
1315 gc.disable()
1316 self.assertFalse(gc.isenabled())
1317 subprocess.call([sys.executable, '-c', ''],
1318 preexec_fn=lambda: None)
1319 self.assertFalse(gc.isenabled(),
1320 "Popen enabled gc when it shouldn't.")
1321
1322 gc.enable()
1323 self.assertTrue(gc.isenabled())
1324 subprocess.call([sys.executable, '-c', ''],
1325 preexec_fn=lambda: None)
1326 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1327
1328 gc.disable = raise_runtime_error
1329 self.assertRaises(RuntimeError, subprocess.Popen,
1330 [sys.executable, '-c', ''],
1331 preexec_fn=lambda: None)
1332
1333 del gc.isenabled # force an AttributeError
1334 self.assertRaises(AttributeError, subprocess.Popen,
1335 [sys.executable, '-c', ''],
1336 preexec_fn=lambda: None)
1337 finally:
1338 gc.disable = orig_gc_disable
1339 gc.isenabled = orig_gc_isenabled
1340 if not enabled:
1341 gc.disable()
1342
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001343 def test_args_string(self):
1344 # args is a string
1345 fd, fname = mkstemp()
1346 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001347 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001348 fobj.write("#!/bin/sh\n")
1349 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1350 sys.executable)
1351 os.chmod(fname, 0o700)
1352 p = subprocess.Popen(fname)
1353 p.wait()
1354 os.remove(fname)
1355 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001356
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001357 def test_invalid_args(self):
1358 # invalid arguments should raise ValueError
1359 self.assertRaises(ValueError, subprocess.call,
1360 [sys.executable, "-c",
1361 "import sys; sys.exit(47)"],
1362 startupinfo=47)
1363 self.assertRaises(ValueError, subprocess.call,
1364 [sys.executable, "-c",
1365 "import sys; sys.exit(47)"],
1366 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001367
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001368 def test_shell_sequence(self):
1369 # Run command through the shell (sequence)
1370 newenv = os.environ.copy()
1371 newenv["FRUIT"] = "apple"
1372 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1373 stdout=subprocess.PIPE,
1374 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001375 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001376 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001377
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001378 def test_shell_string(self):
1379 # Run command through the shell (string)
1380 newenv = os.environ.copy()
1381 newenv["FRUIT"] = "apple"
1382 p = subprocess.Popen("echo $FRUIT", shell=1,
1383 stdout=subprocess.PIPE,
1384 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001385 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001386 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001387
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001388 def test_call_string(self):
1389 # call() function with string argument on UNIX
1390 fd, fname = mkstemp()
1391 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001392 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001393 fobj.write("#!/bin/sh\n")
1394 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1395 sys.executable)
1396 os.chmod(fname, 0o700)
1397 rc = subprocess.call(fname)
1398 os.remove(fname)
1399 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001400
Stefan Krah9542cc62010-07-19 14:20:53 +00001401 def test_specific_shell(self):
1402 # Issue #9265: Incorrect name passed as arg[0].
1403 shells = []
1404 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1405 for name in ['bash', 'ksh']:
1406 sh = os.path.join(prefix, name)
1407 if os.path.isfile(sh):
1408 shells.append(sh)
1409 if not shells: # Will probably work for any shell but csh.
1410 self.skipTest("bash or ksh required for this test")
1411 sh = '/bin/sh'
1412 if os.path.isfile(sh) and not os.path.islink(sh):
1413 # Test will fail if /bin/sh is a symlink to csh.
1414 shells.append(sh)
1415 for sh in shells:
1416 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1417 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001418 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001419 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1420
Florent Xicluna4886d242010-03-08 13:27:26 +00001421 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001422 # Do not inherit file handles from the parent.
1423 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001424 # Also set the SIGINT handler to the default to make sure it's not
1425 # being ignored (some tests rely on that.)
1426 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1427 try:
1428 p = subprocess.Popen([sys.executable, "-c", """if 1:
1429 import sys, time
1430 sys.stdout.write('x\\n')
1431 sys.stdout.flush()
1432 time.sleep(30)
1433 """],
1434 close_fds=True,
1435 stdin=subprocess.PIPE,
1436 stdout=subprocess.PIPE,
1437 stderr=subprocess.PIPE)
1438 finally:
1439 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001440 # Wait for the interpreter to be completely initialized before
1441 # sending any signal.
1442 p.stdout.read(1)
1443 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001444 return p
1445
Charles-François Natali53221e32013-01-12 16:52:20 +01001446 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1447 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001448 def _kill_dead_process(self, method, *args):
1449 # Do not inherit file handles from the parent.
1450 # It should fix failures on some platforms.
1451 p = subprocess.Popen([sys.executable, "-c", """if 1:
1452 import sys, time
1453 sys.stdout.write('x\\n')
1454 sys.stdout.flush()
1455 """],
1456 close_fds=True,
1457 stdin=subprocess.PIPE,
1458 stdout=subprocess.PIPE,
1459 stderr=subprocess.PIPE)
1460 # Wait for the interpreter to be completely initialized before
1461 # sending any signal.
1462 p.stdout.read(1)
1463 # The process should end after this
1464 time.sleep(1)
1465 # This shouldn't raise even though the child is now dead
1466 getattr(p, method)(*args)
1467 p.communicate()
1468
Florent Xicluna4886d242010-03-08 13:27:26 +00001469 def test_send_signal(self):
1470 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001471 _, stderr = p.communicate()
1472 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001473 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001474
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001475 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001476 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001477 _, stderr = p.communicate()
1478 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001479 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001480
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001481 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001482 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001483 _, stderr = p.communicate()
1484 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001485 self.assertEqual(p.wait(), -signal.SIGTERM)
1486
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001487 def test_send_signal_dead(self):
1488 # Sending a signal to a dead process
1489 self._kill_dead_process('send_signal', signal.SIGINT)
1490
1491 def test_kill_dead(self):
1492 # Killing a dead process
1493 self._kill_dead_process('kill')
1494
1495 def test_terminate_dead(self):
1496 # Terminating a dead process
1497 self._kill_dead_process('terminate')
1498
Victor Stinnerdaf45552013-08-28 00:53:59 +02001499 def _save_fds(self, save_fds):
1500 fds = []
1501 for fd in save_fds:
1502 inheritable = os.get_inheritable(fd)
1503 saved = os.dup(fd)
1504 fds.append((fd, saved, inheritable))
1505 return fds
1506
1507 def _restore_fds(self, fds):
1508 for fd, saved, inheritable in fds:
1509 os.dup2(saved, fd, inheritable=inheritable)
1510 os.close(saved)
1511
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001512 def check_close_std_fds(self, fds):
1513 # Issue #9905: test that subprocess pipes still work properly with
1514 # some standard fds closed
1515 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001516 saved_fds = self._save_fds(fds)
1517 for fd, saved, inheritable in saved_fds:
1518 if fd == 0:
1519 stdin = saved
1520 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001521 try:
1522 for fd in fds:
1523 os.close(fd)
1524 out, err = subprocess.Popen([sys.executable, "-c",
1525 'import sys;'
1526 'sys.stdout.write("apple");'
1527 'sys.stdout.flush();'
1528 'sys.stderr.write("orange")'],
1529 stdin=stdin,
1530 stdout=subprocess.PIPE,
1531 stderr=subprocess.PIPE).communicate()
1532 err = support.strip_python_stderr(err)
1533 self.assertEqual((out, err), (b'apple', b'orange'))
1534 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001535 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001536
1537 def test_close_fd_0(self):
1538 self.check_close_std_fds([0])
1539
1540 def test_close_fd_1(self):
1541 self.check_close_std_fds([1])
1542
1543 def test_close_fd_2(self):
1544 self.check_close_std_fds([2])
1545
1546 def test_close_fds_0_1(self):
1547 self.check_close_std_fds([0, 1])
1548
1549 def test_close_fds_0_2(self):
1550 self.check_close_std_fds([0, 2])
1551
1552 def test_close_fds_1_2(self):
1553 self.check_close_std_fds([1, 2])
1554
1555 def test_close_fds_0_1_2(self):
1556 # Issue #10806: test that subprocess pipes still work properly with
1557 # all standard fds closed.
1558 self.check_close_std_fds([0, 1, 2])
1559
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001560 def test_remapping_std_fds(self):
1561 # open up some temporary files
1562 temps = [mkstemp() for i in range(3)]
1563 try:
1564 temp_fds = [fd for fd, fname in temps]
1565
1566 # unlink the files -- we won't need to reopen them
1567 for fd, fname in temps:
1568 os.unlink(fname)
1569
1570 # write some data to what will become stdin, and rewind
1571 os.write(temp_fds[1], b"STDIN")
1572 os.lseek(temp_fds[1], 0, 0)
1573
1574 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001575 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001576 try:
1577 # duplicate the file objects over the standard fd's
1578 for fd, temp_fd in enumerate(temp_fds):
1579 os.dup2(temp_fd, fd)
1580
1581 # now use those files in the "wrong" order, so that subprocess
1582 # has to rearrange them in the child
1583 p = subprocess.Popen([sys.executable, "-c",
1584 'import sys; got = sys.stdin.read();'
1585 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1586 stdin=temp_fds[1],
1587 stdout=temp_fds[2],
1588 stderr=temp_fds[0])
1589 p.wait()
1590 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001591 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001592
1593 for fd in temp_fds:
1594 os.lseek(fd, 0, 0)
1595
1596 out = os.read(temp_fds[2], 1024)
1597 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1598 self.assertEqual(out, b"got STDIN")
1599 self.assertEqual(err, b"err")
1600
1601 finally:
1602 for fd in temp_fds:
1603 os.close(fd)
1604
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001605 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1606 # open up some temporary files
1607 temps = [mkstemp() for i in range(3)]
1608 temp_fds = [fd for fd, fname in temps]
1609 try:
1610 # unlink the files -- we won't need to reopen them
1611 for fd, fname in temps:
1612 os.unlink(fname)
1613
1614 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001615 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001616 try:
1617 # duplicate the temp files over the standard fd's 0, 1, 2
1618 for fd, temp_fd in enumerate(temp_fds):
1619 os.dup2(temp_fd, fd)
1620
1621 # write some data to what will become stdin, and rewind
1622 os.write(stdin_no, b"STDIN")
1623 os.lseek(stdin_no, 0, 0)
1624
1625 # now use those files in the given order, so that subprocess
1626 # has to rearrange them in the child
1627 p = subprocess.Popen([sys.executable, "-c",
1628 'import sys; got = sys.stdin.read();'
1629 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1630 stdin=stdin_no,
1631 stdout=stdout_no,
1632 stderr=stderr_no)
1633 p.wait()
1634
1635 for fd in temp_fds:
1636 os.lseek(fd, 0, 0)
1637
1638 out = os.read(stdout_no, 1024)
1639 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1640 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001641 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001642
1643 self.assertEqual(out, b"got STDIN")
1644 self.assertEqual(err, b"err")
1645
1646 finally:
1647 for fd in temp_fds:
1648 os.close(fd)
1649
1650 # When duping fds, if there arises a situation where one of the fds is
1651 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1652 # This tests all combinations of this.
1653 def test_swap_fds(self):
1654 self.check_swap_fds(0, 1, 2)
1655 self.check_swap_fds(0, 2, 1)
1656 self.check_swap_fds(1, 0, 2)
1657 self.check_swap_fds(1, 2, 0)
1658 self.check_swap_fds(2, 0, 1)
1659 self.check_swap_fds(2, 1, 0)
1660
Victor Stinner13bb71c2010-04-23 21:41:56 +00001661 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001662 def prepare():
1663 raise ValueError("surrogate:\uDCff")
1664
1665 try:
1666 subprocess.call(
1667 [sys.executable, "-c", "pass"],
1668 preexec_fn=prepare)
1669 except ValueError as err:
1670 # Pure Python implementations keeps the message
1671 self.assertIsNone(subprocess._posixsubprocess)
1672 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001673 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001674 # _posixsubprocess uses a default message
1675 self.assertIsNotNone(subprocess._posixsubprocess)
1676 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1677 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001678 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001679
Victor Stinner13bb71c2010-04-23 21:41:56 +00001680 def test_undecodable_env(self):
1681 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001682 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001683 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001684 env = os.environ.copy()
1685 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001686 # Use C locale to get ascii for the locale encoding to force
1687 # surrogate-escaping of \xFF in the child process; otherwise it can
1688 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001689 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001690 stdout = subprocess.check_output(
1691 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001692 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001693 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001694 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001695
1696 # test bytes
1697 key = key.encode("ascii", "surrogateescape")
1698 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001699 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001700 env = os.environ.copy()
1701 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001702 stdout = subprocess.check_output(
1703 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001704 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001705 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001706 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001707
Victor Stinnerb745a742010-05-18 17:17:23 +00001708 def test_bytes_program(self):
1709 abs_program = os.fsencode(sys.executable)
1710 path, program = os.path.split(sys.executable)
1711 program = os.fsencode(program)
1712
1713 # absolute bytes path
1714 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001715 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001716
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001717 # absolute bytes path as a string
1718 cmd = b"'" + abs_program + b"' -c pass"
1719 exitcode = subprocess.call(cmd, shell=True)
1720 self.assertEqual(exitcode, 0)
1721
Victor Stinnerb745a742010-05-18 17:17:23 +00001722 # bytes program, unicode PATH
1723 env = os.environ.copy()
1724 env["PATH"] = path
1725 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001726 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001727
1728 # bytes program, bytes PATH
1729 envb = os.environb.copy()
1730 envb[b"PATH"] = os.fsencode(path)
1731 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001732 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001733
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001734 def test_pipe_cloexec(self):
1735 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1736 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1737
1738 p1 = subprocess.Popen([sys.executable, sleeper],
1739 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1740 stderr=subprocess.PIPE, close_fds=False)
1741
1742 self.addCleanup(p1.communicate, b'')
1743
1744 p2 = subprocess.Popen([sys.executable, fd_status],
1745 stdout=subprocess.PIPE, close_fds=False)
1746
1747 output, error = p2.communicate()
1748 result_fds = set(map(int, output.split(b',')))
1749 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1750 p1.stderr.fileno()])
1751
1752 self.assertFalse(result_fds & unwanted_fds,
1753 "Expected no fds from %r to be open in child, "
1754 "found %r" %
1755 (unwanted_fds, result_fds & unwanted_fds))
1756
1757 def test_pipe_cloexec_real_tools(self):
1758 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1759 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1760
1761 subdata = b'zxcvbn'
1762 data = subdata * 4 + b'\n'
1763
1764 p1 = subprocess.Popen([sys.executable, qcat],
1765 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1766 close_fds=False)
1767
1768 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1769 stdin=p1.stdout, stdout=subprocess.PIPE,
1770 close_fds=False)
1771
1772 self.addCleanup(p1.wait)
1773 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001774 def kill_p1():
1775 try:
1776 p1.terminate()
1777 except ProcessLookupError:
1778 pass
1779 def kill_p2():
1780 try:
1781 p2.terminate()
1782 except ProcessLookupError:
1783 pass
1784 self.addCleanup(kill_p1)
1785 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001786
1787 p1.stdin.write(data)
1788 p1.stdin.close()
1789
1790 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1791
1792 self.assertTrue(readfiles, "The child hung")
1793 self.assertEqual(p2.stdout.read(), data)
1794
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001795 p1.stdout.close()
1796 p2.stdout.close()
1797
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001798 def test_close_fds(self):
1799 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1800
1801 fds = os.pipe()
1802 self.addCleanup(os.close, fds[0])
1803 self.addCleanup(os.close, fds[1])
1804
1805 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001806 # add a bunch more fds
1807 for _ in range(9):
1808 fd = os.open("/dev/null", os.O_RDONLY)
1809 self.addCleanup(os.close, fd)
1810 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001811
Victor Stinnerdaf45552013-08-28 00:53:59 +02001812 for fd in open_fds:
1813 os.set_inheritable(fd, True)
1814
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001815 p = subprocess.Popen([sys.executable, fd_status],
1816 stdout=subprocess.PIPE, close_fds=False)
1817 output, ignored = p.communicate()
1818 remaining_fds = set(map(int, output.split(b',')))
1819
1820 self.assertEqual(remaining_fds & open_fds, open_fds,
1821 "Some fds were closed")
1822
1823 p = subprocess.Popen([sys.executable, fd_status],
1824 stdout=subprocess.PIPE, close_fds=True)
1825 output, ignored = p.communicate()
1826 remaining_fds = set(map(int, output.split(b',')))
1827
1828 self.assertFalse(remaining_fds & open_fds,
1829 "Some fds were left open")
1830 self.assertIn(1, remaining_fds, "Subprocess failed")
1831
Gregory P. Smith8facece2012-01-21 14:01:08 -08001832 # Keep some of the fd's we opened open in the subprocess.
1833 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1834 fds_to_keep = set(open_fds.pop() for _ in range(8))
1835 p = subprocess.Popen([sys.executable, fd_status],
1836 stdout=subprocess.PIPE, close_fds=True,
1837 pass_fds=())
1838 output, ignored = p.communicate()
1839 remaining_fds = set(map(int, output.split(b',')))
1840
1841 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1842 "Some fds not in pass_fds were left open")
1843 self.assertIn(1, remaining_fds, "Subprocess failed")
1844
Victor Stinner88701e22011-06-01 13:13:04 +02001845 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1846 # descriptor of a pipe closed in the parent process is valid in the
1847 # child process according to fstat(), but the mode of the file
1848 # descriptor is invalid, and read or write raise an error.
1849 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001850 def test_pass_fds(self):
1851 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1852
1853 open_fds = set()
1854
1855 for x in range(5):
1856 fds = os.pipe()
1857 self.addCleanup(os.close, fds[0])
1858 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02001859 os.set_inheritable(fds[0], True)
1860 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001861 open_fds.update(fds)
1862
1863 for fd in open_fds:
1864 p = subprocess.Popen([sys.executable, fd_status],
1865 stdout=subprocess.PIPE, close_fds=True,
1866 pass_fds=(fd, ))
1867 output, ignored = p.communicate()
1868
1869 remaining_fds = set(map(int, output.split(b',')))
1870 to_be_closed = open_fds - {fd}
1871
1872 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1873 self.assertFalse(remaining_fds & to_be_closed,
1874 "fd to be closed passed")
1875
1876 # pass_fds overrides close_fds with a warning.
1877 with self.assertWarns(RuntimeWarning) as context:
1878 self.assertFalse(subprocess.call(
1879 [sys.executable, "-c", "import sys; sys.exit(0)"],
1880 close_fds=False, pass_fds=(fd, )))
1881 self.assertIn('overriding close_fds', str(context.warning))
1882
Victor Stinnerdaf45552013-08-28 00:53:59 +02001883 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02001884 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02001885
1886 inheritable, non_inheritable = os.pipe()
1887 self.addCleanup(os.close, inheritable)
1888 self.addCleanup(os.close, non_inheritable)
1889 os.set_inheritable(inheritable, True)
1890 os.set_inheritable(non_inheritable, False)
1891 pass_fds = (inheritable, non_inheritable)
1892 args = [sys.executable, script]
1893 args += list(map(str, pass_fds))
1894
1895 p = subprocess.Popen(args,
1896 stdout=subprocess.PIPE, close_fds=True,
1897 pass_fds=pass_fds)
1898 output, ignored = p.communicate()
1899 fds = set(map(int, output.split(b',')))
1900
1901 # the inheritable file descriptor must be inherited, so its inheritable
1902 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02001903 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02001904
1905 # inheritable flag must not be changed in the parent process
1906 self.assertEqual(os.get_inheritable(inheritable), True)
1907 self.assertEqual(os.get_inheritable(non_inheritable), False)
1908
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001909 def test_stdout_stdin_are_single_inout_fd(self):
1910 with io.open(os.devnull, "r+") as inout:
1911 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1912 stdout=inout, stdin=inout)
1913 p.wait()
1914
1915 def test_stdout_stderr_are_single_inout_fd(self):
1916 with io.open(os.devnull, "r+") as inout:
1917 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1918 stdout=inout, stderr=inout)
1919 p.wait()
1920
1921 def test_stderr_stdin_are_single_inout_fd(self):
1922 with io.open(os.devnull, "r+") as inout:
1923 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1924 stderr=inout, stdin=inout)
1925 p.wait()
1926
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001927 def test_wait_when_sigchild_ignored(self):
1928 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1929 sigchild_ignore = support.findfile("sigchild_ignore.py",
1930 subdir="subprocessdata")
1931 p = subprocess.Popen([sys.executable, sigchild_ignore],
1932 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1933 stdout, stderr = p.communicate()
1934 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001935 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001936 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001937
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001938 def test_select_unbuffered(self):
1939 # Issue #11459: bufsize=0 should really set the pipes as
1940 # unbuffered (and therefore let select() work properly).
1941 select = support.import_module("select")
1942 p = subprocess.Popen([sys.executable, "-c",
1943 'import sys;'
1944 'sys.stdout.write("apple")'],
1945 stdout=subprocess.PIPE,
1946 bufsize=0)
1947 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001948 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001949 try:
1950 self.assertEqual(f.read(4), b"appl")
1951 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1952 finally:
1953 p.wait()
1954
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001955 def test_zombie_fast_process_del(self):
1956 # Issue #12650: on Unix, if Popen.__del__() was called before the
1957 # process exited, it wouldn't be added to subprocess._active, and would
1958 # remain a zombie.
1959 # spawn a Popen, and delete its reference before it exits
1960 p = subprocess.Popen([sys.executable, "-c",
1961 'import sys, time;'
1962 'time.sleep(0.2)'],
1963 stdout=subprocess.PIPE,
1964 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001965 self.addCleanup(p.stdout.close)
1966 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001967 ident = id(p)
1968 pid = p.pid
1969 del p
1970 # check that p is in the active processes list
1971 self.assertIn(ident, [id(o) for o in subprocess._active])
1972
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001973 def test_leak_fast_process_del_killed(self):
1974 # Issue #12650: on Unix, if Popen.__del__() was called before the
1975 # process exited, and the process got killed by a signal, it would never
1976 # be removed from subprocess._active, which triggered a FD and memory
1977 # leak.
1978 # spawn a Popen, delete its reference and kill it
1979 p = subprocess.Popen([sys.executable, "-c",
1980 'import time;'
1981 'time.sleep(3)'],
1982 stdout=subprocess.PIPE,
1983 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001984 self.addCleanup(p.stdout.close)
1985 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001986 ident = id(p)
1987 pid = p.pid
1988 del p
1989 os.kill(pid, signal.SIGKILL)
1990 # check that p is in the active processes list
1991 self.assertIn(ident, [id(o) for o in subprocess._active])
1992
1993 # let some time for the process to exit, and create a new Popen: this
1994 # should trigger the wait() of p
1995 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001996 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001997 with subprocess.Popen(['nonexisting_i_hope'],
1998 stdout=subprocess.PIPE,
1999 stderr=subprocess.PIPE) as proc:
2000 pass
2001 # p should have been wait()ed on, and removed from the _active list
2002 self.assertRaises(OSError, os.waitpid, pid, 0)
2003 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2004
Charles-François Natali249cdc32013-08-25 18:24:45 +02002005 def test_close_fds_after_preexec(self):
2006 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2007
2008 # this FD is used as dup2() target by preexec_fn, and should be closed
2009 # in the child process
2010 fd = os.dup(1)
2011 self.addCleanup(os.close, fd)
2012
2013 p = subprocess.Popen([sys.executable, fd_status],
2014 stdout=subprocess.PIPE, close_fds=True,
2015 preexec_fn=lambda: os.dup2(1, fd))
2016 output, ignored = p.communicate()
2017
2018 remaining_fds = set(map(int, output.split(b',')))
2019
2020 self.assertNotIn(fd, remaining_fds)
2021
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002022
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002023@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002024class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002025
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002026 def test_startupinfo(self):
2027 # startupinfo argument
2028 # We uses hardcoded constants, because we do not want to
2029 # depend on win32all.
2030 STARTF_USESHOWWINDOW = 1
2031 SW_MAXIMIZE = 3
2032 startupinfo = subprocess.STARTUPINFO()
2033 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2034 startupinfo.wShowWindow = SW_MAXIMIZE
2035 # Since Python is a console process, it won't be affected
2036 # by wShowWindow, but the argument should be silently
2037 # ignored
2038 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002039 startupinfo=startupinfo)
2040
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002041 def test_creationflags(self):
2042 # creationflags argument
2043 CREATE_NEW_CONSOLE = 16
2044 sys.stderr.write(" a DOS box should flash briefly ...\n")
2045 subprocess.call(sys.executable +
2046 ' -c "import time; time.sleep(0.25)"',
2047 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002048
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002049 def test_invalid_args(self):
2050 # invalid arguments should raise ValueError
2051 self.assertRaises(ValueError, subprocess.call,
2052 [sys.executable, "-c",
2053 "import sys; sys.exit(47)"],
2054 preexec_fn=lambda: 1)
2055 self.assertRaises(ValueError, subprocess.call,
2056 [sys.executable, "-c",
2057 "import sys; sys.exit(47)"],
2058 stdout=subprocess.PIPE,
2059 close_fds=True)
2060
2061 def test_close_fds(self):
2062 # close file descriptors
2063 rc = subprocess.call([sys.executable, "-c",
2064 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002065 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002066 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002067
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002068 def test_shell_sequence(self):
2069 # Run command through the shell (sequence)
2070 newenv = os.environ.copy()
2071 newenv["FRUIT"] = "physalis"
2072 p = subprocess.Popen(["set"], shell=1,
2073 stdout=subprocess.PIPE,
2074 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002075 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002076 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002077
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002078 def test_shell_string(self):
2079 # Run command through the shell (string)
2080 newenv = os.environ.copy()
2081 newenv["FRUIT"] = "physalis"
2082 p = subprocess.Popen("set", shell=1,
2083 stdout=subprocess.PIPE,
2084 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002085 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002086 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002087
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002088 def test_call_string(self):
2089 # call() function with string argument on Windows
2090 rc = subprocess.call(sys.executable +
2091 ' -c "import sys; sys.exit(47)"')
2092 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002093
Florent Xicluna4886d242010-03-08 13:27:26 +00002094 def _kill_process(self, method, *args):
2095 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002096 p = subprocess.Popen([sys.executable, "-c", """if 1:
2097 import sys, time
2098 sys.stdout.write('x\\n')
2099 sys.stdout.flush()
2100 time.sleep(30)
2101 """],
2102 stdin=subprocess.PIPE,
2103 stdout=subprocess.PIPE,
2104 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00002105 self.addCleanup(p.stdout.close)
2106 self.addCleanup(p.stderr.close)
2107 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00002108 # Wait for the interpreter to be completely initialized before
2109 # sending any signal.
2110 p.stdout.read(1)
2111 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00002112 _, stderr = p.communicate()
2113 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00002114 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002115 self.assertNotEqual(returncode, 0)
2116
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002117 def _kill_dead_process(self, method, *args):
2118 p = subprocess.Popen([sys.executable, "-c", """if 1:
2119 import sys, time
2120 sys.stdout.write('x\\n')
2121 sys.stdout.flush()
2122 sys.exit(42)
2123 """],
2124 stdin=subprocess.PIPE,
2125 stdout=subprocess.PIPE,
2126 stderr=subprocess.PIPE)
2127 self.addCleanup(p.stdout.close)
2128 self.addCleanup(p.stderr.close)
2129 self.addCleanup(p.stdin.close)
2130 # Wait for the interpreter to be completely initialized before
2131 # sending any signal.
2132 p.stdout.read(1)
2133 # The process should end after this
2134 time.sleep(1)
2135 # This shouldn't raise even though the child is now dead
2136 getattr(p, method)(*args)
2137 _, stderr = p.communicate()
2138 self.assertStderrEqual(stderr, b'')
2139 rc = p.wait()
2140 self.assertEqual(rc, 42)
2141
Florent Xicluna4886d242010-03-08 13:27:26 +00002142 def test_send_signal(self):
2143 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002144
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002145 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002146 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002147
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002148 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002149 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002150
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002151 def test_send_signal_dead(self):
2152 self._kill_dead_process('send_signal', signal.SIGTERM)
2153
2154 def test_kill_dead(self):
2155 self._kill_dead_process('kill')
2156
2157 def test_terminate_dead(self):
2158 self._kill_dead_process('terminate')
2159
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002160
Brett Cannona23810f2008-05-26 19:04:21 +00002161# The module says:
2162# "NB This only works (and is only relevant) for UNIX."
2163#
2164# Actually, getoutput should work on any platform with an os.popen, but
2165# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002166@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002167class CommandTests(unittest.TestCase):
2168 def test_getoutput(self):
2169 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2170 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2171 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002172
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002173 # we use mkdtemp in the next line to create an empty directory
2174 # under our exclusive control; from that, we can invent a pathname
2175 # that we _know_ won't exist. This is guaranteed to fail.
2176 dir = None
2177 try:
2178 dir = tempfile.mkdtemp()
2179 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00002180
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002181 status, output = subprocess.getstatusoutput('cat ' + name)
2182 self.assertNotEqual(status, 0)
2183 finally:
2184 if dir is not None:
2185 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002186
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002187
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002188@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
2189 "poll system call not supported")
2190class ProcessTestCaseNoPoll(ProcessTestCase):
2191 def setUp(self):
2192 subprocess._has_poll = False
2193 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002194
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002195 def tearDown(self):
2196 subprocess._has_poll = True
2197 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002198
2199
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002200class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00002201 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002202 def test_eintr_retry_call(self):
2203 record_calls = []
2204 def fake_os_func(*args):
2205 record_calls.append(args)
2206 if len(record_calls) == 2:
2207 raise OSError(errno.EINTR, "fake interrupted system call")
2208 return tuple(reversed(args))
2209
2210 self.assertEqual((999, 256),
2211 subprocess._eintr_retry_call(fake_os_func, 256, 999))
2212 self.assertEqual([(256, 999)], record_calls)
2213 # This time there will be an EINTR so it will loop once.
2214 self.assertEqual((666,),
2215 subprocess._eintr_retry_call(fake_os_func, 666))
2216 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
2217
2218
Tim Golden126c2962010-08-11 14:20:40 +00002219@unittest.skipUnless(mswindows, "Windows-specific tests")
2220class CommandsWithSpaces (BaseTestCase):
2221
2222 def setUp(self):
2223 super().setUp()
2224 f, fname = mkstemp(".py", "te st")
2225 self.fname = fname.lower ()
2226 os.write(f, b"import sys;"
2227 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2228 )
2229 os.close(f)
2230
2231 def tearDown(self):
2232 os.remove(self.fname)
2233 super().tearDown()
2234
2235 def with_spaces(self, *args, **kwargs):
2236 kwargs['stdout'] = subprocess.PIPE
2237 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002238 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002239 self.assertEqual(
2240 p.stdout.read ().decode("mbcs"),
2241 "2 [%r, 'ab cd']" % self.fname
2242 )
2243
2244 def test_shell_string_with_spaces(self):
2245 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002246 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2247 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002248
2249 def test_shell_sequence_with_spaces(self):
2250 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002251 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002252
2253 def test_noshell_string_with_spaces(self):
2254 # call() function with string argument with spaces on Windows
2255 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2256 "ab cd"))
2257
2258 def test_noshell_sequence_with_spaces(self):
2259 # call() function with sequence argument with spaces on Windows
2260 self.with_spaces([sys.executable, self.fname, "ab cd"])
2261
Brian Curtin79cdb662010-12-03 02:46:02 +00002262
Georg Brandla86b2622012-02-20 21:34:57 +01002263class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002264
2265 def test_pipe(self):
2266 with subprocess.Popen([sys.executable, "-c",
2267 "import sys;"
2268 "sys.stdout.write('stdout');"
2269 "sys.stderr.write('stderr');"],
2270 stdout=subprocess.PIPE,
2271 stderr=subprocess.PIPE) as proc:
2272 self.assertEqual(proc.stdout.read(), b"stdout")
2273 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2274
2275 self.assertTrue(proc.stdout.closed)
2276 self.assertTrue(proc.stderr.closed)
2277
2278 def test_returncode(self):
2279 with subprocess.Popen([sys.executable, "-c",
2280 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002281 pass
2282 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002283 self.assertEqual(proc.returncode, 100)
2284
2285 def test_communicate_stdin(self):
2286 with subprocess.Popen([sys.executable, "-c",
2287 "import sys;"
2288 "sys.exit(sys.stdin.read() == 'context')"],
2289 stdin=subprocess.PIPE) as proc:
2290 proc.communicate(b"context")
2291 self.assertEqual(proc.returncode, 1)
2292
2293 def test_invalid_args(self):
Andrew Svetlovb1726972012-12-26 23:34:54 +02002294 with self.assertRaises(FileNotFoundError) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002295 with subprocess.Popen(['nonexisting_i_hope'],
2296 stdout=subprocess.PIPE,
2297 stderr=subprocess.PIPE) as proc:
2298 pass
2299
Brian Curtin79cdb662010-12-03 02:46:02 +00002300
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002301def test_main():
2302 unit_tests = (ProcessTestCase,
2303 POSIXProcessTestCase,
2304 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002305 CommandTests,
2306 ProcessTestCaseNoPoll,
2307 HelperFunctionTests,
2308 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002309 ContextManagerTests,
2310 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002311
2312 support.run_unittest(*unit_tests)
2313 support.reap_children()
2314
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002315if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002316 unittest.main()