blob: 7d0708d5f7fe64a3f928e1b0ac7897dea8277170 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00002from unittest import mock
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
Gregory P. Smith50e16e32017-01-22 17:28:38 -08006import platform
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04008import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Charles-François Natali3a4586a2013-11-08 19:56:59 +010013import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000015import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040016import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050017import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030018import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050019
20try:
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080021 import ctypes
22except ImportError:
23 ctypes = None
Gregory P. Smith56bc3b72017-05-23 07:49:13 -070024else:
25 import ctypes.util
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080026
27try:
Antoine Pitroua8392712013-08-30 23:38:13 +020028 import threading
29except ImportError:
30 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050031
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020032try:
33 import _testcapi
34except ImportError:
35 _testcapi = None
36
Steve Dower22d06982016-09-06 19:38:15 -070037if support.PGO:
38 raise unittest.SkipTest("test is not helpful for PGO")
39
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000040mswindows = (sys.platform == "win32")
41
42#
43# Depends on the following external programs: Python
44#
45
46if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000047 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
48 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000049else:
50 SETBINARY = ''
51
Victor Stinner9a83f652017-08-21 23:51:31 +020052NONEXISTING_CMD = ('nonexisting_i_hope',)
53
Florent Xiclunab1e94e82010-02-27 22:12:37 +000054
Florent Xiclunac049d872010-03-27 22:47:23 +000055class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000056 def setUp(self):
57 # Try to minimize the number of children we have so this test
58 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000059 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000060
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000061 def tearDown(self):
62 for inst in subprocess._active:
63 inst.wait()
64 subprocess._cleanup()
65 self.assertFalse(subprocess._active, "subprocess._active not empty")
Victor Stinnercc42c122017-07-28 18:00:22 +020066 self.doCleanups()
67 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000068
Florent Xiclunab1e94e82010-02-27 22:12:37 +000069 def assertStderrEqual(self, stderr, expected, msg=None):
70 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
71 # shutdown time. That frustrates tests trying to check stderr produced
72 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000073 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040074 # strip_python_stderr also strips whitespace, so we do too.
75 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000076 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000077
Florent Xiclunac049d872010-03-27 22:47:23 +000078
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080079class PopenTestException(Exception):
80 pass
81
82
83class PopenExecuteChildRaises(subprocess.Popen):
84 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
85 _execute_child fails.
86 """
87 def _execute_child(self, *args, **kwargs):
88 raise PopenTestException("Forced Exception for Test")
89
90
Florent Xiclunac049d872010-03-27 22:47:23 +000091class ProcessTestCase(BaseTestCase):
92
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070093 def test_io_buffered_by_default(self):
94 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
95 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
96 stderr=subprocess.PIPE)
97 try:
98 self.assertIsInstance(p.stdin, io.BufferedIOBase)
99 self.assertIsInstance(p.stdout, io.BufferedIOBase)
100 self.assertIsInstance(p.stderr, io.BufferedIOBase)
101 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700102 p.stdin.close()
103 p.stdout.close()
104 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700105 p.wait()
106
107 def test_io_unbuffered_works(self):
108 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
109 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
110 stderr=subprocess.PIPE, bufsize=0)
111 try:
112 self.assertIsInstance(p.stdin, io.RawIOBase)
113 self.assertIsInstance(p.stdout, io.RawIOBase)
114 self.assertIsInstance(p.stderr, io.RawIOBase)
115 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700116 p.stdin.close()
117 p.stdout.close()
118 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700119 p.wait()
120
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000121 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000122 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000123 rc = subprocess.call([sys.executable, "-c",
124 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000125 self.assertEqual(rc, 47)
126
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400127 def test_call_timeout(self):
128 # call() function with timeout argument; we want to test that the child
129 # process gets killed when the timeout expires. If the child isn't
130 # killed, this call will deadlock since subprocess.call waits for the
131 # child.
132 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
133 [sys.executable, "-c", "while True: pass"],
134 timeout=0.1)
135
Peter Astrand454f7672005-01-01 09:36:35 +0000136 def test_check_call_zero(self):
137 # check_call() function with zero return code
138 rc = subprocess.check_call([sys.executable, "-c",
139 "import sys; sys.exit(0)"])
140 self.assertEqual(rc, 0)
141
142 def test_check_call_nonzero(self):
143 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000144 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000145 subprocess.check_call([sys.executable, "-c",
146 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000147 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000148
Georg Brandlf9734072008-12-07 15:30:06 +0000149 def test_check_output(self):
150 # check_output() function with zero return code
151 output = subprocess.check_output(
152 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000153 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000154
155 def test_check_output_nonzero(self):
156 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000157 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000158 subprocess.check_output(
159 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000160 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000161
162 def test_check_output_stderr(self):
163 # check_output() function stderr redirected to stdout
164 output = subprocess.check_output(
165 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
166 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000167 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000168
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300169 def test_check_output_stdin_arg(self):
170 # check_output() can be called with stdin set to a file
171 tf = tempfile.TemporaryFile()
172 self.addCleanup(tf.close)
173 tf.write(b'pear')
174 tf.seek(0)
175 output = subprocess.check_output(
176 [sys.executable, "-c",
177 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
178 stdin=tf)
179 self.assertIn(b'PEAR', output)
180
181 def test_check_output_input_arg(self):
182 # check_output() can be called with input set to a string
183 output = subprocess.check_output(
184 [sys.executable, "-c",
185 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
186 input=b'pear')
187 self.assertIn(b'PEAR', output)
188
Georg Brandlf9734072008-12-07 15:30:06 +0000189 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300190 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000191 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000192 output = subprocess.check_output(
193 [sys.executable, "-c", "print('will not be run')"],
194 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000195 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000196 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000197
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300198 def test_check_output_stdin_with_input_arg(self):
199 # check_output() refuses to accept 'stdin' with 'input'
200 tf = tempfile.TemporaryFile()
201 self.addCleanup(tf.close)
202 tf.write(b'pear')
203 tf.seek(0)
204 with self.assertRaises(ValueError) as c:
205 output = subprocess.check_output(
206 [sys.executable, "-c", "print('will not be run')"],
207 stdin=tf, input=b'hare')
208 self.fail("Expected ValueError when stdin and input args supplied.")
209 self.assertIn('stdin', c.exception.args[0])
210 self.assertIn('input', c.exception.args[0])
211
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400212 def test_check_output_timeout(self):
213 # check_output() function with timeout arg
214 with self.assertRaises(subprocess.TimeoutExpired) as c:
215 output = subprocess.check_output(
216 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200217 "import sys, time\n"
218 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400219 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200220 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400221 # Some heavily loaded buildbots (sparc Debian 3.x) require
222 # this much time to start and print.
223 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400224 self.fail("Expected TimeoutExpired.")
225 self.assertEqual(c.exception.output, b'BDFL')
226
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000228 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000229 newenv = os.environ.copy()
230 newenv["FRUIT"] = "banana"
231 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000232 'import sys, os;'
233 'sys.exit(os.getenv("FRUIT")=="banana")'],
234 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000235 self.assertEqual(rc, 1)
236
Victor Stinner87b9bc32011-06-01 00:57:47 +0200237 def test_invalid_args(self):
238 # Popen() called with invalid arguments should raise TypeError
239 # but Popen.__del__ should not complain (issue #12085)
240 with support.captured_stderr() as s:
241 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
242 argcount = subprocess.Popen.__init__.__code__.co_argcount
243 too_many_args = [0] * (argcount + 1)
244 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
245 self.assertEqual(s.getvalue(), '')
246
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000248 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000249 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000250 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000251 self.addCleanup(p.stdout.close)
252 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000253 p.wait()
254 self.assertEqual(p.stdin, None)
255
256 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200257 # .stdout is None when not redirected, and the child's stdout will
258 # be inherited from the parent. In order to test this we run a
259 # subprocess in a subprocess:
260 # this_test
261 # \-- subprocess created by this test (parent)
262 # \-- subprocess created by the parent subprocess (child)
263 # The parent doesn't specify stdout, so the child will use the
264 # parent's stdout. This test checks that the message printed by the
265 # child goes to the parent stdout. The parent also checks that the
266 # child's stdout is None. See #11963.
267 code = ('import sys; from subprocess import Popen, PIPE;'
268 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
269 ' stdin=PIPE, stderr=PIPE);'
270 'p.wait(); assert p.stdout is None;')
271 p = subprocess.Popen([sys.executable, "-c", code],
272 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
273 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000274 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200275 out, err = p.communicate()
276 self.assertEqual(p.returncode, 0, err)
277 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000278
279 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000280 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000281 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000283 self.addCleanup(p.stdout.close)
284 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285 p.wait()
286 self.assertEqual(p.stderr, None)
287
Chris Jerdonek776cb192012-10-08 15:56:43 -0700288 def _assert_python(self, pre_args, **kwargs):
289 # We include sys.exit() to prevent the test runner from hanging
290 # whenever python is found.
291 args = pre_args + ["import sys; sys.exit(47)"]
292 p = subprocess.Popen(args, **kwargs)
293 p.wait()
294 self.assertEqual(47, p.returncode)
295
296 def test_executable(self):
297 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700298 #
299 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
300 # determine where its standard library is, so we need the directory
301 # of args[0] to be valid for the Popen() call to Python to succeed.
302 # See also issue #16170 and issue #7774.
303 doesnotexist = os.path.join(os.path.dirname(sys.executable),
304 "doesnotexist")
305 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700306
307 def test_executable_takes_precedence(self):
308 # Check that the executable argument takes precedence over args[0].
309 #
310 # Verify first that the call succeeds without the executable arg.
311 pre_args = [sys.executable, "-c"]
312 self._assert_python(pre_args)
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100313 self.assertRaises((FileNotFoundError, PermissionError),
314 self._assert_python, pre_args,
Chris Jerdonek776cb192012-10-08 15:56:43 -0700315 executable="doesnotexist")
316
317 @unittest.skipIf(mswindows, "executable argument replaces shell")
318 def test_executable_replaces_shell(self):
319 # Check that the executable argument replaces the default shell
320 # when shell=True.
321 self._assert_python([], executable=sys.executable, shell=True)
322
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700323 # For use in the test_cwd* tests below.
324 def _normalize_cwd(self, cwd):
325 # Normalize an expected cwd (for Tru64 support).
326 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
327 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300328 with support.change_cwd(cwd):
329 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700330
331 # For use in the test_cwd* tests below.
332 def _split_python_path(self):
333 # Return normalized (python_dir, python_base).
334 python_path = os.path.realpath(sys.executable)
335 return os.path.split(python_path)
336
337 # For use in the test_cwd* tests below.
338 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
339 # Invoke Python via Popen, and assert that (1) the call succeeds,
340 # and that (2) the current working directory of the child process
341 # matches *expected_cwd*.
342 p = subprocess.Popen([python_arg, "-c",
343 "import os, sys; "
344 "sys.stdout.write(os.getcwd()); "
345 "sys.exit(47)"],
346 stdout=subprocess.PIPE,
347 **kwargs)
348 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000349 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700350 self.assertEqual(47, p.returncode)
351 normcase = os.path.normcase
352 self.assertEqual(normcase(expected_cwd),
353 normcase(p.stdout.read().decode("utf-8")))
354
355 def test_cwd(self):
356 # Check that cwd changes the cwd for the child process.
357 temp_dir = tempfile.gettempdir()
358 temp_dir = self._normalize_cwd(temp_dir)
359 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
360
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530361 def test_cwd_with_pathlike(self):
362 temp_dir = tempfile.gettempdir()
363 temp_dir = self._normalize_cwd(temp_dir)
364
365 class _PathLikeObj:
366 def __fspath__(self):
367 return temp_dir
368
369 self._assert_cwd(temp_dir, sys.executable, cwd=_PathLikeObj())
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_arg(self):
373 # Check that Popen looks for args[0] relative to cwd if args[0]
374 # is relative.
375 python_dir, python_base = self._split_python_path()
376 rel_python = os.path.join(os.curdir, python_base)
377 with support.temp_cwd() as wrong_dir:
378 # Before calling with the correct cwd, confirm that the call fails
379 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700380 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700381 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700382 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700383 [rel_python], cwd=wrong_dir)
384 python_dir = self._normalize_cwd(python_dir)
385 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
386
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700387 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700388 def test_cwd_with_relative_executable(self):
389 # Check that Popen looks for executable relative to cwd if executable
390 # is relative (and that executable takes precedence over args[0]).
391 python_dir, python_base = self._split_python_path()
392 rel_python = os.path.join(os.curdir, python_base)
393 doesntexist = "somethingyoudonthave"
394 with support.temp_cwd() as wrong_dir:
395 # Before calling with the correct cwd, confirm that the call fails
396 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700397 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700398 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700399 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700400 [doesntexist], executable=rel_python,
401 cwd=wrong_dir)
402 python_dir = self._normalize_cwd(python_dir)
403 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
404 cwd=python_dir)
405
406 def test_cwd_with_absolute_arg(self):
407 # Check that Popen can find the executable when the cwd is wrong
408 # if args[0] is an absolute path.
409 python_dir, python_base = self._split_python_path()
410 abs_python = os.path.join(python_dir, python_base)
411 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300412 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700413 # Before calling with an absolute path, confirm that using a
414 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700415 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700416 [rel_python], cwd=wrong_dir)
417 wrong_dir = self._normalize_cwd(wrong_dir)
418 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
419
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100420 @unittest.skipIf(sys.base_prefix != sys.prefix,
421 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000422 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700423 python_dir, python_base = self._split_python_path()
424 python_dir = self._normalize_cwd(python_dir)
425 self._assert_cwd(python_dir, "somethingyoudonthave",
426 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000427
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100428 @unittest.skipIf(sys.base_prefix != sys.prefix,
429 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000430 @unittest.skipIf(sysconfig.is_python_build(),
431 "need an installed Python. See #7774")
432 def test_executable_without_cwd(self):
433 # For a normal installation, it should work without 'cwd'
434 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700435 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
436 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000437
438 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000439 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000440 p = subprocess.Popen([sys.executable, "-c",
441 'import sys; sys.exit(sys.stdin.read() == "pear")'],
442 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000443 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 p.stdin.close()
445 p.wait()
446 self.assertEqual(p.returncode, 1)
447
448 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000449 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000450 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000451 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000453 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454 os.lseek(d, 0, 0)
455 p = subprocess.Popen([sys.executable, "-c",
456 'import sys; sys.exit(sys.stdin.read() == "pear")'],
457 stdin=d)
458 p.wait()
459 self.assertEqual(p.returncode, 1)
460
461 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000462 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000464 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000465 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466 tf.seek(0)
467 p = subprocess.Popen([sys.executable, "-c",
468 'import sys; sys.exit(sys.stdin.read() == "pear")'],
469 stdin=tf)
470 p.wait()
471 self.assertEqual(p.returncode, 1)
472
473 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000474 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000475 p = subprocess.Popen([sys.executable, "-c",
476 'import sys; sys.stdout.write("orange")'],
477 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200478 with p:
479 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000480
481 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000482 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000483 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000484 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 d = tf.fileno()
486 p = subprocess.Popen([sys.executable, "-c",
487 'import sys; sys.stdout.write("orange")'],
488 stdout=d)
489 p.wait()
490 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000491 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492
493 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000494 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000495 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000496 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000497 p = subprocess.Popen([sys.executable, "-c",
498 'import sys; sys.stdout.write("orange")'],
499 stdout=tf)
500 p.wait()
501 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000502 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000503
504 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000505 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000506 p = subprocess.Popen([sys.executable, "-c",
507 'import sys; sys.stderr.write("strawberry")'],
508 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200509 with p:
510 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000511
512 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000513 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000514 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000515 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 d = tf.fileno()
517 p = subprocess.Popen([sys.executable, "-c",
518 'import sys; sys.stderr.write("strawberry")'],
519 stderr=d)
520 p.wait()
521 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000522 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523
524 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000525 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000526 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000527 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 p = subprocess.Popen([sys.executable, "-c",
529 'import sys; sys.stderr.write("strawberry")'],
530 stderr=tf)
531 p.wait()
532 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000533 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534
Martin Panterc7635892016-05-13 01:54:44 +0000535 def test_stderr_redirect_with_no_stdout_redirect(self):
536 # test stderr=STDOUT while stdout=None (not set)
537
538 # - grandchild prints to stderr
539 # - child redirects grandchild's stderr to its stdout
540 # - the parent should get grandchild's stderr in child's stdout
541 p = subprocess.Popen([sys.executable, "-c",
542 'import sys, subprocess;'
543 'rc = subprocess.call([sys.executable, "-c",'
544 ' "import sys;"'
545 ' "sys.stderr.write(\'42\')"],'
546 ' stderr=subprocess.STDOUT);'
547 'sys.exit(rc)'],
548 stdout=subprocess.PIPE,
549 stderr=subprocess.PIPE)
550 stdout, stderr = p.communicate()
551 #NOTE: stdout should get stderr from grandchild
552 self.assertStderrEqual(stdout, b'42')
553 self.assertStderrEqual(stderr, b'') # should be empty
554 self.assertEqual(p.returncode, 0)
555
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000557 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000559 'import sys;'
560 'sys.stdout.write("apple");'
561 'sys.stdout.flush();'
562 'sys.stderr.write("orange")'],
563 stdout=subprocess.PIPE,
564 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200565 with p:
566 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000567
568 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000569 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000570 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000571 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000572 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000573 'import sys;'
574 'sys.stdout.write("apple");'
575 'sys.stdout.flush();'
576 'sys.stderr.write("orange")'],
577 stdout=tf,
578 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000579 p.wait()
580 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000581 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000582
Thomas Wouters89f507f2006-12-13 04:49:30 +0000583 def test_stdout_filedes_of_stdout(self):
584 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200585 # To avoid printing the text on stdout, we do something similar to
586 # test_stdout_none (see above). The parent subprocess calls the child
587 # subprocess passing stdout=1, and this test uses stdout=PIPE in
588 # order to capture and check the output of the parent. See #11963.
589 code = ('import sys, subprocess; '
590 'rc = subprocess.call([sys.executable, "-c", '
591 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
592 'b\'test with stdout=1\'))"], stdout=1); '
593 'assert rc == 18')
594 p = subprocess.Popen([sys.executable, "-c", code],
595 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
596 self.addCleanup(p.stdout.close)
597 self.addCleanup(p.stderr.close)
598 out, err = p.communicate()
599 self.assertEqual(p.returncode, 0, err)
600 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000601
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200602 def test_stdout_devnull(self):
603 p = subprocess.Popen([sys.executable, "-c",
604 'for i in range(10240):'
605 'print("x" * 1024)'],
606 stdout=subprocess.DEVNULL)
607 p.wait()
608 self.assertEqual(p.stdout, None)
609
610 def test_stderr_devnull(self):
611 p = subprocess.Popen([sys.executable, "-c",
612 'import sys\n'
613 'for i in range(10240):'
614 'sys.stderr.write("x" * 1024)'],
615 stderr=subprocess.DEVNULL)
616 p.wait()
617 self.assertEqual(p.stderr, None)
618
619 def test_stdin_devnull(self):
620 p = subprocess.Popen([sys.executable, "-c",
621 'import sys;'
622 'sys.stdin.read(1)'],
623 stdin=subprocess.DEVNULL)
624 p.wait()
625 self.assertEqual(p.stdin, None)
626
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000627 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000628 newenv = os.environ.copy()
629 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200630 with subprocess.Popen([sys.executable, "-c",
631 'import sys,os;'
632 'sys.stdout.write(os.getenv("FRUIT"))'],
633 stdout=subprocess.PIPE,
634 env=newenv) as p:
635 stdout, stderr = p.communicate()
636 self.assertEqual(stdout, b"orange")
637
Victor Stinner62d51182011-06-23 01:02:25 +0200638 # Windows requires at least the SYSTEMROOT environment variable to start
639 # Python
640 @unittest.skipIf(sys.platform == 'win32',
641 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700642 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
643 'The Python shared library cannot be loaded '
644 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200645 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700646 """Verify that env={} is as empty as possible."""
647
Gregory P. Smith85aba232017-05-30 16:21:47 -0700648 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700649 """Determine if an environment variable is under our control."""
650 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
651 # on adding even when the environment in exec is empty.
652 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700653 return ('VERSIONER' in n or '__CF' in n or # MacOS
Nick Coghlan6ea41862017-06-11 13:16:15 +1000654 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
655 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700656
Victor Stinnerf1512a22011-06-21 17:18:38 +0200657 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700658 'import os; print(list(os.environ.keys()))'],
659 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200660 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700661 child_env_names = eval(stdout.strip())
662 self.assertIsInstance(child_env_names, list)
663 child_env_names = [k for k in child_env_names
664 if not is_env_var_to_ignore(k)]
665 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000666
Serhiy Storchakad174d242017-06-23 19:39:27 +0300667 def test_invalid_cmd(self):
668 # null character in the command name
669 cmd = sys.executable + '\0'
670 with self.assertRaises(ValueError):
671 subprocess.Popen([cmd, "-c", "pass"])
672
673 # null character in the command argument
674 with self.assertRaises(ValueError):
675 subprocess.Popen([sys.executable, "-c", "pass#\0"])
676
677 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300678 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300679 newenv = os.environ.copy()
680 newenv["FRUIT\0VEGETABLE"] = "cabbage"
681 with self.assertRaises(ValueError):
682 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
683
Ville Skyttä49b27342017-08-03 09:00:59 +0300684 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300685 newenv = os.environ.copy()
686 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
687 with self.assertRaises(ValueError):
688 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
689
Ville Skyttä49b27342017-08-03 09:00:59 +0300690 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300691 newenv = os.environ.copy()
692 newenv["FRUIT=ORANGE"] = "lemon"
693 with self.assertRaises(ValueError):
694 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
695
Ville Skyttä49b27342017-08-03 09:00:59 +0300696 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300697 newenv = os.environ.copy()
698 newenv["FRUIT"] = "orange=lemon"
699 with subprocess.Popen([sys.executable, "-c",
700 'import sys, os;'
701 'sys.stdout.write(os.getenv("FRUIT"))'],
702 stdout=subprocess.PIPE,
703 env=newenv) as p:
704 stdout, stderr = p.communicate()
705 self.assertEqual(stdout, b"orange=lemon")
706
Peter Astrandcbac93c2005-03-03 20:24:28 +0000707 def test_communicate_stdin(self):
708 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000709 'import sys;'
710 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000711 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000712 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000713 self.assertEqual(p.returncode, 1)
714
715 def test_communicate_stdout(self):
716 p = subprocess.Popen([sys.executable, "-c",
717 'import sys; sys.stdout.write("pineapple")'],
718 stdout=subprocess.PIPE)
719 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000720 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000721 self.assertEqual(stderr, None)
722
723 def test_communicate_stderr(self):
724 p = subprocess.Popen([sys.executable, "-c",
725 'import sys; sys.stderr.write("pineapple")'],
726 stderr=subprocess.PIPE)
727 (stdout, stderr) = p.communicate()
728 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000729 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000730
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000732 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000733 'import sys,os;'
734 'sys.stderr.write("pineapple");'
735 'sys.stdout.write(sys.stdin.read())'],
736 stdin=subprocess.PIPE,
737 stdout=subprocess.PIPE,
738 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000739 self.addCleanup(p.stdout.close)
740 self.addCleanup(p.stderr.close)
741 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000742 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000743 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000744 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000745
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400746 def test_communicate_timeout(self):
747 p = subprocess.Popen([sys.executable, "-c",
748 'import sys,os,time;'
749 'sys.stderr.write("pineapple\\n");'
750 'time.sleep(1);'
751 'sys.stderr.write("pear\\n");'
752 'sys.stdout.write(sys.stdin.read())'],
753 universal_newlines=True,
754 stdin=subprocess.PIPE,
755 stdout=subprocess.PIPE,
756 stderr=subprocess.PIPE)
757 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
758 timeout=0.3)
759 # Make sure we can keep waiting for it, and that we get the whole output
760 # after it completes.
761 (stdout, stderr) = p.communicate()
762 self.assertEqual(stdout, "banana")
763 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
764
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700765 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200766 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400767 p = subprocess.Popen([sys.executable, "-c",
768 'import sys,os,time;'
769 'sys.stdout.write("a" * (64 * 1024));'
770 'time.sleep(0.2);'
771 'sys.stdout.write("a" * (64 * 1024));'
772 'time.sleep(0.2);'
773 'sys.stdout.write("a" * (64 * 1024));'
774 'time.sleep(0.2);'
775 'sys.stdout.write("a" * (64 * 1024));'],
776 stdout=subprocess.PIPE)
777 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
778 (stdout, _) = p.communicate()
779 self.assertEqual(len(stdout), 4 * 64 * 1024)
780
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000781 # Test for the fd leak reported in http://bugs.python.org/issue2791.
782 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000783 for stdin_pipe in (False, True):
784 for stdout_pipe in (False, True):
785 for stderr_pipe in (False, True):
786 options = {}
787 if stdin_pipe:
788 options['stdin'] = subprocess.PIPE
789 if stdout_pipe:
790 options['stdout'] = subprocess.PIPE
791 if stderr_pipe:
792 options['stderr'] = subprocess.PIPE
793 if not options:
794 continue
795 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
796 p.communicate()
797 if p.stdin is not None:
798 self.assertTrue(p.stdin.closed)
799 if p.stdout is not None:
800 self.assertTrue(p.stdout.closed)
801 if p.stderr is not None:
802 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000803
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000804 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000805 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000806 p = subprocess.Popen([sys.executable, "-c",
807 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000808 (stdout, stderr) = p.communicate()
809 self.assertEqual(stdout, None)
810 self.assertEqual(stderr, None)
811
812 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000813 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000814 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000815 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000816 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000817 os.close(x)
818 os.close(y)
819 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000820 'import sys,os;'
821 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200822 'sys.stderr.write("x" * %d);'
823 'sys.stdout.write(sys.stdin.read())' %
824 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000825 stdin=subprocess.PIPE,
826 stdout=subprocess.PIPE,
827 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000828 self.addCleanup(p.stdout.close)
829 self.addCleanup(p.stderr.close)
830 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200831 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000832 (stdout, stderr) = p.communicate(string_to_write)
833 self.assertEqual(stdout, string_to_write)
834
835 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000836 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000837 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000838 'import sys,os;'
839 'sys.stdout.write(sys.stdin.read())'],
840 stdin=subprocess.PIPE,
841 stdout=subprocess.PIPE,
842 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000843 self.addCleanup(p.stdout.close)
844 self.addCleanup(p.stderr.close)
845 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000846 p.stdin.write(b"banana")
847 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000848 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000849 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000850
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000851 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000852 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000853 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200854 'buf = sys.stdout.buffer;'
855 'buf.write(sys.stdin.readline().encode());'
856 'buf.flush();'
857 'buf.write(b"line2\\n");'
858 'buf.flush();'
859 'buf.write(sys.stdin.read().encode());'
860 'buf.flush();'
861 'buf.write(b"line4\\n");'
862 'buf.flush();'
863 'buf.write(b"line5\\r\\n");'
864 'buf.flush();'
865 'buf.write(b"line6\\r");'
866 'buf.flush();'
867 'buf.write(b"\\nline7");'
868 'buf.flush();'
869 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200870 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000871 stdout=subprocess.PIPE,
872 universal_newlines=1)
Victor Stinner7438c612016-05-20 12:43:15 +0200873 with p:
874 p.stdin.write("line1\n")
875 p.stdin.flush()
876 self.assertEqual(p.stdout.readline(), "line1\n")
877 p.stdin.write("line3\n")
878 p.stdin.close()
879 self.addCleanup(p.stdout.close)
880 self.assertEqual(p.stdout.readline(),
881 "line2\n")
882 self.assertEqual(p.stdout.read(6),
883 "line3\n")
884 self.assertEqual(p.stdout.read(),
885 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000886
887 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000888 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000889 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000890 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200891 'buf = sys.stdout.buffer;'
892 'buf.write(b"line2\\n");'
893 'buf.flush();'
894 'buf.write(b"line4\\n");'
895 'buf.flush();'
896 'buf.write(b"line5\\r\\n");'
897 'buf.flush();'
898 'buf.write(b"line6\\r");'
899 'buf.flush();'
900 'buf.write(b"\\nline7");'
901 'buf.flush();'
902 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200903 stderr=subprocess.PIPE,
904 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000905 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000906 self.addCleanup(p.stdout.close)
907 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000908 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200909 self.assertEqual(stdout,
910 "line2\nline4\nline5\nline6\nline7\nline8")
911
912 def test_universal_newlines_communicate_stdin(self):
913 # universal newlines through communicate(), with only stdin
914 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300915 'import sys,os;' + SETBINARY + textwrap.dedent('''
916 s = sys.stdin.readline()
917 assert s == "line1\\n", repr(s)
918 s = sys.stdin.read()
919 assert s == "line3\\n", repr(s)
920 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200921 stdin=subprocess.PIPE,
922 universal_newlines=1)
923 (stdout, stderr) = p.communicate("line1\nline3\n")
924 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000925
Andrew Svetlovf3765072012-08-14 18:35:17 +0300926 def test_universal_newlines_communicate_input_none(self):
927 # Test communicate(input=None) with universal newlines.
928 #
929 # We set stdout to PIPE because, as of this writing, a different
930 # code path is tested when the number of pipes is zero or one.
931 p = subprocess.Popen([sys.executable, "-c", "pass"],
932 stdin=subprocess.PIPE,
933 stdout=subprocess.PIPE,
934 universal_newlines=True)
935 p.communicate()
936 self.assertEqual(p.returncode, 0)
937
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300938 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300939 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300940 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300941 'import sys,os;' + SETBINARY + textwrap.dedent('''
942 s = sys.stdin.buffer.readline()
943 sys.stdout.buffer.write(s)
944 sys.stdout.buffer.write(b"line2\\r")
945 sys.stderr.buffer.write(b"eline2\\n")
946 s = sys.stdin.buffer.read()
947 sys.stdout.buffer.write(s)
948 sys.stdout.buffer.write(b"line4\\n")
949 sys.stdout.buffer.write(b"line5\\r\\n")
950 sys.stderr.buffer.write(b"eline6\\r")
951 sys.stderr.buffer.write(b"eline7\\r\\nz")
952 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300953 stdin=subprocess.PIPE,
954 stderr=subprocess.PIPE,
955 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300956 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300957 self.addCleanup(p.stdout.close)
958 self.addCleanup(p.stderr.close)
959 (stdout, stderr) = p.communicate("line1\nline3\n")
960 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300961 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300962 # Python debug build push something like "[42442 refs]\n"
963 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300964 # Don't use assertStderrEqual because it strips CR and LF from output.
965 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300966
Andrew Svetlov82860712012-08-19 22:13:41 +0300967 def test_universal_newlines_communicate_encodings(self):
968 # Check that universal newlines mode works for various encodings,
969 # in particular for encodings in the UTF-16 and UTF-32 families.
970 # See issue #15595.
971 #
972 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
973 # without, and UTF-16 and UTF-32.
974 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300975 code = ("import sys; "
976 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
977 encoding)
978 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700979 # We set stdin to be non-None because, as of this writing,
980 # a different code path is used when the number of pipes is
981 # zero or one.
982 popen = subprocess.Popen(args,
983 stdin=subprocess.PIPE,
984 stdout=subprocess.PIPE,
985 encoding=encoding)
986 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +0300987 self.assertEqual(stdout, '1\n2\n3\n4')
988
Steve Dower050acae2016-09-06 20:16:17 -0700989 def test_communicate_errors(self):
990 for errors, expected in [
991 ('ignore', ''),
992 ('replace', '\ufffd\ufffd'),
993 ('surrogateescape', '\udc80\udc80'),
994 ('backslashreplace', '\\x80\\x80'),
995 ]:
996 code = ("import sys; "
997 r"sys.stdout.buffer.write(b'[\x80\x80]')")
998 args = [sys.executable, '-c', code]
999 # We set stdin to be non-None because, as of this writing,
1000 # a different code path is used when the number of pipes is
1001 # zero or one.
1002 popen = subprocess.Popen(args,
1003 stdin=subprocess.PIPE,
1004 stdout=subprocess.PIPE,
1005 encoding='utf-8',
1006 errors=errors)
1007 stdout, stderr = popen.communicate(input='')
1008 self.assertEqual(stdout, '[{}]'.format(expected))
1009
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001010 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001011 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +00001012 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001013 max_handles = 1026 # too much for most UNIX systems
1014 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001015 max_handles = 2050 # too much for (at least some) Windows setups
1016 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001017 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001018 try:
1019 for i in range(max_handles):
1020 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001021 tmpfile = os.path.join(tmpdir, support.TESTFN)
1022 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001023 except OSError as e:
1024 if e.errno != errno.EMFILE:
1025 raise
1026 break
1027 else:
1028 self.skipTest("failed to reach the file descriptor limit "
1029 "(tried %d)" % max_handles)
1030 # Close a couple of them (should be enough for a subprocess)
1031 for i in range(10):
1032 os.close(handles.pop())
1033 # Loop creating some subprocesses. If one of them leaks some fds,
1034 # the next loop iteration will fail by reaching the max fd limit.
1035 for i in range(15):
1036 p = subprocess.Popen([sys.executable, "-c",
1037 "import sys;"
1038 "sys.stdout.write(sys.stdin.read())"],
1039 stdin=subprocess.PIPE,
1040 stdout=subprocess.PIPE,
1041 stderr=subprocess.PIPE)
1042 data = p.communicate(b"lime")[0]
1043 self.assertEqual(data, b"lime")
1044 finally:
1045 for h in handles:
1046 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001047 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001048
1049 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001050 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1051 '"a b c" d e')
1052 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1053 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001054 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1055 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001056 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1057 'a\\\\\\b "de fg" h')
1058 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1059 'a\\\\\\"b c d')
1060 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1061 '"a\\\\b c" d e')
1062 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1063 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001064 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1065 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001066
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001067 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001068 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001069 "import os; os.read(0, 1)"],
1070 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001071 self.addCleanup(p.stdin.close)
1072 self.assertIsNone(p.poll())
1073 os.write(p.stdin.fileno(), b'A')
1074 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001075 # Subsequent invocations should just return the returncode
1076 self.assertEqual(p.poll(), 0)
1077
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001078 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001079 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001080 self.assertEqual(p.wait(), 0)
1081 # Subsequent invocations should just return the returncode
1082 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001083
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001084 def test_wait_timeout(self):
1085 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001086 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001087 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001088 p.wait(timeout=0.0001)
1089 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001090 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1091 # time to start.
1092 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001093
Peter Astrand738131d2004-11-30 21:04:45 +00001094 def test_invalid_bufsize(self):
1095 # an invalid type of the bufsize argument should raise
1096 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001097 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001098 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001099
Guido van Rossum46a05a72007-06-07 21:56:45 +00001100 def test_bufsize_is_none(self):
1101 # bufsize=None should be the same as bufsize=0.
1102 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1103 self.assertEqual(p.wait(), 0)
1104 # Again with keyword arg
1105 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1106 self.assertEqual(p.wait(), 0)
1107
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001108 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1109 # subprocess may deadlock with bufsize=1, see issue #21332
1110 with subprocess.Popen([sys.executable, "-c", "import sys;"
1111 "sys.stdout.write(sys.stdin.readline());"
1112 "sys.stdout.flush()"],
1113 stdin=subprocess.PIPE,
1114 stdout=subprocess.PIPE,
1115 stderr=subprocess.DEVNULL,
1116 bufsize=1,
1117 universal_newlines=universal_newlines) as p:
1118 p.stdin.write(line) # expect that it flushes the line in text mode
1119 os.close(p.stdin.fileno()) # close it without flushing the buffer
1120 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001121 with support.SuppressCrashReport():
1122 try:
1123 p.stdin.close()
1124 except OSError:
1125 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001126 p.stdin = None
1127 self.assertEqual(p.returncode, 0)
1128 self.assertEqual(read_line, expected)
1129
1130 def test_bufsize_equal_one_text_mode(self):
1131 # line is flushed in text mode with bufsize=1.
1132 # we should get the full line in return
1133 line = "line\n"
1134 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1135
1136 def test_bufsize_equal_one_binary_mode(self):
1137 # line is not flushed in binary mode with bufsize=1.
1138 # we should get empty response
1139 line = b'line' + os.linesep.encode() # assume ascii-based locale
1140 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1141
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001142 def test_leaking_fds_on_error(self):
1143 # see bug #5179: Popen leaks file descriptors to PIPEs if
1144 # the child fails to execute; this will eventually exhaust
1145 # the maximum number of open fds. 1024 seems a very common
1146 # value for that limit, but Windows has 2048, so we loop
1147 # 1024 times (each call leaked two fds).
1148 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001149 with self.assertRaises(OSError) as c:
Victor Stinner9a83f652017-08-21 23:51:31 +02001150 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001151 stdout=subprocess.PIPE,
1152 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001153 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001154 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001155 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001156
Victor Stinner9a83f652017-08-21 23:51:31 +02001157 def test_nonexisting_with_pipes(self):
1158 # bpo-30121: Popen with pipes must close properly pipes on error.
1159 # Previously, os.close() was called with a Windows handle which is not
1160 # a valid file descriptor.
1161 #
1162 # Run the test in a subprocess to control how the CRT reports errors
1163 # and to get stderr content.
1164 try:
1165 import msvcrt
1166 msvcrt.CrtSetReportMode
1167 except (AttributeError, ImportError):
1168 self.skipTest("need msvcrt.CrtSetReportMode")
1169
1170 code = textwrap.dedent(f"""
1171 import msvcrt
1172 import subprocess
1173
1174 cmd = {NONEXISTING_CMD!r}
1175
1176 for report_type in [msvcrt.CRT_WARN,
1177 msvcrt.CRT_ERROR,
1178 msvcrt.CRT_ASSERT]:
1179 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1180 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1181
1182 try:
1183 subprocess.Popen([cmd],
1184 stdout=subprocess.PIPE,
1185 stderr=subprocess.PIPE)
1186 except OSError:
1187 pass
1188 """)
1189 cmd = [sys.executable, "-c", code]
1190 proc = subprocess.Popen(cmd,
1191 stderr=subprocess.PIPE,
1192 universal_newlines=True)
1193 with proc:
1194 stderr = proc.communicate()[1]
1195 self.assertEqual(stderr, "")
1196 self.assertEqual(proc.returncode, 0)
1197
Antoine Pitroua8392712013-08-30 23:38:13 +02001198 @unittest.skipIf(threading is None, "threading required")
1199 def test_double_close_on_error(self):
1200 # Issue #18851
1201 fds = []
1202 def open_fds():
1203 for i in range(20):
1204 fds.extend(os.pipe())
1205 time.sleep(0.001)
1206 t = threading.Thread(target=open_fds)
1207 t.start()
1208 try:
1209 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001210 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001211 stdin=subprocess.PIPE,
1212 stdout=subprocess.PIPE,
1213 stderr=subprocess.PIPE)
1214 finally:
1215 t.join()
1216 exc = None
1217 for fd in fds:
1218 # If a double close occurred, some of those fds will
1219 # already have been closed by mistake, and os.close()
1220 # here will raise.
1221 try:
1222 os.close(fd)
1223 except OSError as e:
1224 exc = e
1225 if exc is not None:
1226 raise exc
1227
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001228 @unittest.skipIf(threading is None, "threading required")
1229 def test_threadsafe_wait(self):
1230 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1231 proc = subprocess.Popen([sys.executable, '-c',
1232 'import time; time.sleep(12)'])
1233 self.assertEqual(proc.returncode, None)
1234 results = []
1235
1236 def kill_proc_timer_thread():
1237 results.append(('thread-start-poll-result', proc.poll()))
1238 # terminate it from the thread and wait for the result.
1239 proc.kill()
1240 proc.wait()
1241 results.append(('thread-after-kill-and-wait', proc.returncode))
1242 # this wait should be a no-op given the above.
1243 proc.wait()
1244 results.append(('thread-after-second-wait', proc.returncode))
1245
1246 # This is a timing sensitive test, the failure mode is
1247 # triggered when both the main thread and this thread are in
1248 # the wait() call at once. The delay here is to allow the
1249 # main thread to most likely be blocked in its wait() call.
1250 t = threading.Timer(0.2, kill_proc_timer_thread)
1251 t.start()
1252
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001253 if mswindows:
1254 expected_errorcode = 1
1255 else:
1256 # Should be -9 because of the proc.kill() from the thread.
1257 expected_errorcode = -9
1258
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001259 # Wait for the process to finish; the thread should kill it
1260 # long before it finishes on its own. Supplying a timeout
1261 # triggers a different code path for better coverage.
1262 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001263 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001264 msg="unexpected result in wait from main thread")
1265
1266 # This should be a no-op with no change in returncode.
1267 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001268 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001269 msg="unexpected result in second main wait.")
1270
1271 t.join()
1272 # Ensure that all of the thread results are as expected.
1273 # When a race condition occurs in wait(), the returncode could
1274 # be set by the wrong thread that doesn't actually have it
1275 # leading to an incorrect value.
1276 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001277 ('thread-after-kill-and-wait', expected_errorcode),
1278 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001279 results)
1280
Victor Stinnerb3693582010-05-21 20:13:12 +00001281 def test_issue8780(self):
1282 # Ensure that stdout is inherited from the parent
1283 # if stdout=PIPE is not used
1284 code = ';'.join((
1285 'import subprocess, sys',
1286 'retcode = subprocess.call('
1287 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1288 'assert retcode == 0'))
1289 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001290 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001291
Tim Goldenaf5ac392010-08-06 13:03:56 +00001292 def test_handles_closed_on_exception(self):
1293 # If CreateProcess exits with an error, ensure the
1294 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001295 ifhandle, ifname = tempfile.mkstemp()
1296 ofhandle, ofname = tempfile.mkstemp()
1297 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001298 try:
1299 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1300 stderr=efhandle)
1301 except OSError:
1302 os.close(ifhandle)
1303 os.remove(ifname)
1304 os.close(ofhandle)
1305 os.remove(ofname)
1306 os.close(efhandle)
1307 os.remove(efname)
1308 self.assertFalse(os.path.exists(ifname))
1309 self.assertFalse(os.path.exists(ofname))
1310 self.assertFalse(os.path.exists(efname))
1311
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001312 def test_communicate_epipe(self):
1313 # Issue 10963: communicate() should hide EPIPE
1314 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1315 stdin=subprocess.PIPE,
1316 stdout=subprocess.PIPE,
1317 stderr=subprocess.PIPE)
1318 self.addCleanup(p.stdout.close)
1319 self.addCleanup(p.stderr.close)
1320 self.addCleanup(p.stdin.close)
1321 p.communicate(b"x" * 2**20)
1322
1323 def test_communicate_epipe_only_stdin(self):
1324 # Issue 10963: communicate() should hide EPIPE
1325 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1326 stdin=subprocess.PIPE)
1327 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001328 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001329 p.communicate(b"x" * 2**20)
1330
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001331 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1332 "Requires signal.SIGUSR1")
1333 @unittest.skipUnless(hasattr(os, 'kill'),
1334 "Requires os.kill")
1335 @unittest.skipUnless(hasattr(os, 'getppid'),
1336 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001337 def test_communicate_eintr(self):
1338 # Issue #12493: communicate() should handle EINTR
1339 def handler(signum, frame):
1340 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001341 old_handler = signal.signal(signal.SIGUSR1, handler)
1342 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001343
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001344 args = [sys.executable, "-c",
1345 'import os, signal;'
1346 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001347 for stream in ('stdout', 'stderr'):
1348 kw = {stream: subprocess.PIPE}
1349 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001350 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001351 process.communicate()
1352
Tim Peterse718f612004-10-12 21:51:32 +00001353
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001354 # This test is Linux-ish specific for simplicity to at least have
1355 # some coverage. It is not a platform specific bug.
1356 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1357 "Linux specific")
1358 def test_failed_child_execute_fd_leak(self):
1359 """Test for the fork() failure fd leak reported in issue16327."""
1360 fd_directory = '/proc/%d/fd' % os.getpid()
1361 fds_before_popen = os.listdir(fd_directory)
1362 with self.assertRaises(PopenTestException):
1363 PopenExecuteChildRaises(
1364 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1365 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1366
1367 # NOTE: This test doesn't verify that the real _execute_child
1368 # does not close the file descriptors itself on the way out
1369 # during an exception. Code inspection has confirmed that.
1370
1371 fds_after_exception = os.listdir(fd_directory)
1372 self.assertEqual(fds_before_popen, fds_after_exception)
1373
Gregory P. Smitha3a6df32017-08-24 18:15:02 -07001374 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001375 def test_file_not_found_includes_filename(self):
1376 with self.assertRaises(FileNotFoundError) as c:
1377 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1378 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1379
Gregory P. Smitha3a6df32017-08-24 18:15:02 -07001380 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001381 def test_file_not_found_with_bad_cwd(self):
1382 with self.assertRaises(FileNotFoundError) as c:
1383 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1384 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1385
Gregory P. Smith6e730002015-04-14 16:14:25 -07001386
1387class RunFuncTestCase(BaseTestCase):
1388 def run_python(self, code, **kwargs):
1389 """Run Python code in a subprocess using subprocess.run"""
1390 argv = [sys.executable, "-c", code]
1391 return subprocess.run(argv, **kwargs)
1392
1393 def test_returncode(self):
1394 # call() function with sequence argument
1395 cp = self.run_python("import sys; sys.exit(47)")
1396 self.assertEqual(cp.returncode, 47)
1397 with self.assertRaises(subprocess.CalledProcessError):
1398 cp.check_returncode()
1399
1400 def test_check(self):
1401 with self.assertRaises(subprocess.CalledProcessError) as c:
1402 self.run_python("import sys; sys.exit(47)", check=True)
1403 self.assertEqual(c.exception.returncode, 47)
1404
1405 def test_check_zero(self):
1406 # check_returncode shouldn't raise when returncode is zero
1407 cp = self.run_python("import sys; sys.exit(0)", check=True)
1408 self.assertEqual(cp.returncode, 0)
1409
1410 def test_timeout(self):
1411 # run() function with timeout argument; we want to test that the child
1412 # process gets killed when the timeout expires. If the child isn't
1413 # killed, this call will deadlock since subprocess.run waits for the
1414 # child.
1415 with self.assertRaises(subprocess.TimeoutExpired):
1416 self.run_python("while True: pass", timeout=0.0001)
1417
1418 def test_capture_stdout(self):
1419 # capture stdout with zero return code
1420 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1421 self.assertIn(b'BDFL', cp.stdout)
1422
1423 def test_capture_stderr(self):
1424 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1425 stderr=subprocess.PIPE)
1426 self.assertIn(b'BDFL', cp.stderr)
1427
1428 def test_check_output_stdin_arg(self):
1429 # run() can be called with stdin set to a file
1430 tf = tempfile.TemporaryFile()
1431 self.addCleanup(tf.close)
1432 tf.write(b'pear')
1433 tf.seek(0)
1434 cp = self.run_python(
1435 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1436 stdin=tf, stdout=subprocess.PIPE)
1437 self.assertIn(b'PEAR', cp.stdout)
1438
1439 def test_check_output_input_arg(self):
1440 # check_output() can be called with input set to a string
1441 cp = self.run_python(
1442 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1443 input=b'pear', stdout=subprocess.PIPE)
1444 self.assertIn(b'PEAR', cp.stdout)
1445
1446 def test_check_output_stdin_with_input_arg(self):
1447 # run() refuses to accept 'stdin' with 'input'
1448 tf = tempfile.TemporaryFile()
1449 self.addCleanup(tf.close)
1450 tf.write(b'pear')
1451 tf.seek(0)
1452 with self.assertRaises(ValueError,
1453 msg="Expected ValueError when stdin and input args supplied.") as c:
1454 output = self.run_python("print('will not be run')",
1455 stdin=tf, input=b'hare')
1456 self.assertIn('stdin', c.exception.args[0])
1457 self.assertIn('input', c.exception.args[0])
1458
1459 def test_check_output_timeout(self):
1460 with self.assertRaises(subprocess.TimeoutExpired) as c:
1461 cp = self.run_python((
1462 "import sys, time\n"
1463 "sys.stdout.write('BDFL')\n"
1464 "sys.stdout.flush()\n"
1465 "time.sleep(3600)"),
1466 # Some heavily loaded buildbots (sparc Debian 3.x) require
1467 # this much time to start and print.
1468 timeout=3, stdout=subprocess.PIPE)
1469 self.assertEqual(c.exception.output, b'BDFL')
1470 # output is aliased to stdout
1471 self.assertEqual(c.exception.stdout, b'BDFL')
1472
1473 def test_run_kwargs(self):
1474 newenv = os.environ.copy()
1475 newenv["FRUIT"] = "banana"
1476 cp = self.run_python(('import sys, os;'
1477 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1478 env=newenv)
1479 self.assertEqual(cp.returncode, 33)
1480
1481
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001482@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001483class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001484
Gregory P. Smith5591b022012-10-10 03:34:47 -07001485 def setUp(self):
1486 super().setUp()
1487 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1488
1489 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001490 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001491 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001492 except OSError as e:
1493 # This avoids hard coding the errno value or the OS perror()
1494 # string and instead capture the exception that we want to see
1495 # below for comparison.
1496 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001497 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001498 else:
Martin Pantereb995702016-07-28 01:11:04 +00001499 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001500 self._nonexistent_dir)
1501 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001502
Gregory P. Smith5591b022012-10-10 03:34:47 -07001503 def test_exception_cwd(self):
1504 """Test error in the child raised in the parent for a bad cwd."""
1505 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001506 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001507 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001508 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001509 except OSError as e:
1510 # Test that the child process chdir failure actually makes
1511 # it up to the parent process as the correct exception.
1512 self.assertEqual(desired_exception.errno, e.errno)
1513 self.assertEqual(desired_exception.strerror, e.strerror)
1514 else:
1515 self.fail("Expected OSError: %s" % desired_exception)
1516
Gregory P. Smith5591b022012-10-10 03:34:47 -07001517 def test_exception_bad_executable(self):
1518 """Test error in the child raised in the parent for a bad executable."""
1519 desired_exception = self._get_chdir_exception()
1520 try:
1521 p = subprocess.Popen([sys.executable, "-c", ""],
1522 executable=self._nonexistent_dir)
1523 except OSError as e:
1524 # Test that the child process exec failure actually makes
1525 # it up to the parent process as the correct exception.
1526 self.assertEqual(desired_exception.errno, e.errno)
1527 self.assertEqual(desired_exception.strerror, e.strerror)
1528 else:
1529 self.fail("Expected OSError: %s" % desired_exception)
1530
1531 def test_exception_bad_args_0(self):
1532 """Test error in the child raised in the parent for a bad args[0]."""
1533 desired_exception = self._get_chdir_exception()
1534 try:
1535 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1536 except OSError as e:
1537 # Test that the child process exec failure actually makes
1538 # it up to the parent process as the correct exception.
1539 self.assertEqual(desired_exception.errno, e.errno)
1540 self.assertEqual(desired_exception.strerror, e.strerror)
1541 else:
1542 self.fail("Expected OSError: %s" % desired_exception)
1543
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001544 def test_restore_signals(self):
1545 # Code coverage for both values of restore_signals to make sure it
1546 # at least does not blow up.
1547 # A test for behavior would be complex. Contributions welcome.
1548 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1549 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1550
1551 def test_start_new_session(self):
1552 # For code coverage of calling setsid(). We don't care if we get an
1553 # EPERM error from it depending on the test execution environment, that
1554 # still indicates that it was called.
1555 try:
1556 output = subprocess.check_output(
1557 [sys.executable, "-c",
1558 "import os; print(os.getpgid(os.getpid()))"],
1559 start_new_session=True)
1560 except OSError as e:
1561 if e.errno != errno.EPERM:
1562 raise
1563 else:
1564 parent_pgid = os.getpgid(os.getpid())
1565 child_pgid = int(output)
1566 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001567
1568 def test_run_abort(self):
1569 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001570 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001571 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001572 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001573 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001574 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001575
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001576 def test_CalledProcessError_str_signal(self):
1577 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1578 error_string = str(err)
1579 # We're relying on the repr() of the signal.Signals intenum to provide
1580 # the word signal, the signal name and the numeric value.
1581 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001582 # We're not being specific about the signal name as some signals have
1583 # multiple names and which name is revealed can vary.
1584 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001585 self.assertIn(str(signal.SIGABRT), error_string)
1586
1587 def test_CalledProcessError_str_unknown_signal(self):
1588 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1589 error_string = str(err)
1590 self.assertIn("unknown signal 9876543.", error_string)
1591
1592 def test_CalledProcessError_str_non_zero(self):
1593 err = subprocess.CalledProcessError(2, "fake cmd")
1594 error_string = str(err)
1595 self.assertIn("non-zero exit status 2.", error_string)
1596
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001597 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001598 # DISCLAIMER: Setting environment variables is *not* a good use
1599 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001600 p = subprocess.Popen([sys.executable, "-c",
1601 'import sys,os;'
1602 'sys.stdout.write(os.getenv("FRUIT"))'],
1603 stdout=subprocess.PIPE,
1604 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001605 with p:
1606 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001607
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001608 def test_preexec_exception(self):
1609 def raise_it():
1610 raise ValueError("What if two swallows carried a coconut?")
1611 try:
1612 p = subprocess.Popen([sys.executable, "-c", ""],
1613 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001614 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001615 self.assertTrue(
1616 subprocess._posixsubprocess,
1617 "Expected a ValueError from the preexec_fn")
1618 except ValueError as e:
1619 self.assertIn("coconut", e.args[0])
1620 else:
1621 self.fail("Exception raised by preexec_fn did not make it "
1622 "to the parent process.")
1623
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001624 class _TestExecuteChildPopen(subprocess.Popen):
1625 """Used to test behavior at the end of _execute_child."""
1626 def __init__(self, testcase, *args, **kwargs):
1627 self._testcase = testcase
1628 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001629
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001630 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001631 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001632 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001633 finally:
1634 # Open a bunch of file descriptors and verify that
1635 # none of them are the same as the ones the Popen
1636 # instance is using for stdin/stdout/stderr.
1637 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1638 for _ in range(8)]
1639 try:
1640 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001641 self._testcase.assertNotIn(
1642 fd, (self.stdin.fileno(), self.stdout.fileno(),
1643 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001644 msg="At least one fd was closed early.")
1645 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001646 for fd in devzero_fds:
1647 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001648
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001649 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1650 def test_preexec_errpipe_does_not_double_close_pipes(self):
1651 """Issue16140: Don't double close pipes on preexec error."""
1652
1653 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001654 raise subprocess.SubprocessError(
1655 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001656
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001657 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001658 self._TestExecuteChildPopen(
1659 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001660 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1661 stderr=subprocess.PIPE, preexec_fn=raise_it)
1662
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001663 def test_preexec_gc_module_failure(self):
1664 # This tests the code that disables garbage collection if the child
1665 # process will execute any Python.
1666 def raise_runtime_error():
1667 raise RuntimeError("this shouldn't escape")
1668 enabled = gc.isenabled()
1669 orig_gc_disable = gc.disable
1670 orig_gc_isenabled = gc.isenabled
1671 try:
1672 gc.disable()
1673 self.assertFalse(gc.isenabled())
1674 subprocess.call([sys.executable, '-c', ''],
1675 preexec_fn=lambda: None)
1676 self.assertFalse(gc.isenabled(),
1677 "Popen enabled gc when it shouldn't.")
1678
1679 gc.enable()
1680 self.assertTrue(gc.isenabled())
1681 subprocess.call([sys.executable, '-c', ''],
1682 preexec_fn=lambda: None)
1683 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1684
1685 gc.disable = raise_runtime_error
1686 self.assertRaises(RuntimeError, subprocess.Popen,
1687 [sys.executable, '-c', ''],
1688 preexec_fn=lambda: None)
1689
1690 del gc.isenabled # force an AttributeError
1691 self.assertRaises(AttributeError, subprocess.Popen,
1692 [sys.executable, '-c', ''],
1693 preexec_fn=lambda: None)
1694 finally:
1695 gc.disable = orig_gc_disable
1696 gc.isenabled = orig_gc_isenabled
1697 if not enabled:
1698 gc.disable()
1699
Martin Panterf7fdbda2015-12-05 09:51:52 +00001700 @unittest.skipIf(
1701 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001702 def test_preexec_fork_failure(self):
1703 # The internal code did not preserve the previous exception when
1704 # re-enabling garbage collection
1705 try:
1706 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1707 except ImportError as err:
1708 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1709 limits = getrlimit(RLIMIT_NPROC)
1710 [_, hard] = limits
1711 setrlimit(RLIMIT_NPROC, (0, hard))
1712 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001713 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001714 subprocess.call([sys.executable, '-c', ''],
1715 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001716 except BlockingIOError:
1717 # Forking should raise EAGAIN, translated to BlockingIOError
1718 pass
1719 else:
1720 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001721
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001722 def test_args_string(self):
1723 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001724 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001725 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001726 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001727 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001728 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1729 sys.executable)
1730 os.chmod(fname, 0o700)
1731 p = subprocess.Popen(fname)
1732 p.wait()
1733 os.remove(fname)
1734 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001735
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001736 def test_invalid_args(self):
1737 # invalid arguments should raise ValueError
1738 self.assertRaises(ValueError, subprocess.call,
1739 [sys.executable, "-c",
1740 "import sys; sys.exit(47)"],
1741 startupinfo=47)
1742 self.assertRaises(ValueError, subprocess.call,
1743 [sys.executable, "-c",
1744 "import sys; sys.exit(47)"],
1745 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001746
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001747 def test_shell_sequence(self):
1748 # Run command through the shell (sequence)
1749 newenv = os.environ.copy()
1750 newenv["FRUIT"] = "apple"
1751 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1752 stdout=subprocess.PIPE,
1753 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001754 with p:
1755 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001756
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001757 def test_shell_string(self):
1758 # Run command through the shell (string)
1759 newenv = os.environ.copy()
1760 newenv["FRUIT"] = "apple"
1761 p = subprocess.Popen("echo $FRUIT", shell=1,
1762 stdout=subprocess.PIPE,
1763 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001764 with p:
1765 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001766
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001767 def test_call_string(self):
1768 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001769 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001770 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001771 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001772 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001773 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1774 sys.executable)
1775 os.chmod(fname, 0o700)
1776 rc = subprocess.call(fname)
1777 os.remove(fname)
1778 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001779
Stefan Krah9542cc62010-07-19 14:20:53 +00001780 def test_specific_shell(self):
1781 # Issue #9265: Incorrect name passed as arg[0].
1782 shells = []
1783 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1784 for name in ['bash', 'ksh']:
1785 sh = os.path.join(prefix, name)
1786 if os.path.isfile(sh):
1787 shells.append(sh)
1788 if not shells: # Will probably work for any shell but csh.
1789 self.skipTest("bash or ksh required for this test")
1790 sh = '/bin/sh'
1791 if os.path.isfile(sh) and not os.path.islink(sh):
1792 # Test will fail if /bin/sh is a symlink to csh.
1793 shells.append(sh)
1794 for sh in shells:
1795 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1796 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001797 with p:
1798 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001799
Florent Xicluna4886d242010-03-08 13:27:26 +00001800 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001801 # Do not inherit file handles from the parent.
1802 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001803 # Also set the SIGINT handler to the default to make sure it's not
1804 # being ignored (some tests rely on that.)
1805 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1806 try:
1807 p = subprocess.Popen([sys.executable, "-c", """if 1:
1808 import sys, time
1809 sys.stdout.write('x\\n')
1810 sys.stdout.flush()
1811 time.sleep(30)
1812 """],
1813 close_fds=True,
1814 stdin=subprocess.PIPE,
1815 stdout=subprocess.PIPE,
1816 stderr=subprocess.PIPE)
1817 finally:
1818 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001819 # Wait for the interpreter to be completely initialized before
1820 # sending any signal.
1821 p.stdout.read(1)
1822 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001823 return p
1824
Charles-François Natali53221e32013-01-12 16:52:20 +01001825 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1826 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001827 def _kill_dead_process(self, method, *args):
1828 # Do not inherit file handles from the parent.
1829 # It should fix failures on some platforms.
1830 p = subprocess.Popen([sys.executable, "-c", """if 1:
1831 import sys, time
1832 sys.stdout.write('x\\n')
1833 sys.stdout.flush()
1834 """],
1835 close_fds=True,
1836 stdin=subprocess.PIPE,
1837 stdout=subprocess.PIPE,
1838 stderr=subprocess.PIPE)
1839 # Wait for the interpreter to be completely initialized before
1840 # sending any signal.
1841 p.stdout.read(1)
1842 # The process should end after this
1843 time.sleep(1)
1844 # This shouldn't raise even though the child is now dead
1845 getattr(p, method)(*args)
1846 p.communicate()
1847
Florent Xicluna4886d242010-03-08 13:27:26 +00001848 def test_send_signal(self):
1849 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001850 _, stderr = p.communicate()
1851 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001852 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001853
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001854 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001855 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001856 _, stderr = p.communicate()
1857 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001858 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001859
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001860 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001861 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001862 _, stderr = p.communicate()
1863 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001864 self.assertEqual(p.wait(), -signal.SIGTERM)
1865
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001866 def test_send_signal_dead(self):
1867 # Sending a signal to a dead process
1868 self._kill_dead_process('send_signal', signal.SIGINT)
1869
1870 def test_kill_dead(self):
1871 # Killing a dead process
1872 self._kill_dead_process('kill')
1873
1874 def test_terminate_dead(self):
1875 # Terminating a dead process
1876 self._kill_dead_process('terminate')
1877
Victor Stinnerdaf45552013-08-28 00:53:59 +02001878 def _save_fds(self, save_fds):
1879 fds = []
1880 for fd in save_fds:
1881 inheritable = os.get_inheritable(fd)
1882 saved = os.dup(fd)
1883 fds.append((fd, saved, inheritable))
1884 return fds
1885
1886 def _restore_fds(self, fds):
1887 for fd, saved, inheritable in fds:
1888 os.dup2(saved, fd, inheritable=inheritable)
1889 os.close(saved)
1890
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001891 def check_close_std_fds(self, fds):
1892 # Issue #9905: test that subprocess pipes still work properly with
1893 # some standard fds closed
1894 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001895 saved_fds = self._save_fds(fds)
1896 for fd, saved, inheritable in saved_fds:
1897 if fd == 0:
1898 stdin = saved
1899 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001900 try:
1901 for fd in fds:
1902 os.close(fd)
1903 out, err = subprocess.Popen([sys.executable, "-c",
1904 'import sys;'
1905 'sys.stdout.write("apple");'
1906 'sys.stdout.flush();'
1907 'sys.stderr.write("orange")'],
1908 stdin=stdin,
1909 stdout=subprocess.PIPE,
1910 stderr=subprocess.PIPE).communicate()
1911 err = support.strip_python_stderr(err)
1912 self.assertEqual((out, err), (b'apple', b'orange'))
1913 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001914 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001915
1916 def test_close_fd_0(self):
1917 self.check_close_std_fds([0])
1918
1919 def test_close_fd_1(self):
1920 self.check_close_std_fds([1])
1921
1922 def test_close_fd_2(self):
1923 self.check_close_std_fds([2])
1924
1925 def test_close_fds_0_1(self):
1926 self.check_close_std_fds([0, 1])
1927
1928 def test_close_fds_0_2(self):
1929 self.check_close_std_fds([0, 2])
1930
1931 def test_close_fds_1_2(self):
1932 self.check_close_std_fds([1, 2])
1933
1934 def test_close_fds_0_1_2(self):
1935 # Issue #10806: test that subprocess pipes still work properly with
1936 # all standard fds closed.
1937 self.check_close_std_fds([0, 1, 2])
1938
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001939 def test_small_errpipe_write_fd(self):
1940 """Issue #15798: Popen should work when stdio fds are available."""
1941 new_stdin = os.dup(0)
1942 new_stdout = os.dup(1)
1943 try:
1944 os.close(0)
1945 os.close(1)
1946
1947 # Side test: if errpipe_write fails to have its CLOEXEC
1948 # flag set this should cause the parent to think the exec
1949 # failed. Extremely unlikely: everyone supports CLOEXEC.
1950 subprocess.Popen([
1951 sys.executable, "-c",
1952 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1953 finally:
1954 # Restore original stdin and stdout
1955 os.dup2(new_stdin, 0)
1956 os.dup2(new_stdout, 1)
1957 os.close(new_stdin)
1958 os.close(new_stdout)
1959
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001960 def test_remapping_std_fds(self):
1961 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001962 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001963 try:
1964 temp_fds = [fd for fd, fname in temps]
1965
1966 # unlink the files -- we won't need to reopen them
1967 for fd, fname in temps:
1968 os.unlink(fname)
1969
1970 # write some data to what will become stdin, and rewind
1971 os.write(temp_fds[1], b"STDIN")
1972 os.lseek(temp_fds[1], 0, 0)
1973
1974 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001975 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001976 try:
1977 # duplicate the file objects over the standard fd's
1978 for fd, temp_fd in enumerate(temp_fds):
1979 os.dup2(temp_fd, fd)
1980
1981 # now use those files in the "wrong" order, so that subprocess
1982 # has to rearrange them in the child
1983 p = subprocess.Popen([sys.executable, "-c",
1984 'import sys; got = sys.stdin.read();'
1985 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1986 stdin=temp_fds[1],
1987 stdout=temp_fds[2],
1988 stderr=temp_fds[0])
1989 p.wait()
1990 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001991 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001992
1993 for fd in temp_fds:
1994 os.lseek(fd, 0, 0)
1995
1996 out = os.read(temp_fds[2], 1024)
1997 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1998 self.assertEqual(out, b"got STDIN")
1999 self.assertEqual(err, b"err")
2000
2001 finally:
2002 for fd in temp_fds:
2003 os.close(fd)
2004
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002005 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2006 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002007 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002008 temp_fds = [fd for fd, fname in temps]
2009 try:
2010 # unlink the files -- we won't need to reopen them
2011 for fd, fname in temps:
2012 os.unlink(fname)
2013
2014 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002015 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002016 try:
2017 # duplicate the temp files over the standard fd's 0, 1, 2
2018 for fd, temp_fd in enumerate(temp_fds):
2019 os.dup2(temp_fd, fd)
2020
2021 # write some data to what will become stdin, and rewind
2022 os.write(stdin_no, b"STDIN")
2023 os.lseek(stdin_no, 0, 0)
2024
2025 # now use those files in the given order, so that subprocess
2026 # has to rearrange them in the child
2027 p = subprocess.Popen([sys.executable, "-c",
2028 'import sys; got = sys.stdin.read();'
2029 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2030 stdin=stdin_no,
2031 stdout=stdout_no,
2032 stderr=stderr_no)
2033 p.wait()
2034
2035 for fd in temp_fds:
2036 os.lseek(fd, 0, 0)
2037
2038 out = os.read(stdout_no, 1024)
2039 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2040 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002041 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002042
2043 self.assertEqual(out, b"got STDIN")
2044 self.assertEqual(err, b"err")
2045
2046 finally:
2047 for fd in temp_fds:
2048 os.close(fd)
2049
2050 # When duping fds, if there arises a situation where one of the fds is
2051 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2052 # This tests all combinations of this.
2053 def test_swap_fds(self):
2054 self.check_swap_fds(0, 1, 2)
2055 self.check_swap_fds(0, 2, 1)
2056 self.check_swap_fds(1, 0, 2)
2057 self.check_swap_fds(1, 2, 0)
2058 self.check_swap_fds(2, 0, 1)
2059 self.check_swap_fds(2, 1, 0)
2060
Victor Stinner13bb71c2010-04-23 21:41:56 +00002061 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002062 def prepare():
2063 raise ValueError("surrogate:\uDCff")
2064
2065 try:
2066 subprocess.call(
2067 [sys.executable, "-c", "pass"],
2068 preexec_fn=prepare)
2069 except ValueError as err:
2070 # Pure Python implementations keeps the message
2071 self.assertIsNone(subprocess._posixsubprocess)
2072 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002073 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002074 # _posixsubprocess uses a default message
2075 self.assertIsNotNone(subprocess._posixsubprocess)
2076 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2077 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002078 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002079
Victor Stinner13bb71c2010-04-23 21:41:56 +00002080 def test_undecodable_env(self):
2081 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002082 encoded_value = value.encode("ascii", "surrogateescape")
2083
Victor Stinner13bb71c2010-04-23 21:41:56 +00002084 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002085 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002086 env = os.environ.copy()
2087 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002088 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00002089 # surrogate-escaping of \xFF in the child process; otherwise it can
2090 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00002091 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01002092 if sys.platform.startswith("aix"):
2093 # On AIX, the C locale uses the Latin1 encoding
2094 decoded_value = encoded_value.decode("latin1", "surrogateescape")
2095 else:
2096 # On other UNIXes, the C locale uses the ASCII encoding
2097 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002098 stdout = subprocess.check_output(
2099 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002100 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002101 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002102 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002103
2104 # test bytes
2105 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002106 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002107 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002108 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002109 stdout = subprocess.check_output(
2110 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002111 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002112 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002113 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002114
Victor Stinnerb745a742010-05-18 17:17:23 +00002115 def test_bytes_program(self):
2116 abs_program = os.fsencode(sys.executable)
2117 path, program = os.path.split(sys.executable)
2118 program = os.fsencode(program)
2119
2120 # absolute bytes path
2121 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002122 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002123
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002124 # absolute bytes path as a string
2125 cmd = b"'" + abs_program + b"' -c pass"
2126 exitcode = subprocess.call(cmd, shell=True)
2127 self.assertEqual(exitcode, 0)
2128
Victor Stinnerb745a742010-05-18 17:17:23 +00002129 # bytes program, unicode PATH
2130 env = os.environ.copy()
2131 env["PATH"] = path
2132 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002133 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002134
2135 # bytes program, bytes PATH
2136 envb = os.environb.copy()
2137 envb[b"PATH"] = os.fsencode(path)
2138 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002139 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002140
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002141 def test_pipe_cloexec(self):
2142 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2143 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2144
2145 p1 = subprocess.Popen([sys.executable, sleeper],
2146 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2147 stderr=subprocess.PIPE, close_fds=False)
2148
2149 self.addCleanup(p1.communicate, b'')
2150
2151 p2 = subprocess.Popen([sys.executable, fd_status],
2152 stdout=subprocess.PIPE, close_fds=False)
2153
2154 output, error = p2.communicate()
2155 result_fds = set(map(int, output.split(b',')))
2156 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2157 p1.stderr.fileno()])
2158
2159 self.assertFalse(result_fds & unwanted_fds,
2160 "Expected no fds from %r to be open in child, "
2161 "found %r" %
2162 (unwanted_fds, result_fds & unwanted_fds))
2163
2164 def test_pipe_cloexec_real_tools(self):
2165 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2166 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2167
2168 subdata = b'zxcvbn'
2169 data = subdata * 4 + b'\n'
2170
2171 p1 = subprocess.Popen([sys.executable, qcat],
2172 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2173 close_fds=False)
2174
2175 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2176 stdin=p1.stdout, stdout=subprocess.PIPE,
2177 close_fds=False)
2178
2179 self.addCleanup(p1.wait)
2180 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002181 def kill_p1():
2182 try:
2183 p1.terminate()
2184 except ProcessLookupError:
2185 pass
2186 def kill_p2():
2187 try:
2188 p2.terminate()
2189 except ProcessLookupError:
2190 pass
2191 self.addCleanup(kill_p1)
2192 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002193
2194 p1.stdin.write(data)
2195 p1.stdin.close()
2196
2197 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2198
2199 self.assertTrue(readfiles, "The child hung")
2200 self.assertEqual(p2.stdout.read(), data)
2201
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002202 p1.stdout.close()
2203 p2.stdout.close()
2204
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002205 def test_close_fds(self):
2206 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2207
2208 fds = os.pipe()
2209 self.addCleanup(os.close, fds[0])
2210 self.addCleanup(os.close, fds[1])
2211
2212 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002213 # add a bunch more fds
2214 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002215 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002216 self.addCleanup(os.close, fd)
2217 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002218
Victor Stinnerdaf45552013-08-28 00:53:59 +02002219 for fd in open_fds:
2220 os.set_inheritable(fd, True)
2221
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002222 p = subprocess.Popen([sys.executable, fd_status],
2223 stdout=subprocess.PIPE, close_fds=False)
2224 output, ignored = p.communicate()
2225 remaining_fds = set(map(int, output.split(b',')))
2226
2227 self.assertEqual(remaining_fds & open_fds, open_fds,
2228 "Some fds were closed")
2229
2230 p = subprocess.Popen([sys.executable, fd_status],
2231 stdout=subprocess.PIPE, close_fds=True)
2232 output, ignored = p.communicate()
2233 remaining_fds = set(map(int, output.split(b',')))
2234
2235 self.assertFalse(remaining_fds & open_fds,
2236 "Some fds were left open")
2237 self.assertIn(1, remaining_fds, "Subprocess failed")
2238
Gregory P. Smith8facece2012-01-21 14:01:08 -08002239 # Keep some of the fd's we opened open in the subprocess.
2240 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2241 fds_to_keep = set(open_fds.pop() for _ in range(8))
2242 p = subprocess.Popen([sys.executable, fd_status],
2243 stdout=subprocess.PIPE, close_fds=True,
2244 pass_fds=())
2245 output, ignored = p.communicate()
2246 remaining_fds = set(map(int, output.split(b',')))
2247
2248 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2249 "Some fds not in pass_fds were left open")
2250 self.assertIn(1, remaining_fds, "Subprocess failed")
2251
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002252
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002253 @unittest.skipIf(sys.platform.startswith("freebsd") and
2254 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2255 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002256 def test_close_fds_when_max_fd_is_lowered(self):
2257 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2258 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2259
Gregory P. Smith634aa682014-06-15 17:51:04 -07002260 # This launches the meat of the test in a child process to
2261 # avoid messing with the larger unittest processes maximum
2262 # number of file descriptors.
2263 # This process launches:
2264 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2265 # a bunch of high open fds above the new lower rlimit.
2266 # Those are reported via stdout before launching a new
2267 # process with close_fds=False to run the actual test:
2268 # +--> The TEST: This one launches a fd_status.py
2269 # subprocess with close_fds=True so we can find out if
2270 # any of the fds above the lowered rlimit are still open.
2271 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2272 '''
2273 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002274 open_fds = set()
2275 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002276 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002277 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002278 open_fds.add(fd)
2279
2280 # Leave a two pairs of low ones available for use by the
2281 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002282 # We also leave 10 more open as some Python buildbots run into
2283 # "too many open files" errors during the test if we do not.
2284 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002285 os.close(fd)
2286 open_fds.remove(fd)
2287
2288 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002289 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002290 os.set_inheritable(fd, True)
2291
2292 max_fd_open = max(open_fds)
2293
Gregory P. Smith634aa682014-06-15 17:51:04 -07002294 # Communicate the open_fds to the parent unittest.TestCase process.
2295 print(','.join(map(str, sorted(open_fds))))
2296 sys.stdout.flush()
2297
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002298 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2299 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002300 # 29 is lower than the highest fds we are leaving open.
2301 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002302 # Launch a new Python interpreter with our low fd rlim_cur that
2303 # inherits open fds above that limit. It then uses subprocess
2304 # with close_fds=True to get a report of open fds in the child.
2305 # An explicit list of fds to check is passed to fd_status.py as
2306 # letting fd_status rely on its default logic would miss the
2307 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002308 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002309 [sys.executable, '-c',
2310 textwrap.dedent("""
2311 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002312 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002313 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002314 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002315 """.format(max_fd=max_fd_open+1))],
2316 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002317 finally:
2318 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002319 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002320
2321 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002322 output_lines = output.splitlines()
2323 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002324 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002325 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2326 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002327
Gregory P. Smith634aa682014-06-15 17:51:04 -07002328 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002329 msg="Some fds were left open.")
2330
2331
Victor Stinner88701e22011-06-01 13:13:04 +02002332 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2333 # descriptor of a pipe closed in the parent process is valid in the
2334 # child process according to fstat(), but the mode of the file
2335 # descriptor is invalid, and read or write raise an error.
2336 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002337 def test_pass_fds(self):
2338 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2339
2340 open_fds = set()
2341
2342 for x in range(5):
2343 fds = os.pipe()
2344 self.addCleanup(os.close, fds[0])
2345 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002346 os.set_inheritable(fds[0], True)
2347 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002348 open_fds.update(fds)
2349
2350 for fd in open_fds:
2351 p = subprocess.Popen([sys.executable, fd_status],
2352 stdout=subprocess.PIPE, close_fds=True,
2353 pass_fds=(fd, ))
2354 output, ignored = p.communicate()
2355
2356 remaining_fds = set(map(int, output.split(b',')))
2357 to_be_closed = open_fds - {fd}
2358
2359 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2360 self.assertFalse(remaining_fds & to_be_closed,
2361 "fd to be closed passed")
2362
2363 # pass_fds overrides close_fds with a warning.
2364 with self.assertWarns(RuntimeWarning) as context:
2365 self.assertFalse(subprocess.call(
2366 [sys.executable, "-c", "import sys; sys.exit(0)"],
2367 close_fds=False, pass_fds=(fd, )))
2368 self.assertIn('overriding close_fds', str(context.warning))
2369
Victor Stinnerdaf45552013-08-28 00:53:59 +02002370 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002371 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002372
2373 inheritable, non_inheritable = os.pipe()
2374 self.addCleanup(os.close, inheritable)
2375 self.addCleanup(os.close, non_inheritable)
2376 os.set_inheritable(inheritable, True)
2377 os.set_inheritable(non_inheritable, False)
2378 pass_fds = (inheritable, non_inheritable)
2379 args = [sys.executable, script]
2380 args += list(map(str, pass_fds))
2381
2382 p = subprocess.Popen(args,
2383 stdout=subprocess.PIPE, close_fds=True,
2384 pass_fds=pass_fds)
2385 output, ignored = p.communicate()
2386 fds = set(map(int, output.split(b',')))
2387
2388 # the inheritable file descriptor must be inherited, so its inheritable
2389 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002390 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002391
2392 # inheritable flag must not be changed in the parent process
2393 self.assertEqual(os.get_inheritable(inheritable), True)
2394 self.assertEqual(os.get_inheritable(non_inheritable), False)
2395
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002396 def test_stdout_stdin_are_single_inout_fd(self):
2397 with io.open(os.devnull, "r+") as inout:
2398 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2399 stdout=inout, stdin=inout)
2400 p.wait()
2401
2402 def test_stdout_stderr_are_single_inout_fd(self):
2403 with io.open(os.devnull, "r+") as inout:
2404 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2405 stdout=inout, stderr=inout)
2406 p.wait()
2407
2408 def test_stderr_stdin_are_single_inout_fd(self):
2409 with io.open(os.devnull, "r+") as inout:
2410 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2411 stderr=inout, stdin=inout)
2412 p.wait()
2413
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002414 def test_wait_when_sigchild_ignored(self):
2415 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2416 sigchild_ignore = support.findfile("sigchild_ignore.py",
2417 subdir="subprocessdata")
2418 p = subprocess.Popen([sys.executable, sigchild_ignore],
2419 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2420 stdout, stderr = p.communicate()
2421 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002422 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002423 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002424
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002425 def test_select_unbuffered(self):
2426 # Issue #11459: bufsize=0 should really set the pipes as
2427 # unbuffered (and therefore let select() work properly).
2428 select = support.import_module("select")
2429 p = subprocess.Popen([sys.executable, "-c",
2430 'import sys;'
2431 'sys.stdout.write("apple")'],
2432 stdout=subprocess.PIPE,
2433 bufsize=0)
2434 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002435 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002436 try:
2437 self.assertEqual(f.read(4), b"appl")
2438 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2439 finally:
2440 p.wait()
2441
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002442 def test_zombie_fast_process_del(self):
2443 # Issue #12650: on Unix, if Popen.__del__() was called before the
2444 # process exited, it wouldn't be added to subprocess._active, and would
2445 # remain a zombie.
2446 # spawn a Popen, and delete its reference before it exits
2447 p = subprocess.Popen([sys.executable, "-c",
2448 'import sys, time;'
2449 'time.sleep(0.2)'],
2450 stdout=subprocess.PIPE,
2451 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002452 self.addCleanup(p.stdout.close)
2453 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002454 ident = id(p)
2455 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002456 with support.check_warnings(('', ResourceWarning)):
2457 p = None
2458
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002459 # check that p is in the active processes list
2460 self.assertIn(ident, [id(o) for o in subprocess._active])
2461
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002462 def test_leak_fast_process_del_killed(self):
2463 # Issue #12650: on Unix, if Popen.__del__() was called before the
2464 # process exited, and the process got killed by a signal, it would never
2465 # be removed from subprocess._active, which triggered a FD and memory
2466 # leak.
2467 # spawn a Popen, delete its reference and kill it
2468 p = subprocess.Popen([sys.executable, "-c",
2469 'import time;'
2470 'time.sleep(3)'],
2471 stdout=subprocess.PIPE,
2472 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002473 self.addCleanup(p.stdout.close)
2474 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002475 ident = id(p)
2476 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002477 with support.check_warnings(('', ResourceWarning)):
2478 p = None
2479
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002480 os.kill(pid, signal.SIGKILL)
2481 # check that p is in the active processes list
2482 self.assertIn(ident, [id(o) for o in subprocess._active])
2483
2484 # let some time for the process to exit, and create a new Popen: this
2485 # should trigger the wait() of p
2486 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002487 with self.assertRaises(OSError) as c:
Victor Stinner9a83f652017-08-21 23:51:31 +02002488 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002489 stdout=subprocess.PIPE,
2490 stderr=subprocess.PIPE) as proc:
2491 pass
2492 # p should have been wait()ed on, and removed from the _active list
2493 self.assertRaises(OSError, os.waitpid, pid, 0)
2494 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2495
Charles-François Natali249cdc32013-08-25 18:24:45 +02002496 def test_close_fds_after_preexec(self):
2497 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2498
2499 # this FD is used as dup2() target by preexec_fn, and should be closed
2500 # in the child process
2501 fd = os.dup(1)
2502 self.addCleanup(os.close, fd)
2503
2504 p = subprocess.Popen([sys.executable, fd_status],
2505 stdout=subprocess.PIPE, close_fds=True,
2506 preexec_fn=lambda: os.dup2(1, fd))
2507 output, ignored = p.communicate()
2508
2509 remaining_fds = set(map(int, output.split(b',')))
2510
2511 self.assertNotIn(fd, remaining_fds)
2512
Victor Stinner8f437aa2014-10-05 17:25:19 +02002513 @support.cpython_only
2514 def test_fork_exec(self):
2515 # Issue #22290: fork_exec() must not crash on memory allocation failure
2516 # or other errors
2517 import _posixsubprocess
2518 gc_enabled = gc.isenabled()
2519 try:
2520 # Use a preexec function and enable the garbage collector
2521 # to force fork_exec() to re-enable the garbage collector
2522 # on error.
2523 func = lambda: None
2524 gc.enable()
2525
Victor Stinner8f437aa2014-10-05 17:25:19 +02002526 for args, exe_list, cwd, env_list in (
2527 (123, [b"exe"], None, [b"env"]),
2528 ([b"arg"], 123, None, [b"env"]),
2529 ([b"arg"], [b"exe"], 123, [b"env"]),
2530 ([b"arg"], [b"exe"], None, 123),
2531 ):
2532 with self.assertRaises(TypeError):
2533 _posixsubprocess.fork_exec(
2534 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002535 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002536 -1, -1, -1, -1,
2537 1, 2, 3, 4,
2538 True, True, func)
2539 finally:
2540 if not gc_enabled:
2541 gc.disable()
2542
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002543 @support.cpython_only
2544 def test_fork_exec_sorted_fd_sanity_check(self):
2545 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2546 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002547 class BadInt:
2548 first = True
2549 def __init__(self, value):
2550 self.value = value
2551 def __int__(self):
2552 if self.first:
2553 self.first = False
2554 return self.value
2555 raise ValueError
2556
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002557 gc_enabled = gc.isenabled()
2558 try:
2559 gc.enable()
2560
2561 for fds_to_keep in (
2562 (-1, 2, 3, 4, 5), # Negative number.
2563 ('str', 4), # Not an int.
2564 (18, 23, 42, 2**63), # Out of range.
2565 (5, 4), # Not sorted.
2566 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002567 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002568 ):
2569 with self.assertRaises(
2570 ValueError,
2571 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2572 _posixsubprocess.fork_exec(
2573 [b"false"], [b"false"],
2574 True, fds_to_keep, None, [b"env"],
2575 -1, -1, -1, -1,
2576 1, 2, 3, 4,
2577 True, True, None)
2578 self.assertIn('fds_to_keep', str(c.exception))
2579 finally:
2580 if not gc_enabled:
2581 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002582
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002583 def test_communicate_BrokenPipeError_stdin_close(self):
2584 # By not setting stdout or stderr or a timeout we force the fast path
2585 # that just calls _stdin_write() internally due to our mock.
2586 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2587 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2588 mock_proc_stdin.close.side_effect = BrokenPipeError
2589 proc.communicate() # Should swallow BrokenPipeError from close.
2590 mock_proc_stdin.close.assert_called_with()
2591
2592 def test_communicate_BrokenPipeError_stdin_write(self):
2593 # By not setting stdout or stderr or a timeout we force the fast path
2594 # that just calls _stdin_write() internally due to our mock.
2595 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2596 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2597 mock_proc_stdin.write.side_effect = BrokenPipeError
2598 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2599 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2600 mock_proc_stdin.close.assert_called_once_with()
2601
2602 def test_communicate_BrokenPipeError_stdin_flush(self):
2603 # Setting stdin and stdout forces the ._communicate() code path.
2604 # python -h exits faster than python -c pass (but spams stdout).
2605 proc = subprocess.Popen([sys.executable, '-h'],
2606 stdin=subprocess.PIPE,
2607 stdout=subprocess.PIPE)
2608 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2609 open(os.devnull, 'wb') as dev_null:
2610 mock_proc_stdin.flush.side_effect = BrokenPipeError
2611 # because _communicate registers a selector using proc.stdin...
2612 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2613 # _communicate() should swallow BrokenPipeError from flush.
2614 proc.communicate(b'stuff')
2615 mock_proc_stdin.flush.assert_called_once_with()
2616
2617 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2618 # Setting stdin and stdout forces the ._communicate() code path.
2619 # python -h exits faster than python -c pass (but spams stdout).
2620 proc = subprocess.Popen([sys.executable, '-h'],
2621 stdin=subprocess.PIPE,
2622 stdout=subprocess.PIPE)
2623 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2624 mock_proc_stdin.close.side_effect = BrokenPipeError
2625 # _communicate() should swallow BrokenPipeError from close.
2626 proc.communicate(timeout=999)
2627 mock_proc_stdin.close.assert_called_once_with()
2628
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002629 @unittest.skipUnless(_testcapi is not None
2630 and hasattr(_testcapi, 'W_STOPCODE'),
2631 'need _testcapi.W_STOPCODE')
2632 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002633 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002634 args = [sys.executable, '-c', 'pass']
2635 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002636
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002637 # Wait until the real process completes to avoid zombie process
2638 pid = proc.pid
2639 pid, status = os.waitpid(pid, 0)
2640 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002641
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002642 status = _testcapi.W_STOPCODE(3)
2643 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
2644 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02002645
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002646 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002647
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002648
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002649@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002650class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002651
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002652 def test_startupinfo(self):
2653 # startupinfo argument
2654 # We uses hardcoded constants, because we do not want to
2655 # depend on win32all.
2656 STARTF_USESHOWWINDOW = 1
2657 SW_MAXIMIZE = 3
2658 startupinfo = subprocess.STARTUPINFO()
2659 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2660 startupinfo.wShowWindow = SW_MAXIMIZE
2661 # Since Python is a console process, it won't be affected
2662 # by wShowWindow, but the argument should be silently
2663 # ignored
2664 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002665 startupinfo=startupinfo)
2666
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302667 def test_startupinfo_keywords(self):
2668 # startupinfo argument
2669 # We use hardcoded constants, because we do not want to
2670 # depend on win32all.
2671 STARTF_USERSHOWWINDOW = 1
2672 SW_MAXIMIZE = 3
2673 startupinfo = subprocess.STARTUPINFO(
2674 dwFlags=STARTF_USERSHOWWINDOW,
2675 wShowWindow=SW_MAXIMIZE
2676 )
2677 # Since Python is a console process, it won't be affected
2678 # by wShowWindow, but the argument should be silently
2679 # ignored
2680 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2681 startupinfo=startupinfo)
2682
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002683 def test_creationflags(self):
2684 # creationflags argument
2685 CREATE_NEW_CONSOLE = 16
2686 sys.stderr.write(" a DOS box should flash briefly ...\n")
2687 subprocess.call(sys.executable +
2688 ' -c "import time; time.sleep(0.25)"',
2689 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002690
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002691 def test_invalid_args(self):
2692 # invalid arguments should raise ValueError
2693 self.assertRaises(ValueError, subprocess.call,
2694 [sys.executable, "-c",
2695 "import sys; sys.exit(47)"],
2696 preexec_fn=lambda: 1)
2697 self.assertRaises(ValueError, subprocess.call,
2698 [sys.executable, "-c",
2699 "import sys; sys.exit(47)"],
2700 stdout=subprocess.PIPE,
2701 close_fds=True)
2702
2703 def test_close_fds(self):
2704 # close file descriptors
2705 rc = subprocess.call([sys.executable, "-c",
2706 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002707 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002708 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002709
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002710 def test_shell_sequence(self):
2711 # Run command through the shell (sequence)
2712 newenv = os.environ.copy()
2713 newenv["FRUIT"] = "physalis"
2714 p = subprocess.Popen(["set"], shell=1,
2715 stdout=subprocess.PIPE,
2716 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002717 with p:
2718 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002719
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002720 def test_shell_string(self):
2721 # Run command through the shell (string)
2722 newenv = os.environ.copy()
2723 newenv["FRUIT"] = "physalis"
2724 p = subprocess.Popen("set", shell=1,
2725 stdout=subprocess.PIPE,
2726 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002727 with p:
2728 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002729
Steve Dower050acae2016-09-06 20:16:17 -07002730 def test_shell_encodings(self):
2731 # Run command through the shell (string)
2732 for enc in ['ansi', 'oem']:
2733 newenv = os.environ.copy()
2734 newenv["FRUIT"] = "physalis"
2735 p = subprocess.Popen("set", shell=1,
2736 stdout=subprocess.PIPE,
2737 env=newenv,
2738 encoding=enc)
2739 with p:
2740 self.assertIn("physalis", p.stdout.read(), enc)
2741
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002742 def test_call_string(self):
2743 # call() function with string argument on Windows
2744 rc = subprocess.call(sys.executable +
2745 ' -c "import sys; sys.exit(47)"')
2746 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002747
Florent Xicluna4886d242010-03-08 13:27:26 +00002748 def _kill_process(self, method, *args):
2749 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002750 p = subprocess.Popen([sys.executable, "-c", """if 1:
2751 import sys, time
2752 sys.stdout.write('x\\n')
2753 sys.stdout.flush()
2754 time.sleep(30)
2755 """],
2756 stdin=subprocess.PIPE,
2757 stdout=subprocess.PIPE,
2758 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002759 with p:
2760 # Wait for the interpreter to be completely initialized before
2761 # sending any signal.
2762 p.stdout.read(1)
2763 getattr(p, method)(*args)
2764 _, stderr = p.communicate()
2765 self.assertStderrEqual(stderr, b'')
2766 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002767 self.assertNotEqual(returncode, 0)
2768
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002769 def _kill_dead_process(self, method, *args):
2770 p = subprocess.Popen([sys.executable, "-c", """if 1:
2771 import sys, time
2772 sys.stdout.write('x\\n')
2773 sys.stdout.flush()
2774 sys.exit(42)
2775 """],
2776 stdin=subprocess.PIPE,
2777 stdout=subprocess.PIPE,
2778 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002779 with p:
2780 # Wait for the interpreter to be completely initialized before
2781 # sending any signal.
2782 p.stdout.read(1)
2783 # The process should end after this
2784 time.sleep(1)
2785 # This shouldn't raise even though the child is now dead
2786 getattr(p, method)(*args)
2787 _, stderr = p.communicate()
2788 self.assertStderrEqual(stderr, b'')
2789 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002790 self.assertEqual(rc, 42)
2791
Florent Xicluna4886d242010-03-08 13:27:26 +00002792 def test_send_signal(self):
2793 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002794
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002795 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002796 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002797
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002798 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002799 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002800
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002801 def test_send_signal_dead(self):
2802 self._kill_dead_process('send_signal', signal.SIGTERM)
2803
2804 def test_kill_dead(self):
2805 self._kill_dead_process('kill')
2806
2807 def test_terminate_dead(self):
2808 self._kill_dead_process('terminate')
2809
Martin Panter23172bd2016-04-16 11:28:10 +00002810class MiscTests(unittest.TestCase):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002811 def test_getoutput(self):
2812 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2813 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2814 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002815
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002816 # we use mkdtemp in the next line to create an empty directory
2817 # under our exclusive control; from that, we can invent a pathname
2818 # that we _know_ won't exist. This is guaranteed to fail.
2819 dir = None
2820 try:
2821 dir = tempfile.mkdtemp()
2822 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002823 status, output = subprocess.getstatusoutput(
2824 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002825 self.assertNotEqual(status, 0)
2826 finally:
2827 if dir is not None:
2828 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002829
Gregory P. Smithace55862015-04-07 15:57:54 -07002830 def test__all__(self):
2831 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00002832 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07002833 exported = set(subprocess.__all__)
2834 possible_exports = set()
2835 import types
2836 for name, value in subprocess.__dict__.items():
2837 if name.startswith('_'):
2838 continue
2839 if isinstance(value, (types.ModuleType,)):
2840 continue
2841 possible_exports.add(name)
2842 self.assertEqual(exported, possible_exports - intentionally_excluded)
2843
2844
Martin Panter23172bd2016-04-16 11:28:10 +00002845@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2846 "Test needs selectors.PollSelector")
2847class ProcessTestCaseNoPoll(ProcessTestCase):
2848 def setUp(self):
2849 self.orig_selector = subprocess._PopenSelector
2850 subprocess._PopenSelector = selectors.SelectSelector
2851 ProcessTestCase.setUp(self)
2852
2853 def tearDown(self):
2854 subprocess._PopenSelector = self.orig_selector
2855 ProcessTestCase.tearDown(self)
2856
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002857
Tim Golden126c2962010-08-11 14:20:40 +00002858@unittest.skipUnless(mswindows, "Windows-specific tests")
2859class CommandsWithSpaces (BaseTestCase):
2860
2861 def setUp(self):
2862 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002863 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002864 self.fname = fname.lower ()
2865 os.write(f, b"import sys;"
2866 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2867 )
2868 os.close(f)
2869
2870 def tearDown(self):
2871 os.remove(self.fname)
2872 super().tearDown()
2873
2874 def with_spaces(self, *args, **kwargs):
2875 kwargs['stdout'] = subprocess.PIPE
2876 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02002877 with p:
2878 self.assertEqual(
2879 p.stdout.read ().decode("mbcs"),
2880 "2 [%r, 'ab cd']" % self.fname
2881 )
Tim Golden126c2962010-08-11 14:20:40 +00002882
2883 def test_shell_string_with_spaces(self):
2884 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002885 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2886 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002887
2888 def test_shell_sequence_with_spaces(self):
2889 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002890 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002891
2892 def test_noshell_string_with_spaces(self):
2893 # call() function with string argument with spaces on Windows
2894 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2895 "ab cd"))
2896
2897 def test_noshell_sequence_with_spaces(self):
2898 # call() function with sequence argument with spaces on Windows
2899 self.with_spaces([sys.executable, self.fname, "ab cd"])
2900
Brian Curtin79cdb662010-12-03 02:46:02 +00002901
Georg Brandla86b2622012-02-20 21:34:57 +01002902class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002903
2904 def test_pipe(self):
2905 with subprocess.Popen([sys.executable, "-c",
2906 "import sys;"
2907 "sys.stdout.write('stdout');"
2908 "sys.stderr.write('stderr');"],
2909 stdout=subprocess.PIPE,
2910 stderr=subprocess.PIPE) as proc:
2911 self.assertEqual(proc.stdout.read(), b"stdout")
2912 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2913
2914 self.assertTrue(proc.stdout.closed)
2915 self.assertTrue(proc.stderr.closed)
2916
2917 def test_returncode(self):
2918 with subprocess.Popen([sys.executable, "-c",
2919 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002920 pass
2921 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002922 self.assertEqual(proc.returncode, 100)
2923
2924 def test_communicate_stdin(self):
2925 with subprocess.Popen([sys.executable, "-c",
2926 "import sys;"
2927 "sys.exit(sys.stdin.read() == 'context')"],
2928 stdin=subprocess.PIPE) as proc:
2929 proc.communicate(b"context")
2930 self.assertEqual(proc.returncode, 1)
2931
2932 def test_invalid_args(self):
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +01002933 with self.assertRaises((FileNotFoundError, PermissionError)) as c:
Victor Stinner9a83f652017-08-21 23:51:31 +02002934 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00002935 stdout=subprocess.PIPE,
2936 stderr=subprocess.PIPE) as proc:
2937 pass
2938
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002939 def test_broken_pipe_cleanup(self):
2940 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002941 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002942 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002943 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002944 proc = proc.__enter__()
2945 # Prepare to send enough data to overflow any OS pipe buffering and
2946 # guarantee a broken pipe error. Data is held in BufferedWriter
2947 # buffer until closed.
2948 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002949 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002950 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002951 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002952 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002953 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002954
Brian Curtin79cdb662010-12-03 02:46:02 +00002955
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002956if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002957 unittest.main()