blob: 7899aebe06268da158f28c4ad5a69d6bd80b86ed [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Chris Jerdonekec3ea942012-09-30 00:10:28 -07002from test import script_helper
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
6import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04007import io
Andrew Svetlov82860712012-08-19 22:13:41 +03008import locale
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Tim Peters3761e8d2004-10-13 04:07:12 +000013import re
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000015import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000016import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040017import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050018import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030019import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050020
21try:
22 import resource
23except ImportError:
24 resource = None
25
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000026mswindows = (sys.platform == "win32")
27
28#
29# Depends on the following external programs: Python
30#
31
32if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000033 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
34 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000035else:
36 SETBINARY = ''
37
Florent Xiclunab1e94e82010-02-27 22:12:37 +000038
39try:
40 mkstemp = tempfile.mkstemp
41except AttributeError:
42 # tempfile.mkstemp is not available
43 def mkstemp():
44 """Replacement for mkstemp, calling mktemp."""
45 fname = tempfile.mktemp()
46 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
47
Tim Peters3761e8d2004-10-13 04:07:12 +000048
Florent Xiclunac049d872010-03-27 22:47:23 +000049class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000050 def setUp(self):
51 # Try to minimize the number of children we have so this test
52 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000053 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000055 def tearDown(self):
56 for inst in subprocess._active:
57 inst.wait()
58 subprocess._cleanup()
59 self.assertFalse(subprocess._active, "subprocess._active not empty")
60
Florent Xiclunab1e94e82010-02-27 22:12:37 +000061 def assertStderrEqual(self, stderr, expected, msg=None):
62 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
63 # shutdown time. That frustrates tests trying to check stderr produced
64 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000065 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040066 # strip_python_stderr also strips whitespace, so we do too.
67 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000068 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069
Florent Xiclunac049d872010-03-27 22:47:23 +000070
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080071class PopenTestException(Exception):
72 pass
73
74
75class PopenExecuteChildRaises(subprocess.Popen):
76 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
77 _execute_child fails.
78 """
79 def _execute_child(self, *args, **kwargs):
80 raise PopenTestException("Forced Exception for Test")
81
82
Florent Xiclunac049d872010-03-27 22:47:23 +000083class ProcessTestCase(BaseTestCase):
84
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070085 def test_io_buffered_by_default(self):
86 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
87 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
88 stderr=subprocess.PIPE)
89 try:
90 self.assertIsInstance(p.stdin, io.BufferedIOBase)
91 self.assertIsInstance(p.stdout, io.BufferedIOBase)
92 self.assertIsInstance(p.stderr, io.BufferedIOBase)
93 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070094 p.stdin.close()
95 p.stdout.close()
96 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070097 p.wait()
98
99 def test_io_unbuffered_works(self):
100 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
101 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
102 stderr=subprocess.PIPE, bufsize=0)
103 try:
104 self.assertIsInstance(p.stdin, io.RawIOBase)
105 self.assertIsInstance(p.stdout, io.RawIOBase)
106 self.assertIsInstance(p.stderr, io.RawIOBase)
107 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700108 p.stdin.close()
109 p.stdout.close()
110 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700111 p.wait()
112
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000113 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000114 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000115 rc = subprocess.call([sys.executable, "-c",
116 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000117 self.assertEqual(rc, 47)
118
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400119 def test_call_timeout(self):
120 # call() function with timeout argument; we want to test that the child
121 # process gets killed when the timeout expires. If the child isn't
122 # killed, this call will deadlock since subprocess.call waits for the
123 # child.
124 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
125 [sys.executable, "-c", "while True: pass"],
126 timeout=0.1)
127
Peter Astrand454f7672005-01-01 09:36:35 +0000128 def test_check_call_zero(self):
129 # check_call() function with zero return code
130 rc = subprocess.check_call([sys.executable, "-c",
131 "import sys; sys.exit(0)"])
132 self.assertEqual(rc, 0)
133
134 def test_check_call_nonzero(self):
135 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000136 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000137 subprocess.check_call([sys.executable, "-c",
138 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000139 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000140
Georg Brandlf9734072008-12-07 15:30:06 +0000141 def test_check_output(self):
142 # check_output() function with zero return code
143 output = subprocess.check_output(
144 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000145 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000146
147 def test_check_output_nonzero(self):
148 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000149 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000150 subprocess.check_output(
151 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000152 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000153
154 def test_check_output_stderr(self):
155 # check_output() function stderr redirected to stdout
156 output = subprocess.check_output(
157 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
158 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000159 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000160
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300161 def test_check_output_stdin_arg(self):
162 # check_output() can be called with stdin set to a file
163 tf = tempfile.TemporaryFile()
164 self.addCleanup(tf.close)
165 tf.write(b'pear')
166 tf.seek(0)
167 output = subprocess.check_output(
168 [sys.executable, "-c",
169 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
170 stdin=tf)
171 self.assertIn(b'PEAR', output)
172
173 def test_check_output_input_arg(self):
174 # check_output() can be called with input set to a string
175 output = subprocess.check_output(
176 [sys.executable, "-c",
177 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
178 input=b'pear')
179 self.assertIn(b'PEAR', output)
180
Georg Brandlf9734072008-12-07 15:30:06 +0000181 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300182 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000183 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000184 output = subprocess.check_output(
185 [sys.executable, "-c", "print('will not be run')"],
186 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000187 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000188 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000189
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300190 def test_check_output_stdin_with_input_arg(self):
191 # check_output() refuses to accept 'stdin' with 'input'
192 tf = tempfile.TemporaryFile()
193 self.addCleanup(tf.close)
194 tf.write(b'pear')
195 tf.seek(0)
196 with self.assertRaises(ValueError) as c:
197 output = subprocess.check_output(
198 [sys.executable, "-c", "print('will not be run')"],
199 stdin=tf, input=b'hare')
200 self.fail("Expected ValueError when stdin and input args supplied.")
201 self.assertIn('stdin', c.exception.args[0])
202 self.assertIn('input', c.exception.args[0])
203
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400204 def test_check_output_timeout(self):
205 # check_output() function with timeout arg
206 with self.assertRaises(subprocess.TimeoutExpired) as c:
207 output = subprocess.check_output(
208 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200209 "import sys, time\n"
210 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400211 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200212 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400213 # Some heavily loaded buildbots (sparc Debian 3.x) require
214 # this much time to start and print.
215 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400216 self.fail("Expected TimeoutExpired.")
217 self.assertEqual(c.exception.output, b'BDFL')
218
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000219 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000220 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000221 newenv = os.environ.copy()
222 newenv["FRUIT"] = "banana"
223 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000224 'import sys, os;'
225 'sys.exit(os.getenv("FRUIT")=="banana")'],
226 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 self.assertEqual(rc, 1)
228
Victor Stinner87b9bc32011-06-01 00:57:47 +0200229 def test_invalid_args(self):
230 # Popen() called with invalid arguments should raise TypeError
231 # but Popen.__del__ should not complain (issue #12085)
232 with support.captured_stderr() as s:
233 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
234 argcount = subprocess.Popen.__init__.__code__.co_argcount
235 too_many_args = [0] * (argcount + 1)
236 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
237 self.assertEqual(s.getvalue(), '')
238
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000240 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000241 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000243 self.addCleanup(p.stdout.close)
244 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 p.wait()
246 self.assertEqual(p.stdin, None)
247
248 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200249 # .stdout is None when not redirected, and the child's stdout will
250 # be inherited from the parent. In order to test this we run a
251 # subprocess in a subprocess:
252 # this_test
253 # \-- subprocess created by this test (parent)
254 # \-- subprocess created by the parent subprocess (child)
255 # The parent doesn't specify stdout, so the child will use the
256 # parent's stdout. This test checks that the message printed by the
257 # child goes to the parent stdout. The parent also checks that the
258 # child's stdout is None. See #11963.
259 code = ('import sys; from subprocess import Popen, PIPE;'
260 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
261 ' stdin=PIPE, stderr=PIPE);'
262 'p.wait(); assert p.stdout is None;')
263 p = subprocess.Popen([sys.executable, "-c", code],
264 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
265 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000266 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200267 out, err = p.communicate()
268 self.assertEqual(p.returncode, 0, err)
269 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270
271 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000272 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000273 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000275 self.addCleanup(p.stdout.close)
276 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000277 p.wait()
278 self.assertEqual(p.stderr, None)
279
Chris Jerdonek776cb192012-10-08 15:56:43 -0700280 def _assert_python(self, pre_args, **kwargs):
281 # We include sys.exit() to prevent the test runner from hanging
282 # whenever python is found.
283 args = pre_args + ["import sys; sys.exit(47)"]
284 p = subprocess.Popen(args, **kwargs)
285 p.wait()
286 self.assertEqual(47, p.returncode)
287
288 def test_executable(self):
289 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700290 #
291 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
292 # determine where its standard library is, so we need the directory
293 # of args[0] to be valid for the Popen() call to Python to succeed.
294 # See also issue #16170 and issue #7774.
295 doesnotexist = os.path.join(os.path.dirname(sys.executable),
296 "doesnotexist")
297 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700298
299 def test_executable_takes_precedence(self):
300 # Check that the executable argument takes precedence over args[0].
301 #
302 # Verify first that the call succeeds without the executable arg.
303 pre_args = [sys.executable, "-c"]
304 self._assert_python(pre_args)
305 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
306 executable="doesnotexist")
307
308 @unittest.skipIf(mswindows, "executable argument replaces shell")
309 def test_executable_replaces_shell(self):
310 # Check that the executable argument replaces the default shell
311 # when shell=True.
312 self._assert_python([], executable=sys.executable, shell=True)
313
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700314 # For use in the test_cwd* tests below.
315 def _normalize_cwd(self, cwd):
316 # Normalize an expected cwd (for Tru64 support).
317 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
318 # strings. See bug #1063571.
319 original_cwd = os.getcwd()
320 os.chdir(cwd)
321 cwd = os.getcwd()
322 os.chdir(original_cwd)
323 return cwd
324
325 # For use in the test_cwd* tests below.
326 def _split_python_path(self):
327 # Return normalized (python_dir, python_base).
328 python_path = os.path.realpath(sys.executable)
329 return os.path.split(python_path)
330
331 # For use in the test_cwd* tests below.
332 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
333 # Invoke Python via Popen, and assert that (1) the call succeeds,
334 # and that (2) the current working directory of the child process
335 # matches *expected_cwd*.
336 p = subprocess.Popen([python_arg, "-c",
337 "import os, sys; "
338 "sys.stdout.write(os.getcwd()); "
339 "sys.exit(47)"],
340 stdout=subprocess.PIPE,
341 **kwargs)
342 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000343 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700344 self.assertEqual(47, p.returncode)
345 normcase = os.path.normcase
346 self.assertEqual(normcase(expected_cwd),
347 normcase(p.stdout.read().decode("utf-8")))
348
349 def test_cwd(self):
350 # Check that cwd changes the cwd for the child process.
351 temp_dir = tempfile.gettempdir()
352 temp_dir = self._normalize_cwd(temp_dir)
353 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
354
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700355 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700356 def test_cwd_with_relative_arg(self):
357 # Check that Popen looks for args[0] relative to cwd if args[0]
358 # is relative.
359 python_dir, python_base = self._split_python_path()
360 rel_python = os.path.join(os.curdir, python_base)
361 with support.temp_cwd() as wrong_dir:
362 # Before calling with the correct cwd, confirm that the call fails
363 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700364 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700365 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700366 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700367 [rel_python], cwd=wrong_dir)
368 python_dir = self._normalize_cwd(python_dir)
369 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
370
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700371 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700372 def test_cwd_with_relative_executable(self):
373 # Check that Popen looks for executable relative to cwd if executable
374 # is relative (and that executable takes precedence over args[0]).
375 python_dir, python_base = self._split_python_path()
376 rel_python = os.path.join(os.curdir, python_base)
377 doesntexist = "somethingyoudonthave"
378 with support.temp_cwd() as wrong_dir:
379 # Before calling with the correct cwd, confirm that the call fails
380 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700381 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700382 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700383 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700384 [doesntexist], executable=rel_python,
385 cwd=wrong_dir)
386 python_dir = self._normalize_cwd(python_dir)
387 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
388 cwd=python_dir)
389
390 def test_cwd_with_absolute_arg(self):
391 # Check that Popen can find the executable when the cwd is wrong
392 # if args[0] is an absolute path.
393 python_dir, python_base = self._split_python_path()
394 abs_python = os.path.join(python_dir, python_base)
395 rel_python = os.path.join(os.curdir, python_base)
396 with script_helper.temp_dir() as wrong_dir:
397 # Before calling with an absolute path, confirm that using a
398 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700399 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700400 [rel_python], cwd=wrong_dir)
401 wrong_dir = self._normalize_cwd(wrong_dir)
402 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
403
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100404 @unittest.skipIf(sys.base_prefix != sys.prefix,
405 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000406 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700407 python_dir, python_base = self._split_python_path()
408 python_dir = self._normalize_cwd(python_dir)
409 self._assert_cwd(python_dir, "somethingyoudonthave",
410 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000411
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100412 @unittest.skipIf(sys.base_prefix != sys.prefix,
413 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000414 @unittest.skipIf(sysconfig.is_python_build(),
415 "need an installed Python. See #7774")
416 def test_executable_without_cwd(self):
417 # For a normal installation, it should work without 'cwd'
418 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700419 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000420
421 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000422 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 p = subprocess.Popen([sys.executable, "-c",
424 'import sys; sys.exit(sys.stdin.read() == "pear")'],
425 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000426 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000427 p.stdin.close()
428 p.wait()
429 self.assertEqual(p.returncode, 1)
430
431 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000432 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000433 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000434 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000436 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000437 os.lseek(d, 0, 0)
438 p = subprocess.Popen([sys.executable, "-c",
439 'import sys; sys.exit(sys.stdin.read() == "pear")'],
440 stdin=d)
441 p.wait()
442 self.assertEqual(p.returncode, 1)
443
444 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000445 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000446 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000447 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000448 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449 tf.seek(0)
450 p = subprocess.Popen([sys.executable, "-c",
451 'import sys; sys.exit(sys.stdin.read() == "pear")'],
452 stdin=tf)
453 p.wait()
454 self.assertEqual(p.returncode, 1)
455
456 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000457 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000458 p = subprocess.Popen([sys.executable, "-c",
459 'import sys; sys.stdout.write("orange")'],
460 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000461 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000462 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463
464 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000465 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000466 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000467 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468 d = tf.fileno()
469 p = subprocess.Popen([sys.executable, "-c",
470 'import sys; sys.stdout.write("orange")'],
471 stdout=d)
472 p.wait()
473 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000474 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000475
476 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000477 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000478 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000479 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000480 p = subprocess.Popen([sys.executable, "-c",
481 'import sys; sys.stdout.write("orange")'],
482 stdout=tf)
483 p.wait()
484 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000485 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000486
487 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000488 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 p = subprocess.Popen([sys.executable, "-c",
490 'import sys; sys.stderr.write("strawberry")'],
491 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000492 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000493 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494
495 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000496 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000497 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000498 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000499 d = tf.fileno()
500 p = subprocess.Popen([sys.executable, "-c",
501 'import sys; sys.stderr.write("strawberry")'],
502 stderr=d)
503 p.wait()
504 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000505 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000506
507 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000508 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000509 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000510 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000511 p = subprocess.Popen([sys.executable, "-c",
512 'import sys; sys.stderr.write("strawberry")'],
513 stderr=tf)
514 p.wait()
515 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000516 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517
518 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000519 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000521 'import sys;'
522 'sys.stdout.write("apple");'
523 'sys.stdout.flush();'
524 'sys.stderr.write("orange")'],
525 stdout=subprocess.PIPE,
526 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000527 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000528 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000529
530 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000531 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000533 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000535 'import sys;'
536 'sys.stdout.write("apple");'
537 'sys.stdout.flush();'
538 'sys.stderr.write("orange")'],
539 stdout=tf,
540 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000541 p.wait()
542 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000543 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000544
Thomas Wouters89f507f2006-12-13 04:49:30 +0000545 def test_stdout_filedes_of_stdout(self):
546 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200547 # To avoid printing the text on stdout, we do something similar to
548 # test_stdout_none (see above). The parent subprocess calls the child
549 # subprocess passing stdout=1, and this test uses stdout=PIPE in
550 # order to capture and check the output of the parent. See #11963.
551 code = ('import sys, subprocess; '
552 'rc = subprocess.call([sys.executable, "-c", '
553 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
554 'b\'test with stdout=1\'))"], stdout=1); '
555 'assert rc == 18')
556 p = subprocess.Popen([sys.executable, "-c", code],
557 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
558 self.addCleanup(p.stdout.close)
559 self.addCleanup(p.stderr.close)
560 out, err = p.communicate()
561 self.assertEqual(p.returncode, 0, err)
562 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000563
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200564 def test_stdout_devnull(self):
565 p = subprocess.Popen([sys.executable, "-c",
566 'for i in range(10240):'
567 'print("x" * 1024)'],
568 stdout=subprocess.DEVNULL)
569 p.wait()
570 self.assertEqual(p.stdout, None)
571
572 def test_stderr_devnull(self):
573 p = subprocess.Popen([sys.executable, "-c",
574 'import sys\n'
575 'for i in range(10240):'
576 'sys.stderr.write("x" * 1024)'],
577 stderr=subprocess.DEVNULL)
578 p.wait()
579 self.assertEqual(p.stderr, None)
580
581 def test_stdin_devnull(self):
582 p = subprocess.Popen([sys.executable, "-c",
583 'import sys;'
584 'sys.stdin.read(1)'],
585 stdin=subprocess.DEVNULL)
586 p.wait()
587 self.assertEqual(p.stdin, None)
588
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000590 newenv = os.environ.copy()
591 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200592 with subprocess.Popen([sys.executable, "-c",
593 'import sys,os;'
594 'sys.stdout.write(os.getenv("FRUIT"))'],
595 stdout=subprocess.PIPE,
596 env=newenv) as p:
597 stdout, stderr = p.communicate()
598 self.assertEqual(stdout, b"orange")
599
Victor Stinner62d51182011-06-23 01:02:25 +0200600 # Windows requires at least the SYSTEMROOT environment variable to start
601 # Python
602 @unittest.skipIf(sys.platform == 'win32',
603 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200604 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200605 'the python library cannot be loaded '
606 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200607 def test_empty_env(self):
608 with subprocess.Popen([sys.executable, "-c",
609 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200610 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200611 stdout=subprocess.PIPE,
612 env={}) as p:
613 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200614 self.assertIn(stdout.strip(),
615 (b"[]",
616 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
617 # environment
618 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619
Peter Astrandcbac93c2005-03-03 20:24:28 +0000620 def test_communicate_stdin(self):
621 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000622 'import sys;'
623 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000624 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000625 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000626 self.assertEqual(p.returncode, 1)
627
628 def test_communicate_stdout(self):
629 p = subprocess.Popen([sys.executable, "-c",
630 'import sys; sys.stdout.write("pineapple")'],
631 stdout=subprocess.PIPE)
632 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000633 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000634 self.assertEqual(stderr, None)
635
636 def test_communicate_stderr(self):
637 p = subprocess.Popen([sys.executable, "-c",
638 'import sys; sys.stderr.write("pineapple")'],
639 stderr=subprocess.PIPE)
640 (stdout, stderr) = p.communicate()
641 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000642 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000643
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000644 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000645 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000646 'import sys,os;'
647 'sys.stderr.write("pineapple");'
648 'sys.stdout.write(sys.stdin.read())'],
649 stdin=subprocess.PIPE,
650 stdout=subprocess.PIPE,
651 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000652 self.addCleanup(p.stdout.close)
653 self.addCleanup(p.stderr.close)
654 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000655 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000656 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000657 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000658
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400659 def test_communicate_timeout(self):
660 p = subprocess.Popen([sys.executable, "-c",
661 'import sys,os,time;'
662 'sys.stderr.write("pineapple\\n");'
663 'time.sleep(1);'
664 'sys.stderr.write("pear\\n");'
665 'sys.stdout.write(sys.stdin.read())'],
666 universal_newlines=True,
667 stdin=subprocess.PIPE,
668 stdout=subprocess.PIPE,
669 stderr=subprocess.PIPE)
670 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
671 timeout=0.3)
672 # Make sure we can keep waiting for it, and that we get the whole output
673 # after it completes.
674 (stdout, stderr) = p.communicate()
675 self.assertEqual(stdout, "banana")
676 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
677
678 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200679 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400680 p = subprocess.Popen([sys.executable, "-c",
681 'import sys,os,time;'
682 'sys.stdout.write("a" * (64 * 1024));'
683 'time.sleep(0.2);'
684 'sys.stdout.write("a" * (64 * 1024));'
685 'time.sleep(0.2);'
686 'sys.stdout.write("a" * (64 * 1024));'
687 'time.sleep(0.2);'
688 'sys.stdout.write("a" * (64 * 1024));'],
689 stdout=subprocess.PIPE)
690 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
691 (stdout, _) = p.communicate()
692 self.assertEqual(len(stdout), 4 * 64 * 1024)
693
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000694 # Test for the fd leak reported in http://bugs.python.org/issue2791.
695 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000696 for stdin_pipe in (False, True):
697 for stdout_pipe in (False, True):
698 for stderr_pipe in (False, True):
699 options = {}
700 if stdin_pipe:
701 options['stdin'] = subprocess.PIPE
702 if stdout_pipe:
703 options['stdout'] = subprocess.PIPE
704 if stderr_pipe:
705 options['stderr'] = subprocess.PIPE
706 if not options:
707 continue
708 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
709 p.communicate()
710 if p.stdin is not None:
711 self.assertTrue(p.stdin.closed)
712 if p.stdout is not None:
713 self.assertTrue(p.stdout.closed)
714 if p.stderr is not None:
715 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000716
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000717 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000718 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000719 p = subprocess.Popen([sys.executable, "-c",
720 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000721 (stdout, stderr) = p.communicate()
722 self.assertEqual(stdout, None)
723 self.assertEqual(stderr, None)
724
725 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000726 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000727 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000728 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000729 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730 os.close(x)
731 os.close(y)
732 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000733 'import sys,os;'
734 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200735 'sys.stderr.write("x" * %d);'
736 'sys.stdout.write(sys.stdin.read())' %
737 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000738 stdin=subprocess.PIPE,
739 stdout=subprocess.PIPE,
740 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000741 self.addCleanup(p.stdout.close)
742 self.addCleanup(p.stderr.close)
743 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200744 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000745 (stdout, stderr) = p.communicate(string_to_write)
746 self.assertEqual(stdout, string_to_write)
747
748 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000749 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000750 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000751 'import sys,os;'
752 'sys.stdout.write(sys.stdin.read())'],
753 stdin=subprocess.PIPE,
754 stdout=subprocess.PIPE,
755 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000756 self.addCleanup(p.stdout.close)
757 self.addCleanup(p.stderr.close)
758 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000759 p.stdin.write(b"banana")
760 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000761 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000762 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000763
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000765 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000766 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200767 'buf = sys.stdout.buffer;'
768 'buf.write(sys.stdin.readline().encode());'
769 'buf.flush();'
770 'buf.write(b"line2\\n");'
771 'buf.flush();'
772 'buf.write(sys.stdin.read().encode());'
773 'buf.flush();'
774 'buf.write(b"line4\\n");'
775 'buf.flush();'
776 'buf.write(b"line5\\r\\n");'
777 'buf.flush();'
778 'buf.write(b"line6\\r");'
779 'buf.flush();'
780 'buf.write(b"\\nline7");'
781 'buf.flush();'
782 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200783 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000784 stdout=subprocess.PIPE,
785 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200786 p.stdin.write("line1\n")
787 self.assertEqual(p.stdout.readline(), "line1\n")
788 p.stdin.write("line3\n")
789 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000790 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200791 self.assertEqual(p.stdout.readline(),
792 "line2\n")
793 self.assertEqual(p.stdout.read(6),
794 "line3\n")
795 self.assertEqual(p.stdout.read(),
796 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000797
798 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000799 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000800 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000801 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200802 'buf = sys.stdout.buffer;'
803 'buf.write(b"line2\\n");'
804 'buf.flush();'
805 'buf.write(b"line4\\n");'
806 'buf.flush();'
807 'buf.write(b"line5\\r\\n");'
808 'buf.flush();'
809 'buf.write(b"line6\\r");'
810 'buf.flush();'
811 'buf.write(b"\\nline7");'
812 'buf.flush();'
813 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200814 stderr=subprocess.PIPE,
815 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000816 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000817 self.addCleanup(p.stdout.close)
818 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000819 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200820 self.assertEqual(stdout,
821 "line2\nline4\nline5\nline6\nline7\nline8")
822
823 def test_universal_newlines_communicate_stdin(self):
824 # universal newlines through communicate(), with only stdin
825 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300826 'import sys,os;' + SETBINARY + textwrap.dedent('''
827 s = sys.stdin.readline()
828 assert s == "line1\\n", repr(s)
829 s = sys.stdin.read()
830 assert s == "line3\\n", repr(s)
831 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200832 stdin=subprocess.PIPE,
833 universal_newlines=1)
834 (stdout, stderr) = p.communicate("line1\nline3\n")
835 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000836
Andrew Svetlovf3765072012-08-14 18:35:17 +0300837 def test_universal_newlines_communicate_input_none(self):
838 # Test communicate(input=None) with universal newlines.
839 #
840 # We set stdout to PIPE because, as of this writing, a different
841 # code path is tested when the number of pipes is zero or one.
842 p = subprocess.Popen([sys.executable, "-c", "pass"],
843 stdin=subprocess.PIPE,
844 stdout=subprocess.PIPE,
845 universal_newlines=True)
846 p.communicate()
847 self.assertEqual(p.returncode, 0)
848
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300849 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300850 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300851 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300852 'import sys,os;' + SETBINARY + textwrap.dedent('''
853 s = sys.stdin.buffer.readline()
854 sys.stdout.buffer.write(s)
855 sys.stdout.buffer.write(b"line2\\r")
856 sys.stderr.buffer.write(b"eline2\\n")
857 s = sys.stdin.buffer.read()
858 sys.stdout.buffer.write(s)
859 sys.stdout.buffer.write(b"line4\\n")
860 sys.stdout.buffer.write(b"line5\\r\\n")
861 sys.stderr.buffer.write(b"eline6\\r")
862 sys.stderr.buffer.write(b"eline7\\r\\nz")
863 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300864 stdin=subprocess.PIPE,
865 stderr=subprocess.PIPE,
866 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300867 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300868 self.addCleanup(p.stdout.close)
869 self.addCleanup(p.stderr.close)
870 (stdout, stderr) = p.communicate("line1\nline3\n")
871 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300872 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300873 # Python debug build push something like "[42442 refs]\n"
874 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300875 # Don't use assertStderrEqual because it strips CR and LF from output.
876 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300877
Andrew Svetlov82860712012-08-19 22:13:41 +0300878 def test_universal_newlines_communicate_encodings(self):
879 # Check that universal newlines mode works for various encodings,
880 # in particular for encodings in the UTF-16 and UTF-32 families.
881 # See issue #15595.
882 #
883 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
884 # without, and UTF-16 and UTF-32.
885 for encoding in ['utf-16', 'utf-32-be']:
886 old_getpreferredencoding = locale.getpreferredencoding
887 # Indirectly via io.TextIOWrapper, Popen() defaults to
888 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
889 # locale.getpreferredencoding().
890 def getpreferredencoding(do_setlocale=True):
891 return encoding
892 code = ("import sys; "
893 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
894 encoding)
895 args = [sys.executable, '-c', code]
896 try:
897 locale.getpreferredencoding = getpreferredencoding
898 # We set stdin to be non-None because, as of this writing,
899 # a different code path is used when the number of pipes is
900 # zero or one.
901 popen = subprocess.Popen(args, universal_newlines=True,
902 stdin=subprocess.PIPE,
903 stdout=subprocess.PIPE)
904 stdout, stderr = popen.communicate(input='')
905 finally:
906 locale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300907 self.assertEqual(stdout, '1\n2\n3\n4')
908
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000909 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000910 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000911 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000912 max_handles = 1026 # too much for most UNIX systems
913 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000914 max_handles = 2050 # too much for (at least some) Windows setups
915 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400916 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000917 try:
918 for i in range(max_handles):
919 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400920 tmpfile = os.path.join(tmpdir, support.TESTFN)
921 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000922 except OSError as e:
923 if e.errno != errno.EMFILE:
924 raise
925 break
926 else:
927 self.skipTest("failed to reach the file descriptor limit "
928 "(tried %d)" % max_handles)
929 # Close a couple of them (should be enough for a subprocess)
930 for i in range(10):
931 os.close(handles.pop())
932 # Loop creating some subprocesses. If one of them leaks some fds,
933 # the next loop iteration will fail by reaching the max fd limit.
934 for i in range(15):
935 p = subprocess.Popen([sys.executable, "-c",
936 "import sys;"
937 "sys.stdout.write(sys.stdin.read())"],
938 stdin=subprocess.PIPE,
939 stdout=subprocess.PIPE,
940 stderr=subprocess.PIPE)
941 data = p.communicate(b"lime")[0]
942 self.assertEqual(data, b"lime")
943 finally:
944 for h in handles:
945 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400946 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000947
948 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000949 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
950 '"a b c" d e')
951 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
952 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000953 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
954 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000955 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
956 'a\\\\\\b "de fg" h')
957 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
958 'a\\\\\\"b c d')
959 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
960 '"a\\\\b c" d e')
961 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
962 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000963 self.assertEqual(subprocess.list2cmdline(['ab', '']),
964 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000965
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000966 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200967 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200968 "import os; os.read(0, 1)"],
969 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200970 self.addCleanup(p.stdin.close)
971 self.assertIsNone(p.poll())
972 os.write(p.stdin.fileno(), b'A')
973 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000974 # Subsequent invocations should just return the returncode
975 self.assertEqual(p.poll(), 0)
976
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000977 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200978 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000979 self.assertEqual(p.wait(), 0)
980 # Subsequent invocations should just return the returncode
981 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000982
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400983 def test_wait_timeout(self):
984 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200985 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400986 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200987 p.wait(timeout=0.0001)
988 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400989 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
990 # time to start.
991 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400992
Peter Astrand738131d2004-11-30 21:04:45 +0000993 def test_invalid_bufsize(self):
994 # an invalid type of the bufsize argument should raise
995 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000996 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000997 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000998
Guido van Rossum46a05a72007-06-07 21:56:45 +0000999 def test_bufsize_is_none(self):
1000 # bufsize=None should be the same as bufsize=0.
1001 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1002 self.assertEqual(p.wait(), 0)
1003 # Again with keyword arg
1004 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1005 self.assertEqual(p.wait(), 0)
1006
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001007 def test_leaking_fds_on_error(self):
1008 # see bug #5179: Popen leaks file descriptors to PIPEs if
1009 # the child fails to execute; this will eventually exhaust
1010 # the maximum number of open fds. 1024 seems a very common
1011 # value for that limit, but Windows has 2048, so we loop
1012 # 1024 times (each call leaked two fds).
1013 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001014 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001015 subprocess.Popen(['nonexisting_i_hope'],
1016 stdout=subprocess.PIPE,
1017 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001018 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001019 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001020 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001021
Victor Stinnerb3693582010-05-21 20:13:12 +00001022 def test_issue8780(self):
1023 # Ensure that stdout is inherited from the parent
1024 # if stdout=PIPE is not used
1025 code = ';'.join((
1026 'import subprocess, sys',
1027 'retcode = subprocess.call('
1028 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1029 'assert retcode == 0'))
1030 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001031 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001032
Tim Goldenaf5ac392010-08-06 13:03:56 +00001033 def test_handles_closed_on_exception(self):
1034 # If CreateProcess exits with an error, ensure the
1035 # duplicate output handles are released
1036 ifhandle, ifname = mkstemp()
1037 ofhandle, ofname = mkstemp()
1038 efhandle, efname = mkstemp()
1039 try:
1040 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1041 stderr=efhandle)
1042 except OSError:
1043 os.close(ifhandle)
1044 os.remove(ifname)
1045 os.close(ofhandle)
1046 os.remove(ofname)
1047 os.close(efhandle)
1048 os.remove(efname)
1049 self.assertFalse(os.path.exists(ifname))
1050 self.assertFalse(os.path.exists(ofname))
1051 self.assertFalse(os.path.exists(efname))
1052
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001053 def test_communicate_epipe(self):
1054 # Issue 10963: communicate() should hide EPIPE
1055 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1056 stdin=subprocess.PIPE,
1057 stdout=subprocess.PIPE,
1058 stderr=subprocess.PIPE)
1059 self.addCleanup(p.stdout.close)
1060 self.addCleanup(p.stderr.close)
1061 self.addCleanup(p.stdin.close)
1062 p.communicate(b"x" * 2**20)
1063
1064 def test_communicate_epipe_only_stdin(self):
1065 # Issue 10963: communicate() should hide EPIPE
1066 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1067 stdin=subprocess.PIPE)
1068 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001069 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001070 p.communicate(b"x" * 2**20)
1071
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001072 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1073 "Requires signal.SIGUSR1")
1074 @unittest.skipUnless(hasattr(os, 'kill'),
1075 "Requires os.kill")
1076 @unittest.skipUnless(hasattr(os, 'getppid'),
1077 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001078 def test_communicate_eintr(self):
1079 # Issue #12493: communicate() should handle EINTR
1080 def handler(signum, frame):
1081 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001082 old_handler = signal.signal(signal.SIGUSR1, handler)
1083 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001084
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001085 args = [sys.executable, "-c",
1086 'import os, signal;'
1087 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001088 for stream in ('stdout', 'stderr'):
1089 kw = {stream: subprocess.PIPE}
1090 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001091 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001092 process.communicate()
1093
Tim Peterse718f612004-10-12 21:51:32 +00001094
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001095 # This test is Linux-ish specific for simplicity to at least have
1096 # some coverage. It is not a platform specific bug.
1097 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1098 "Linux specific")
1099 def test_failed_child_execute_fd_leak(self):
1100 """Test for the fork() failure fd leak reported in issue16327."""
1101 fd_directory = '/proc/%d/fd' % os.getpid()
1102 fds_before_popen = os.listdir(fd_directory)
1103 with self.assertRaises(PopenTestException):
1104 PopenExecuteChildRaises(
1105 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1106 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1107
1108 # NOTE: This test doesn't verify that the real _execute_child
1109 # does not close the file descriptors itself on the way out
1110 # during an exception. Code inspection has confirmed that.
1111
1112 fds_after_exception = os.listdir(fd_directory)
1113 self.assertEqual(fds_before_popen, fds_after_exception)
1114
1115
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001116# context manager
1117class _SuppressCoreFiles(object):
1118 """Try to prevent core files from being created."""
1119 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001120
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001121 def __enter__(self):
1122 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -05001123 if resource is not None:
1124 try:
1125 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
1126 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
1127 except (ValueError, resource.error):
1128 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001129
Ronald Oussoren102d11a2010-07-23 09:50:05 +00001130 if sys.platform == 'darwin':
1131 # Check if the 'Crash Reporter' on OSX was configured
1132 # in 'Developer' mode and warn that it will get triggered
1133 # when it is.
1134 #
1135 # This assumes that this context manager is used in tests
1136 # that might trigger the next manager.
1137 value = subprocess.Popen(['/usr/bin/defaults', 'read',
1138 'com.apple.CrashReporter', 'DialogType'],
1139 stdout=subprocess.PIPE).communicate()[0]
1140 if value.strip() == b'developer':
1141 print("this tests triggers the Crash Reporter, "
1142 "that is intentional", end='')
1143 sys.stdout.flush()
1144
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001145 def __exit__(self, *args):
1146 """Return core file behavior to default."""
1147 if self.old_limit is None:
1148 return
Benjamin Peterson964561b2011-12-10 12:31:42 -05001149 if resource is not None:
1150 try:
1151 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
1152 except (ValueError, resource.error):
1153 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001154
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001155
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001156@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001157class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001158
Gregory P. Smith5591b022012-10-10 03:34:47 -07001159 def setUp(self):
1160 super().setUp()
1161 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1162
1163 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001164 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001165 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001166 except OSError as e:
1167 # This avoids hard coding the errno value or the OS perror()
1168 # string and instead capture the exception that we want to see
1169 # below for comparison.
1170 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001171 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001172 else:
1173 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001174 self._nonexistent_dir)
1175 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001176
Gregory P. Smith5591b022012-10-10 03:34:47 -07001177 def test_exception_cwd(self):
1178 """Test error in the child raised in the parent for a bad cwd."""
1179 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001180 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001181 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001182 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001183 except OSError as e:
1184 # Test that the child process chdir failure actually makes
1185 # it up to the parent process as the correct exception.
1186 self.assertEqual(desired_exception.errno, e.errno)
1187 self.assertEqual(desired_exception.strerror, e.strerror)
1188 else:
1189 self.fail("Expected OSError: %s" % desired_exception)
1190
Gregory P. Smith5591b022012-10-10 03:34:47 -07001191 def test_exception_bad_executable(self):
1192 """Test error in the child raised in the parent for a bad executable."""
1193 desired_exception = self._get_chdir_exception()
1194 try:
1195 p = subprocess.Popen([sys.executable, "-c", ""],
1196 executable=self._nonexistent_dir)
1197 except OSError as e:
1198 # Test that the child process exec failure actually makes
1199 # it up to the parent process as the correct exception.
1200 self.assertEqual(desired_exception.errno, e.errno)
1201 self.assertEqual(desired_exception.strerror, e.strerror)
1202 else:
1203 self.fail("Expected OSError: %s" % desired_exception)
1204
1205 def test_exception_bad_args_0(self):
1206 """Test error in the child raised in the parent for a bad args[0]."""
1207 desired_exception = self._get_chdir_exception()
1208 try:
1209 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1210 except OSError as e:
1211 # Test that the child process exec failure actually makes
1212 # it up to the parent process as the correct exception.
1213 self.assertEqual(desired_exception.errno, e.errno)
1214 self.assertEqual(desired_exception.strerror, e.strerror)
1215 else:
1216 self.fail("Expected OSError: %s" % desired_exception)
1217
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001218 def test_restore_signals(self):
1219 # Code coverage for both values of restore_signals to make sure it
1220 # at least does not blow up.
1221 # A test for behavior would be complex. Contributions welcome.
1222 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1223 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1224
1225 def test_start_new_session(self):
1226 # For code coverage of calling setsid(). We don't care if we get an
1227 # EPERM error from it depending on the test execution environment, that
1228 # still indicates that it was called.
1229 try:
1230 output = subprocess.check_output(
1231 [sys.executable, "-c",
1232 "import os; print(os.getpgid(os.getpid()))"],
1233 start_new_session=True)
1234 except OSError as e:
1235 if e.errno != errno.EPERM:
1236 raise
1237 else:
1238 parent_pgid = os.getpgid(os.getpid())
1239 child_pgid = int(output)
1240 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001241
1242 def test_run_abort(self):
1243 # returncode handles signal termination
1244 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001245 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001246 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001247 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001248 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001249
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001250 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001251 # DISCLAIMER: Setting environment variables is *not* a good use
1252 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001253 p = subprocess.Popen([sys.executable, "-c",
1254 'import sys,os;'
1255 'sys.stdout.write(os.getenv("FRUIT"))'],
1256 stdout=subprocess.PIPE,
1257 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001258 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001259 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001260
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001261 def test_preexec_exception(self):
1262 def raise_it():
1263 raise ValueError("What if two swallows carried a coconut?")
1264 try:
1265 p = subprocess.Popen([sys.executable, "-c", ""],
1266 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001267 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001268 self.assertTrue(
1269 subprocess._posixsubprocess,
1270 "Expected a ValueError from the preexec_fn")
1271 except ValueError as e:
1272 self.assertIn("coconut", e.args[0])
1273 else:
1274 self.fail("Exception raised by preexec_fn did not make it "
1275 "to the parent process.")
1276
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001277 class _TestExecuteChildPopen(subprocess.Popen):
1278 """Used to test behavior at the end of _execute_child."""
1279 def __init__(self, testcase, *args, **kwargs):
1280 self._testcase = testcase
1281 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001282
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001283 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001284 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001285 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001286 finally:
1287 # Open a bunch of file descriptors and verify that
1288 # none of them are the same as the ones the Popen
1289 # instance is using for stdin/stdout/stderr.
1290 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1291 for _ in range(8)]
1292 try:
1293 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001294 self._testcase.assertNotIn(
1295 fd, (self.stdin.fileno(), self.stdout.fileno(),
1296 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001297 msg="At least one fd was closed early.")
1298 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001299 for fd in devzero_fds:
1300 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001301
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001302 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1303 def test_preexec_errpipe_does_not_double_close_pipes(self):
1304 """Issue16140: Don't double close pipes on preexec error."""
1305
1306 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001307 raise subprocess.SubprocessError(
1308 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001309
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001310 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001311 self._TestExecuteChildPopen(
1312 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001313 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1314 stderr=subprocess.PIPE, preexec_fn=raise_it)
1315
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001316 def test_preexec_gc_module_failure(self):
1317 # This tests the code that disables garbage collection if the child
1318 # process will execute any Python.
1319 def raise_runtime_error():
1320 raise RuntimeError("this shouldn't escape")
1321 enabled = gc.isenabled()
1322 orig_gc_disable = gc.disable
1323 orig_gc_isenabled = gc.isenabled
1324 try:
1325 gc.disable()
1326 self.assertFalse(gc.isenabled())
1327 subprocess.call([sys.executable, '-c', ''],
1328 preexec_fn=lambda: None)
1329 self.assertFalse(gc.isenabled(),
1330 "Popen enabled gc when it shouldn't.")
1331
1332 gc.enable()
1333 self.assertTrue(gc.isenabled())
1334 subprocess.call([sys.executable, '-c', ''],
1335 preexec_fn=lambda: None)
1336 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1337
1338 gc.disable = raise_runtime_error
1339 self.assertRaises(RuntimeError, subprocess.Popen,
1340 [sys.executable, '-c', ''],
1341 preexec_fn=lambda: None)
1342
1343 del gc.isenabled # force an AttributeError
1344 self.assertRaises(AttributeError, subprocess.Popen,
1345 [sys.executable, '-c', ''],
1346 preexec_fn=lambda: None)
1347 finally:
1348 gc.disable = orig_gc_disable
1349 gc.isenabled = orig_gc_isenabled
1350 if not enabled:
1351 gc.disable()
1352
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001353 def test_args_string(self):
1354 # args is a string
1355 fd, fname = mkstemp()
1356 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001357 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001358 fobj.write("#!/bin/sh\n")
1359 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1360 sys.executable)
1361 os.chmod(fname, 0o700)
1362 p = subprocess.Popen(fname)
1363 p.wait()
1364 os.remove(fname)
1365 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001366
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001367 def test_invalid_args(self):
1368 # invalid arguments should raise ValueError
1369 self.assertRaises(ValueError, subprocess.call,
1370 [sys.executable, "-c",
1371 "import sys; sys.exit(47)"],
1372 startupinfo=47)
1373 self.assertRaises(ValueError, subprocess.call,
1374 [sys.executable, "-c",
1375 "import sys; sys.exit(47)"],
1376 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001377
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001378 def test_shell_sequence(self):
1379 # Run command through the shell (sequence)
1380 newenv = os.environ.copy()
1381 newenv["FRUIT"] = "apple"
1382 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1383 stdout=subprocess.PIPE,
1384 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001385 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001386 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001387
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001388 def test_shell_string(self):
1389 # Run command through the shell (string)
1390 newenv = os.environ.copy()
1391 newenv["FRUIT"] = "apple"
1392 p = subprocess.Popen("echo $FRUIT", shell=1,
1393 stdout=subprocess.PIPE,
1394 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001395 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001396 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001397
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001398 def test_call_string(self):
1399 # call() function with string argument on UNIX
1400 fd, fname = mkstemp()
1401 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001402 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001403 fobj.write("#!/bin/sh\n")
1404 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1405 sys.executable)
1406 os.chmod(fname, 0o700)
1407 rc = subprocess.call(fname)
1408 os.remove(fname)
1409 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001410
Stefan Krah9542cc62010-07-19 14:20:53 +00001411 def test_specific_shell(self):
1412 # Issue #9265: Incorrect name passed as arg[0].
1413 shells = []
1414 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1415 for name in ['bash', 'ksh']:
1416 sh = os.path.join(prefix, name)
1417 if os.path.isfile(sh):
1418 shells.append(sh)
1419 if not shells: # Will probably work for any shell but csh.
1420 self.skipTest("bash or ksh required for this test")
1421 sh = '/bin/sh'
1422 if os.path.isfile(sh) and not os.path.islink(sh):
1423 # Test will fail if /bin/sh is a symlink to csh.
1424 shells.append(sh)
1425 for sh in shells:
1426 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1427 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001428 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001429 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1430
Florent Xicluna4886d242010-03-08 13:27:26 +00001431 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001432 # Do not inherit file handles from the parent.
1433 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001434 p = subprocess.Popen([sys.executable, "-c", """if 1:
1435 import sys, time
1436 sys.stdout.write('x\\n')
1437 sys.stdout.flush()
1438 time.sleep(30)
1439 """],
1440 close_fds=True,
1441 stdin=subprocess.PIPE,
1442 stdout=subprocess.PIPE,
1443 stderr=subprocess.PIPE)
1444 # Wait for the interpreter to be completely initialized before
1445 # sending any signal.
1446 p.stdout.read(1)
1447 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001448 return p
1449
Charles-François Natali53221e32013-01-12 16:52:20 +01001450 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1451 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001452 def _kill_dead_process(self, method, *args):
1453 # Do not inherit file handles from the parent.
1454 # It should fix failures on some platforms.
1455 p = subprocess.Popen([sys.executable, "-c", """if 1:
1456 import sys, time
1457 sys.stdout.write('x\\n')
1458 sys.stdout.flush()
1459 """],
1460 close_fds=True,
1461 stdin=subprocess.PIPE,
1462 stdout=subprocess.PIPE,
1463 stderr=subprocess.PIPE)
1464 # Wait for the interpreter to be completely initialized before
1465 # sending any signal.
1466 p.stdout.read(1)
1467 # The process should end after this
1468 time.sleep(1)
1469 # This shouldn't raise even though the child is now dead
1470 getattr(p, method)(*args)
1471 p.communicate()
1472
Florent Xicluna4886d242010-03-08 13:27:26 +00001473 def test_send_signal(self):
1474 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001475 _, stderr = p.communicate()
1476 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001477 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001478
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001479 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001480 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001481 _, stderr = p.communicate()
1482 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001483 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001484
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001485 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001486 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001487 _, stderr = p.communicate()
1488 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001489 self.assertEqual(p.wait(), -signal.SIGTERM)
1490
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001491 def test_send_signal_dead(self):
1492 # Sending a signal to a dead process
1493 self._kill_dead_process('send_signal', signal.SIGINT)
1494
1495 def test_kill_dead(self):
1496 # Killing a dead process
1497 self._kill_dead_process('kill')
1498
1499 def test_terminate_dead(self):
1500 # Terminating a dead process
1501 self._kill_dead_process('terminate')
1502
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001503 def check_close_std_fds(self, fds):
1504 # Issue #9905: test that subprocess pipes still work properly with
1505 # some standard fds closed
1506 stdin = 0
1507 newfds = []
1508 for a in fds:
1509 b = os.dup(a)
1510 newfds.append(b)
1511 if a == 0:
1512 stdin = b
1513 try:
1514 for fd in fds:
1515 os.close(fd)
1516 out, err = subprocess.Popen([sys.executable, "-c",
1517 'import sys;'
1518 'sys.stdout.write("apple");'
1519 'sys.stdout.flush();'
1520 'sys.stderr.write("orange")'],
1521 stdin=stdin,
1522 stdout=subprocess.PIPE,
1523 stderr=subprocess.PIPE).communicate()
1524 err = support.strip_python_stderr(err)
1525 self.assertEqual((out, err), (b'apple', b'orange'))
1526 finally:
1527 for b, a in zip(newfds, fds):
1528 os.dup2(b, a)
1529 for b in newfds:
1530 os.close(b)
1531
1532 def test_close_fd_0(self):
1533 self.check_close_std_fds([0])
1534
1535 def test_close_fd_1(self):
1536 self.check_close_std_fds([1])
1537
1538 def test_close_fd_2(self):
1539 self.check_close_std_fds([2])
1540
1541 def test_close_fds_0_1(self):
1542 self.check_close_std_fds([0, 1])
1543
1544 def test_close_fds_0_2(self):
1545 self.check_close_std_fds([0, 2])
1546
1547 def test_close_fds_1_2(self):
1548 self.check_close_std_fds([1, 2])
1549
1550 def test_close_fds_0_1_2(self):
1551 # Issue #10806: test that subprocess pipes still work properly with
1552 # all standard fds closed.
1553 self.check_close_std_fds([0, 1, 2])
1554
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001555 def test_remapping_std_fds(self):
1556 # open up some temporary files
1557 temps = [mkstemp() for i in range(3)]
1558 try:
1559 temp_fds = [fd for fd, fname in temps]
1560
1561 # unlink the files -- we won't need to reopen them
1562 for fd, fname in temps:
1563 os.unlink(fname)
1564
1565 # write some data to what will become stdin, and rewind
1566 os.write(temp_fds[1], b"STDIN")
1567 os.lseek(temp_fds[1], 0, 0)
1568
1569 # move the standard file descriptors out of the way
1570 saved_fds = [os.dup(fd) for fd in range(3)]
1571 try:
1572 # duplicate the file objects over the standard fd's
1573 for fd, temp_fd in enumerate(temp_fds):
1574 os.dup2(temp_fd, fd)
1575
1576 # now use those files in the "wrong" order, so that subprocess
1577 # has to rearrange them in the child
1578 p = subprocess.Popen([sys.executable, "-c",
1579 'import sys; got = sys.stdin.read();'
1580 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1581 stdin=temp_fds[1],
1582 stdout=temp_fds[2],
1583 stderr=temp_fds[0])
1584 p.wait()
1585 finally:
1586 # restore the original fd's underneath sys.stdin, etc.
1587 for std, saved in enumerate(saved_fds):
1588 os.dup2(saved, std)
1589 os.close(saved)
1590
1591 for fd in temp_fds:
1592 os.lseek(fd, 0, 0)
1593
1594 out = os.read(temp_fds[2], 1024)
1595 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1596 self.assertEqual(out, b"got STDIN")
1597 self.assertEqual(err, b"err")
1598
1599 finally:
1600 for fd in temp_fds:
1601 os.close(fd)
1602
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001603 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1604 # open up some temporary files
1605 temps = [mkstemp() for i in range(3)]
1606 temp_fds = [fd for fd, fname in temps]
1607 try:
1608 # unlink the files -- we won't need to reopen them
1609 for fd, fname in temps:
1610 os.unlink(fname)
1611
1612 # save a copy of the standard file descriptors
1613 saved_fds = [os.dup(fd) for fd in range(3)]
1614 try:
1615 # duplicate the temp files over the standard fd's 0, 1, 2
1616 for fd, temp_fd in enumerate(temp_fds):
1617 os.dup2(temp_fd, fd)
1618
1619 # write some data to what will become stdin, and rewind
1620 os.write(stdin_no, b"STDIN")
1621 os.lseek(stdin_no, 0, 0)
1622
1623 # now use those files in the given order, so that subprocess
1624 # has to rearrange them in the child
1625 p = subprocess.Popen([sys.executable, "-c",
1626 'import sys; got = sys.stdin.read();'
1627 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1628 stdin=stdin_no,
1629 stdout=stdout_no,
1630 stderr=stderr_no)
1631 p.wait()
1632
1633 for fd in temp_fds:
1634 os.lseek(fd, 0, 0)
1635
1636 out = os.read(stdout_no, 1024)
1637 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1638 finally:
1639 for std, saved in enumerate(saved_fds):
1640 os.dup2(saved, std)
1641 os.close(saved)
1642
1643 self.assertEqual(out, b"got STDIN")
1644 self.assertEqual(err, b"err")
1645
1646 finally:
1647 for fd in temp_fds:
1648 os.close(fd)
1649
1650 # When duping fds, if there arises a situation where one of the fds is
1651 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1652 # This tests all combinations of this.
1653 def test_swap_fds(self):
1654 self.check_swap_fds(0, 1, 2)
1655 self.check_swap_fds(0, 2, 1)
1656 self.check_swap_fds(1, 0, 2)
1657 self.check_swap_fds(1, 2, 0)
1658 self.check_swap_fds(2, 0, 1)
1659 self.check_swap_fds(2, 1, 0)
1660
Victor Stinner13bb71c2010-04-23 21:41:56 +00001661 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001662 def prepare():
1663 raise ValueError("surrogate:\uDCff")
1664
1665 try:
1666 subprocess.call(
1667 [sys.executable, "-c", "pass"],
1668 preexec_fn=prepare)
1669 except ValueError as err:
1670 # Pure Python implementations keeps the message
1671 self.assertIsNone(subprocess._posixsubprocess)
1672 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001673 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001674 # _posixsubprocess uses a default message
1675 self.assertIsNotNone(subprocess._posixsubprocess)
1676 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1677 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001678 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001679
Victor Stinner13bb71c2010-04-23 21:41:56 +00001680 def test_undecodable_env(self):
1681 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001682 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001683 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001684 env = os.environ.copy()
1685 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001686 # Use C locale to get ascii for the locale encoding to force
1687 # surrogate-escaping of \xFF in the child process; otherwise it can
1688 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001689 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001690 stdout = subprocess.check_output(
1691 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001692 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001693 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001694 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001695
1696 # test bytes
1697 key = key.encode("ascii", "surrogateescape")
1698 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001699 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001700 env = os.environ.copy()
1701 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001702 stdout = subprocess.check_output(
1703 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001704 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001705 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001706 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001707
Victor Stinnerb745a742010-05-18 17:17:23 +00001708 def test_bytes_program(self):
1709 abs_program = os.fsencode(sys.executable)
1710 path, program = os.path.split(sys.executable)
1711 program = os.fsencode(program)
1712
1713 # absolute bytes path
1714 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001715 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001716
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001717 # absolute bytes path as a string
1718 cmd = b"'" + abs_program + b"' -c pass"
1719 exitcode = subprocess.call(cmd, shell=True)
1720 self.assertEqual(exitcode, 0)
1721
Victor Stinnerb745a742010-05-18 17:17:23 +00001722 # bytes program, unicode PATH
1723 env = os.environ.copy()
1724 env["PATH"] = path
1725 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001726 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001727
1728 # bytes program, bytes PATH
1729 envb = os.environb.copy()
1730 envb[b"PATH"] = os.fsencode(path)
1731 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001732 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001733
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001734 def test_pipe_cloexec(self):
1735 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1736 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1737
1738 p1 = subprocess.Popen([sys.executable, sleeper],
1739 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1740 stderr=subprocess.PIPE, close_fds=False)
1741
1742 self.addCleanup(p1.communicate, b'')
1743
1744 p2 = subprocess.Popen([sys.executable, fd_status],
1745 stdout=subprocess.PIPE, close_fds=False)
1746
1747 output, error = p2.communicate()
1748 result_fds = set(map(int, output.split(b',')))
1749 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1750 p1.stderr.fileno()])
1751
1752 self.assertFalse(result_fds & unwanted_fds,
1753 "Expected no fds from %r to be open in child, "
1754 "found %r" %
1755 (unwanted_fds, result_fds & unwanted_fds))
1756
1757 def test_pipe_cloexec_real_tools(self):
1758 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1759 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1760
1761 subdata = b'zxcvbn'
1762 data = subdata * 4 + b'\n'
1763
1764 p1 = subprocess.Popen([sys.executable, qcat],
1765 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1766 close_fds=False)
1767
1768 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1769 stdin=p1.stdout, stdout=subprocess.PIPE,
1770 close_fds=False)
1771
1772 self.addCleanup(p1.wait)
1773 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001774 def kill_p1():
1775 try:
1776 p1.terminate()
1777 except ProcessLookupError:
1778 pass
1779 def kill_p2():
1780 try:
1781 p2.terminate()
1782 except ProcessLookupError:
1783 pass
1784 self.addCleanup(kill_p1)
1785 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001786
1787 p1.stdin.write(data)
1788 p1.stdin.close()
1789
1790 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1791
1792 self.assertTrue(readfiles, "The child hung")
1793 self.assertEqual(p2.stdout.read(), data)
1794
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001795 p1.stdout.close()
1796 p2.stdout.close()
1797
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001798 def test_close_fds(self):
1799 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1800
1801 fds = os.pipe()
1802 self.addCleanup(os.close, fds[0])
1803 self.addCleanup(os.close, fds[1])
1804
1805 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001806 # add a bunch more fds
1807 for _ in range(9):
1808 fd = os.open("/dev/null", os.O_RDONLY)
1809 self.addCleanup(os.close, fd)
1810 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001811
1812 p = subprocess.Popen([sys.executable, fd_status],
1813 stdout=subprocess.PIPE, close_fds=False)
1814 output, ignored = p.communicate()
1815 remaining_fds = set(map(int, output.split(b',')))
1816
1817 self.assertEqual(remaining_fds & open_fds, open_fds,
1818 "Some fds were closed")
1819
1820 p = subprocess.Popen([sys.executable, fd_status],
1821 stdout=subprocess.PIPE, close_fds=True)
1822 output, ignored = p.communicate()
1823 remaining_fds = set(map(int, output.split(b',')))
1824
1825 self.assertFalse(remaining_fds & open_fds,
1826 "Some fds were left open")
1827 self.assertIn(1, remaining_fds, "Subprocess failed")
1828
Gregory P. Smith8facece2012-01-21 14:01:08 -08001829 # Keep some of the fd's we opened open in the subprocess.
1830 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1831 fds_to_keep = set(open_fds.pop() for _ in range(8))
1832 p = subprocess.Popen([sys.executable, fd_status],
1833 stdout=subprocess.PIPE, close_fds=True,
1834 pass_fds=())
1835 output, ignored = p.communicate()
1836 remaining_fds = set(map(int, output.split(b',')))
1837
1838 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1839 "Some fds not in pass_fds were left open")
1840 self.assertIn(1, remaining_fds, "Subprocess failed")
1841
Victor Stinner88701e22011-06-01 13:13:04 +02001842 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1843 # descriptor of a pipe closed in the parent process is valid in the
1844 # child process according to fstat(), but the mode of the file
1845 # descriptor is invalid, and read or write raise an error.
1846 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001847 def test_pass_fds(self):
1848 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1849
1850 open_fds = set()
1851
1852 for x in range(5):
1853 fds = os.pipe()
1854 self.addCleanup(os.close, fds[0])
1855 self.addCleanup(os.close, fds[1])
1856 open_fds.update(fds)
1857
1858 for fd in open_fds:
1859 p = subprocess.Popen([sys.executable, fd_status],
1860 stdout=subprocess.PIPE, close_fds=True,
1861 pass_fds=(fd, ))
1862 output, ignored = p.communicate()
1863
1864 remaining_fds = set(map(int, output.split(b',')))
1865 to_be_closed = open_fds - {fd}
1866
1867 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1868 self.assertFalse(remaining_fds & to_be_closed,
1869 "fd to be closed passed")
1870
1871 # pass_fds overrides close_fds with a warning.
1872 with self.assertWarns(RuntimeWarning) as context:
1873 self.assertFalse(subprocess.call(
1874 [sys.executable, "-c", "import sys; sys.exit(0)"],
1875 close_fds=False, pass_fds=(fd, )))
1876 self.assertIn('overriding close_fds', str(context.warning))
1877
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001878 def test_stdout_stdin_are_single_inout_fd(self):
1879 with io.open(os.devnull, "r+") as inout:
1880 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1881 stdout=inout, stdin=inout)
1882 p.wait()
1883
1884 def test_stdout_stderr_are_single_inout_fd(self):
1885 with io.open(os.devnull, "r+") as inout:
1886 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1887 stdout=inout, stderr=inout)
1888 p.wait()
1889
1890 def test_stderr_stdin_are_single_inout_fd(self):
1891 with io.open(os.devnull, "r+") as inout:
1892 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1893 stderr=inout, stdin=inout)
1894 p.wait()
1895
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001896 def test_wait_when_sigchild_ignored(self):
1897 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1898 sigchild_ignore = support.findfile("sigchild_ignore.py",
1899 subdir="subprocessdata")
1900 p = subprocess.Popen([sys.executable, sigchild_ignore],
1901 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1902 stdout, stderr = p.communicate()
1903 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001904 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001905 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001906
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001907 def test_select_unbuffered(self):
1908 # Issue #11459: bufsize=0 should really set the pipes as
1909 # unbuffered (and therefore let select() work properly).
1910 select = support.import_module("select")
1911 p = subprocess.Popen([sys.executable, "-c",
1912 'import sys;'
1913 'sys.stdout.write("apple")'],
1914 stdout=subprocess.PIPE,
1915 bufsize=0)
1916 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001917 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001918 try:
1919 self.assertEqual(f.read(4), b"appl")
1920 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1921 finally:
1922 p.wait()
1923
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001924 def test_zombie_fast_process_del(self):
1925 # Issue #12650: on Unix, if Popen.__del__() was called before the
1926 # process exited, it wouldn't be added to subprocess._active, and would
1927 # remain a zombie.
1928 # spawn a Popen, and delete its reference before it exits
1929 p = subprocess.Popen([sys.executable, "-c",
1930 'import sys, time;'
1931 'time.sleep(0.2)'],
1932 stdout=subprocess.PIPE,
1933 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001934 self.addCleanup(p.stdout.close)
1935 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001936 ident = id(p)
1937 pid = p.pid
1938 del p
1939 # check that p is in the active processes list
1940 self.assertIn(ident, [id(o) for o in subprocess._active])
1941
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001942 def test_leak_fast_process_del_killed(self):
1943 # Issue #12650: on Unix, if Popen.__del__() was called before the
1944 # process exited, and the process got killed by a signal, it would never
1945 # be removed from subprocess._active, which triggered a FD and memory
1946 # leak.
1947 # spawn a Popen, delete its reference and kill it
1948 p = subprocess.Popen([sys.executable, "-c",
1949 'import time;'
1950 'time.sleep(3)'],
1951 stdout=subprocess.PIPE,
1952 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001953 self.addCleanup(p.stdout.close)
1954 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001955 ident = id(p)
1956 pid = p.pid
1957 del p
1958 os.kill(pid, signal.SIGKILL)
1959 # check that p is in the active processes list
1960 self.assertIn(ident, [id(o) for o in subprocess._active])
1961
1962 # let some time for the process to exit, and create a new Popen: this
1963 # should trigger the wait() of p
1964 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001965 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001966 with subprocess.Popen(['nonexisting_i_hope'],
1967 stdout=subprocess.PIPE,
1968 stderr=subprocess.PIPE) as proc:
1969 pass
1970 # p should have been wait()ed on, and removed from the _active list
1971 self.assertRaises(OSError, os.waitpid, pid, 0)
1972 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1973
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001974
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001975@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001976class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001977
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001978 def test_startupinfo(self):
1979 # startupinfo argument
1980 # We uses hardcoded constants, because we do not want to
1981 # depend on win32all.
1982 STARTF_USESHOWWINDOW = 1
1983 SW_MAXIMIZE = 3
1984 startupinfo = subprocess.STARTUPINFO()
1985 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1986 startupinfo.wShowWindow = SW_MAXIMIZE
1987 # Since Python is a console process, it won't be affected
1988 # by wShowWindow, but the argument should be silently
1989 # ignored
1990 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001991 startupinfo=startupinfo)
1992
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001993 def test_creationflags(self):
1994 # creationflags argument
1995 CREATE_NEW_CONSOLE = 16
1996 sys.stderr.write(" a DOS box should flash briefly ...\n")
1997 subprocess.call(sys.executable +
1998 ' -c "import time; time.sleep(0.25)"',
1999 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002000
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002001 def test_invalid_args(self):
2002 # invalid arguments should raise ValueError
2003 self.assertRaises(ValueError, subprocess.call,
2004 [sys.executable, "-c",
2005 "import sys; sys.exit(47)"],
2006 preexec_fn=lambda: 1)
2007 self.assertRaises(ValueError, subprocess.call,
2008 [sys.executable, "-c",
2009 "import sys; sys.exit(47)"],
2010 stdout=subprocess.PIPE,
2011 close_fds=True)
2012
2013 def test_close_fds(self):
2014 # close file descriptors
2015 rc = subprocess.call([sys.executable, "-c",
2016 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002017 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002018 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002019
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002020 def test_shell_sequence(self):
2021 # Run command through the shell (sequence)
2022 newenv = os.environ.copy()
2023 newenv["FRUIT"] = "physalis"
2024 p = subprocess.Popen(["set"], shell=1,
2025 stdout=subprocess.PIPE,
2026 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002027 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002028 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002029
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002030 def test_shell_string(self):
2031 # Run command through the shell (string)
2032 newenv = os.environ.copy()
2033 newenv["FRUIT"] = "physalis"
2034 p = subprocess.Popen("set", shell=1,
2035 stdout=subprocess.PIPE,
2036 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002037 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002038 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002039
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002040 def test_call_string(self):
2041 # call() function with string argument on Windows
2042 rc = subprocess.call(sys.executable +
2043 ' -c "import sys; sys.exit(47)"')
2044 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002045
Florent Xicluna4886d242010-03-08 13:27:26 +00002046 def _kill_process(self, method, *args):
2047 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002048 p = subprocess.Popen([sys.executable, "-c", """if 1:
2049 import sys, time
2050 sys.stdout.write('x\\n')
2051 sys.stdout.flush()
2052 time.sleep(30)
2053 """],
2054 stdin=subprocess.PIPE,
2055 stdout=subprocess.PIPE,
2056 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00002057 self.addCleanup(p.stdout.close)
2058 self.addCleanup(p.stderr.close)
2059 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00002060 # Wait for the interpreter to be completely initialized before
2061 # sending any signal.
2062 p.stdout.read(1)
2063 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00002064 _, stderr = p.communicate()
2065 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00002066 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002067 self.assertNotEqual(returncode, 0)
2068
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002069 def _kill_dead_process(self, method, *args):
2070 p = subprocess.Popen([sys.executable, "-c", """if 1:
2071 import sys, time
2072 sys.stdout.write('x\\n')
2073 sys.stdout.flush()
2074 sys.exit(42)
2075 """],
2076 stdin=subprocess.PIPE,
2077 stdout=subprocess.PIPE,
2078 stderr=subprocess.PIPE)
2079 self.addCleanup(p.stdout.close)
2080 self.addCleanup(p.stderr.close)
2081 self.addCleanup(p.stdin.close)
2082 # Wait for the interpreter to be completely initialized before
2083 # sending any signal.
2084 p.stdout.read(1)
2085 # The process should end after this
2086 time.sleep(1)
2087 # This shouldn't raise even though the child is now dead
2088 getattr(p, method)(*args)
2089 _, stderr = p.communicate()
2090 self.assertStderrEqual(stderr, b'')
2091 rc = p.wait()
2092 self.assertEqual(rc, 42)
2093
Florent Xicluna4886d242010-03-08 13:27:26 +00002094 def test_send_signal(self):
2095 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002096
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002097 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002098 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002099
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002100 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002101 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002102
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002103 def test_send_signal_dead(self):
2104 self._kill_dead_process('send_signal', signal.SIGTERM)
2105
2106 def test_kill_dead(self):
2107 self._kill_dead_process('kill')
2108
2109 def test_terminate_dead(self):
2110 self._kill_dead_process('terminate')
2111
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002112
Brett Cannona23810f2008-05-26 19:04:21 +00002113# The module says:
2114# "NB This only works (and is only relevant) for UNIX."
2115#
2116# Actually, getoutput should work on any platform with an os.popen, but
2117# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002118@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002119class CommandTests(unittest.TestCase):
2120 def test_getoutput(self):
2121 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2122 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2123 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002124
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002125 # we use mkdtemp in the next line to create an empty directory
2126 # under our exclusive control; from that, we can invent a pathname
2127 # that we _know_ won't exist. This is guaranteed to fail.
2128 dir = None
2129 try:
2130 dir = tempfile.mkdtemp()
2131 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00002132
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002133 status, output = subprocess.getstatusoutput('cat ' + name)
2134 self.assertNotEqual(status, 0)
2135 finally:
2136 if dir is not None:
2137 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002138
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002139
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002140@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
2141 "poll system call not supported")
2142class ProcessTestCaseNoPoll(ProcessTestCase):
2143 def setUp(self):
2144 subprocess._has_poll = False
2145 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002146
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002147 def tearDown(self):
2148 subprocess._has_poll = True
2149 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002150
2151
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002152class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00002153 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002154 def test_eintr_retry_call(self):
2155 record_calls = []
2156 def fake_os_func(*args):
2157 record_calls.append(args)
2158 if len(record_calls) == 2:
2159 raise OSError(errno.EINTR, "fake interrupted system call")
2160 return tuple(reversed(args))
2161
2162 self.assertEqual((999, 256),
2163 subprocess._eintr_retry_call(fake_os_func, 256, 999))
2164 self.assertEqual([(256, 999)], record_calls)
2165 # This time there will be an EINTR so it will loop once.
2166 self.assertEqual((666,),
2167 subprocess._eintr_retry_call(fake_os_func, 666))
2168 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
2169
2170
Tim Golden126c2962010-08-11 14:20:40 +00002171@unittest.skipUnless(mswindows, "Windows-specific tests")
2172class CommandsWithSpaces (BaseTestCase):
2173
2174 def setUp(self):
2175 super().setUp()
2176 f, fname = mkstemp(".py", "te st")
2177 self.fname = fname.lower ()
2178 os.write(f, b"import sys;"
2179 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2180 )
2181 os.close(f)
2182
2183 def tearDown(self):
2184 os.remove(self.fname)
2185 super().tearDown()
2186
2187 def with_spaces(self, *args, **kwargs):
2188 kwargs['stdout'] = subprocess.PIPE
2189 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002190 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002191 self.assertEqual(
2192 p.stdout.read ().decode("mbcs"),
2193 "2 [%r, 'ab cd']" % self.fname
2194 )
2195
2196 def test_shell_string_with_spaces(self):
2197 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002198 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2199 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002200
2201 def test_shell_sequence_with_spaces(self):
2202 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002203 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002204
2205 def test_noshell_string_with_spaces(self):
2206 # call() function with string argument with spaces on Windows
2207 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2208 "ab cd"))
2209
2210 def test_noshell_sequence_with_spaces(self):
2211 # call() function with sequence argument with spaces on Windows
2212 self.with_spaces([sys.executable, self.fname, "ab cd"])
2213
Brian Curtin79cdb662010-12-03 02:46:02 +00002214
Georg Brandla86b2622012-02-20 21:34:57 +01002215class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002216
2217 def test_pipe(self):
2218 with subprocess.Popen([sys.executable, "-c",
2219 "import sys;"
2220 "sys.stdout.write('stdout');"
2221 "sys.stderr.write('stderr');"],
2222 stdout=subprocess.PIPE,
2223 stderr=subprocess.PIPE) as proc:
2224 self.assertEqual(proc.stdout.read(), b"stdout")
2225 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2226
2227 self.assertTrue(proc.stdout.closed)
2228 self.assertTrue(proc.stderr.closed)
2229
2230 def test_returncode(self):
2231 with subprocess.Popen([sys.executable, "-c",
2232 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002233 pass
2234 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002235 self.assertEqual(proc.returncode, 100)
2236
2237 def test_communicate_stdin(self):
2238 with subprocess.Popen([sys.executable, "-c",
2239 "import sys;"
2240 "sys.exit(sys.stdin.read() == 'context')"],
2241 stdin=subprocess.PIPE) as proc:
2242 proc.communicate(b"context")
2243 self.assertEqual(proc.returncode, 1)
2244
2245 def test_invalid_args(self):
Andrew Svetlovb1726972012-12-26 23:34:54 +02002246 with self.assertRaises(FileNotFoundError) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002247 with subprocess.Popen(['nonexisting_i_hope'],
2248 stdout=subprocess.PIPE,
2249 stderr=subprocess.PIPE) as proc:
2250 pass
2251
Brian Curtin79cdb662010-12-03 02:46:02 +00002252
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002253def test_main():
2254 unit_tests = (ProcessTestCase,
2255 POSIXProcessTestCase,
2256 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002257 CommandTests,
2258 ProcessTestCaseNoPoll,
2259 HelperFunctionTests,
2260 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002261 ContextManagerTests,
2262 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002263
2264 support.run_unittest(*unit_tests)
2265 support.reap_children()
2266
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002267if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002268 unittest.main()