blob: 5220891cbb2ac5afd52ef132e954217c92be5d23 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
2from test import test_support
3import subprocess
4import sys
Gregory P. Smithf0739cb2017-01-22 22:38:28 -08005import platform
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00006import signal
7import os
Gregory P. Smithcce211f2010-03-01 00:05:08 +00008import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import tempfile
10import time
Tim Peters3761e8d2004-10-13 04:07:12 +000011import re
Ezio Melotti8f6a2872010-02-10 21:40:33 +000012import sysconfig
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000013
Benjamin Peterson8b59c232011-12-10 12:31:42 -050014try:
Gregory P. Smithf0739cb2017-01-22 22:38:28 -080015 import ctypes
16except ImportError:
17 ctypes = None
18
19try:
Benjamin Peterson8b59c232011-12-10 12:31:42 -050020 import resource
21except ImportError:
22 resource = None
Antoine Pitrou33fc7442013-08-30 23:38:13 +020023try:
24 import threading
25except ImportError:
26 threading = None
Benjamin Peterson8b59c232011-12-10 12:31:42 -050027
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000028mswindows = (sys.platform == "win32")
29
30#
31# Depends on the following external programs: Python
32#
33
34if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000035 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
36 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000037else:
38 SETBINARY = ''
39
Florent Xicluna98e3fc32010-02-27 19:20:50 +000040
Florent Xiclunafc4d6d72010-03-23 14:36:45 +000041class BaseTestCase(unittest.TestCase):
Neal Norwitzb15ac312006-06-29 04:10:08 +000042 def setUp(self):
Tim Peters38ff36c2006-06-30 06:18:39 +000043 # Try to minimize the number of children we have so this test
44 # doesn't crash on some buildbots (Alphas in particular).
Florent Xicluna98e3fc32010-02-27 19:20:50 +000045 test_support.reap_children()
Neal Norwitzb15ac312006-06-29 04:10:08 +000046
Florent Xiclunaab5e17f2010-03-04 21:31:58 +000047 def tearDown(self):
48 for inst in subprocess._active:
49 inst.wait()
50 subprocess._cleanup()
51 self.assertFalse(subprocess._active, "subprocess._active not empty")
52
Florent Xicluna98e3fc32010-02-27 19:20:50 +000053 def assertStderrEqual(self, stderr, expected, msg=None):
54 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
55 # shutdown time. That frustrates tests trying to check stderr produced
56 # from a spawned Python process.
57 actual = re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr)
58 self.assertEqual(actual, expected, msg)
Neal Norwitzb15ac312006-06-29 04:10:08 +000059
Florent Xiclunafc4d6d72010-03-23 14:36:45 +000060
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -080061class PopenTestException(Exception):
62 pass
63
64
65class PopenExecuteChildRaises(subprocess.Popen):
66 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
67 _execute_child fails.
68 """
69 def _execute_child(self, *args, **kwargs):
70 raise PopenTestException("Forced Exception for Test")
71
72
Florent Xiclunafc4d6d72010-03-23 14:36:45 +000073class ProcessTestCase(BaseTestCase):
74
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000075 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000076 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000077 rc = subprocess.call([sys.executable, "-c",
78 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000079 self.assertEqual(rc, 47)
80
Peter Astrand454f7672005-01-01 09:36:35 +000081 def test_check_call_zero(self):
82 # check_call() function with zero return code
83 rc = subprocess.check_call([sys.executable, "-c",
84 "import sys; sys.exit(0)"])
85 self.assertEqual(rc, 0)
86
87 def test_check_call_nonzero(self):
88 # check_call() function with non-zero return code
Florent Xicluna98e3fc32010-02-27 19:20:50 +000089 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000090 subprocess.check_call([sys.executable, "-c",
91 "import sys; sys.exit(47)"])
Florent Xicluna98e3fc32010-02-27 19:20:50 +000092 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000093
Gregory P. Smith26576802008-12-05 02:27:01 +000094 def test_check_output(self):
95 # check_output() function with zero return code
96 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +000097 [sys.executable, "-c", "print 'BDFL'"])
Ezio Melottiaa980582010-01-23 23:04:36 +000098 self.assertIn('BDFL', output)
Gregory P. Smith97f49f42008-12-04 20:21:09 +000099
Gregory P. Smith26576802008-12-05 02:27:01 +0000100 def test_check_output_nonzero(self):
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000101 # check_call() function with non-zero return code
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000102 with self.assertRaises(subprocess.CalledProcessError) as c:
Gregory P. Smith26576802008-12-05 02:27:01 +0000103 subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000104 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000105 self.assertEqual(c.exception.returncode, 5)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000106
Gregory P. Smith26576802008-12-05 02:27:01 +0000107 def test_check_output_stderr(self):
108 # check_output() function stderr redirected to stdout
109 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000110 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
111 stderr=subprocess.STDOUT)
Ezio Melottiaa980582010-01-23 23:04:36 +0000112 self.assertIn('BDFL', output)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000113
Gregory P. Smith26576802008-12-05 02:27:01 +0000114 def test_check_output_stdout_arg(self):
115 # check_output() function stderr redirected to stdout
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000116 with self.assertRaises(ValueError) as c:
Gregory P. Smith26576802008-12-05 02:27:01 +0000117 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000118 [sys.executable, "-c", "print 'will not be run'"],
119 stdout=sys.stdout)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000120 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000121 self.assertIn('stdout', c.exception.args[0])
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000122
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000123 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000124 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000125 newenv = os.environ.copy()
126 newenv["FRUIT"] = "banana"
127 rc = subprocess.call([sys.executable, "-c",
Florent Xiclunabab22a72010-03-04 19:40:48 +0000128 'import sys, os;'
129 'sys.exit(os.getenv("FRUIT")=="banana")'],
130 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000131 self.assertEqual(rc, 1)
132
Victor Stinner776e69b2011-06-01 01:03:00 +0200133 def test_invalid_args(self):
134 # Popen() called with invalid arguments should raise TypeError
135 # but Popen.__del__ should not complain (issue #12085)
Victor Stinnere9b185f2011-06-01 01:57:48 +0200136 with test_support.captured_stderr() as s:
Victor Stinner776e69b2011-06-01 01:03:00 +0200137 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
138 argcount = subprocess.Popen.__init__.__code__.co_argcount
139 too_many_args = [0] * (argcount + 1)
140 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
141 self.assertEqual(s.getvalue(), '')
142
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000143 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000144 # .stdin is None when not redirected
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
146 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000147 self.addCleanup(p.stdout.close)
148 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000149 p.wait()
150 self.assertEqual(p.stdin, None)
151
152 def test_stdout_none(self):
Ezio Melottiefaad092013-03-11 00:34:33 +0200153 # .stdout is None when not redirected, and the child's stdout will
154 # be inherited from the parent. In order to test this we run a
155 # subprocess in a subprocess:
156 # this_test
157 # \-- subprocess created by this test (parent)
158 # \-- subprocess created by the parent subprocess (child)
159 # The parent doesn't specify stdout, so the child will use the
160 # parent's stdout. This test checks that the message printed by the
161 # child goes to the parent stdout. The parent also checks that the
162 # child's stdout is None. See #11963.
163 code = ('import sys; from subprocess import Popen, PIPE;'
164 'p = Popen([sys.executable, "-c", "print \'test_stdout_none\'"],'
165 ' stdin=PIPE, stderr=PIPE);'
166 'p.wait(); assert p.stdout is None;')
167 p = subprocess.Popen([sys.executable, "-c", code],
168 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
169 self.addCleanup(p.stdout.close)
Brian Curtind117b562010-11-05 04:09:09 +0000170 self.addCleanup(p.stderr.close)
Ezio Melottiefaad092013-03-11 00:34:33 +0200171 out, err = p.communicate()
172 self.assertEqual(p.returncode, 0, err)
173 self.assertEqual(out.rstrip(), 'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000174
175 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000176 # .stderr is None when not redirected
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000177 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
178 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000179 self.addCleanup(p.stdout.close)
180 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000181 p.wait()
182 self.assertEqual(p.stderr, None)
183
Ezio Melotti8f6a2872010-02-10 21:40:33 +0000184 def test_executable_with_cwd(self):
Florent Xicluna63763702010-03-11 01:50:48 +0000185 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti8f6a2872010-02-10 21:40:33 +0000186 p = subprocess.Popen(["somethingyoudonthave", "-c",
187 "import sys; sys.exit(47)"],
188 executable=sys.executable, cwd=python_dir)
189 p.wait()
190 self.assertEqual(p.returncode, 47)
191
192 @unittest.skipIf(sysconfig.is_python_build(),
193 "need an installed Python. See #7774")
194 def test_executable_without_cwd(self):
195 # For a normal installation, it should work without 'cwd'
196 # argument. For test runs in the build directory, see #7774.
197 p = subprocess.Popen(["somethingyoudonthave", "-c",
198 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000199 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000200 p.wait()
201 self.assertEqual(p.returncode, 47)
202
203 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000204 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000205 p = subprocess.Popen([sys.executable, "-c",
206 'import sys; sys.exit(sys.stdin.read() == "pear")'],
207 stdin=subprocess.PIPE)
208 p.stdin.write("pear")
209 p.stdin.close()
210 p.wait()
211 self.assertEqual(p.returncode, 1)
212
213 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000214 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000215 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000216 d = tf.fileno()
217 os.write(d, "pear")
218 os.lseek(d, 0, 0)
219 p = subprocess.Popen([sys.executable, "-c",
220 'import sys; sys.exit(sys.stdin.read() == "pear")'],
221 stdin=d)
222 p.wait()
223 self.assertEqual(p.returncode, 1)
224
225 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000226 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 tf = tempfile.TemporaryFile()
228 tf.write("pear")
229 tf.seek(0)
230 p = subprocess.Popen([sys.executable, "-c",
231 'import sys; sys.exit(sys.stdin.read() == "pear")'],
232 stdin=tf)
233 p.wait()
234 self.assertEqual(p.returncode, 1)
235
236 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000237 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238 p = subprocess.Popen([sys.executable, "-c",
239 'import sys; sys.stdout.write("orange")'],
240 stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000241 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 self.assertEqual(p.stdout.read(), "orange")
243
244 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000245 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000246 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 d = tf.fileno()
248 p = subprocess.Popen([sys.executable, "-c",
249 'import sys; sys.stdout.write("orange")'],
250 stdout=d)
251 p.wait()
252 os.lseek(d, 0, 0)
253 self.assertEqual(os.read(d, 1024), "orange")
254
255 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000256 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000257 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000258 p = subprocess.Popen([sys.executable, "-c",
259 'import sys; sys.stdout.write("orange")'],
260 stdout=tf)
261 p.wait()
262 tf.seek(0)
263 self.assertEqual(tf.read(), "orange")
264
265 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000266 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000267 p = subprocess.Popen([sys.executable, "-c",
268 'import sys; sys.stderr.write("strawberry")'],
269 stderr=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000270 self.addCleanup(p.stderr.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000271 self.assertStderrEqual(p.stderr.read(), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000272
273 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000274 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000275 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276 d = tf.fileno()
277 p = subprocess.Popen([sys.executable, "-c",
278 'import sys; sys.stderr.write("strawberry")'],
279 stderr=d)
280 p.wait()
281 os.lseek(d, 0, 0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000282 self.assertStderrEqual(os.read(d, 1024), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000283
284 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000285 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000286 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000287 p = subprocess.Popen([sys.executable, "-c",
288 'import sys; sys.stderr.write("strawberry")'],
289 stderr=tf)
290 p.wait()
291 tf.seek(0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000292 self.assertStderrEqual(tf.read(), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293
Martin Panter1edccfa2016-05-13 01:54:44 +0000294 def test_stderr_redirect_with_no_stdout_redirect(self):
295 # test stderr=STDOUT while stdout=None (not set)
296
297 # - grandchild prints to stderr
298 # - child redirects grandchild's stderr to its stdout
299 # - the parent should get grandchild's stderr in child's stdout
300 p = subprocess.Popen([sys.executable, "-c",
301 'import sys, subprocess;'
302 'rc = subprocess.call([sys.executable, "-c",'
303 ' "import sys;"'
304 ' "sys.stderr.write(\'42\')"],'
305 ' stderr=subprocess.STDOUT);'
306 'sys.exit(rc)'],
307 stdout=subprocess.PIPE,
308 stderr=subprocess.PIPE)
309 stdout, stderr = p.communicate()
310 #NOTE: stdout should get stderr from grandchild
311 self.assertStderrEqual(stdout, b'42')
312 self.assertStderrEqual(stderr, b'') # should be empty
313 self.assertEqual(p.returncode, 0)
314
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000315 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000316 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000317 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000318 'import sys;'
319 'sys.stdout.write("apple");'
320 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000321 'sys.stderr.write("orange")'],
322 stdout=subprocess.PIPE,
323 stderr=subprocess.STDOUT)
Brian Curtind117b562010-11-05 04:09:09 +0000324 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000325 self.assertStderrEqual(p.stdout.read(), "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000326
327 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000328 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000329 tf = tempfile.TemporaryFile()
330 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000331 'import sys;'
332 'sys.stdout.write("apple");'
333 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334 'sys.stderr.write("orange")'],
335 stdout=tf,
336 stderr=tf)
337 p.wait()
338 tf.seek(0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000339 self.assertStderrEqual(tf.read(), "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000340
Gustavo Niemeyerc36bede2006-09-07 00:48:33 +0000341 def test_stdout_filedes_of_stdout(self):
342 # stdout is set to 1 (#1531862).
Ezio Melotti9b9cd4c2013-03-11 03:21:08 +0200343 # To avoid printing the text on stdout, we do something similar to
Ezio Melottiefaad092013-03-11 00:34:33 +0200344 # test_stdout_none (see above). The parent subprocess calls the child
345 # subprocess passing stdout=1, and this test uses stdout=PIPE in
346 # order to capture and check the output of the parent. See #11963.
347 code = ('import sys, subprocess; '
348 'rc = subprocess.call([sys.executable, "-c", '
349 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
Ezio Melotti9b9cd4c2013-03-11 03:21:08 +0200350 '\'test with stdout=1\'))"], stdout=1); '
351 'assert rc == 18')
Ezio Melottiefaad092013-03-11 00:34:33 +0200352 p = subprocess.Popen([sys.executable, "-c", code],
353 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
354 self.addCleanup(p.stdout.close)
355 self.addCleanup(p.stderr.close)
356 out, err = p.communicate()
357 self.assertEqual(p.returncode, 0, err)
Ezio Melotti9b9cd4c2013-03-11 03:21:08 +0200358 self.assertEqual(out.rstrip(), 'test with stdout=1')
Gustavo Niemeyerc36bede2006-09-07 00:48:33 +0000359
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000360 def test_cwd(self):
Guido van Rossume9a0e882007-12-20 17:28:10 +0000361 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000362 # We cannot use os.path.realpath to canonicalize the path,
363 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
364 cwd = os.getcwd()
365 os.chdir(tmpdir)
366 tmpdir = os.getcwd()
367 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000368 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000369 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370 'sys.stdout.write(os.getcwd())'],
371 stdout=subprocess.PIPE,
372 cwd=tmpdir)
Brian Curtind117b562010-11-05 04:09:09 +0000373 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000374 normcase = os.path.normcase
375 self.assertEqual(normcase(p.stdout.read()), normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000376
377 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000378 newenv = os.environ.copy()
379 newenv["FRUIT"] = "orange"
380 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000381 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000382 'sys.stdout.write(os.getenv("FRUIT"))'],
383 stdout=subprocess.PIPE,
384 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000385 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000386 self.assertEqual(p.stdout.read(), "orange")
387
Serhiy Storchaka9dda2ca2017-06-24 11:49:00 +0300388 def test_invalid_cmd(self):
389 # null character in the command name
390 cmd = sys.executable + '\0'
391 with self.assertRaises(TypeError):
392 subprocess.Popen([cmd, "-c", "pass"])
393
394 # null character in the command argument
395 with self.assertRaises(TypeError):
396 subprocess.Popen([sys.executable, "-c", "pass#\0"])
397
398 def test_invalid_env(self):
399 # null character in the enviroment variable name
400 newenv = os.environ.copy()
401 newenv["FRUIT\0VEGETABLE"] = "cabbage"
402 with self.assertRaises(TypeError):
403 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
404
405 # null character in the enviroment variable value
406 newenv = os.environ.copy()
407 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
408 with self.assertRaises(TypeError):
409 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
410
411 # equal character in the enviroment variable name
412 newenv = os.environ.copy()
413 newenv["FRUIT=ORANGE"] = "lemon"
414 with self.assertRaises(ValueError):
415 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
416
417 # equal character in the enviroment variable value
418 newenv = os.environ.copy()
419 newenv["FRUIT"] = "orange=lemon"
420 p = subprocess.Popen([sys.executable, "-c",
421 'import sys, os;'
422 'sys.stdout.write(os.getenv("FRUIT"))'],
423 stdout=subprocess.PIPE,
424 env=newenv)
425 stdout, stderr = p.communicate()
426 self.assertEqual(stdout, "orange=lemon")
427
Peter Astrandcbac93c2005-03-03 20:24:28 +0000428 def test_communicate_stdin(self):
429 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000430 'import sys;'
431 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000432 stdin=subprocess.PIPE)
433 p.communicate("pear")
434 self.assertEqual(p.returncode, 1)
435
436 def test_communicate_stdout(self):
437 p = subprocess.Popen([sys.executable, "-c",
438 'import sys; sys.stdout.write("pineapple")'],
439 stdout=subprocess.PIPE)
440 (stdout, stderr) = p.communicate()
441 self.assertEqual(stdout, "pineapple")
442 self.assertEqual(stderr, None)
443
444 def test_communicate_stderr(self):
445 p = subprocess.Popen([sys.executable, "-c",
446 'import sys; sys.stderr.write("pineapple")'],
447 stderr=subprocess.PIPE)
448 (stdout, stderr) = p.communicate()
449 self.assertEqual(stdout, None)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000450 self.assertStderrEqual(stderr, "pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000451
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000453 p = subprocess.Popen([sys.executable, "-c",
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000454 'import sys,os;'
455 'sys.stderr.write("pineapple");'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000456 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000457 stdin=subprocess.PIPE,
458 stdout=subprocess.PIPE,
459 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000460 self.addCleanup(p.stdout.close)
461 self.addCleanup(p.stderr.close)
462 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463 (stdout, stderr) = p.communicate("banana")
464 self.assertEqual(stdout, "banana")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000465 self.assertStderrEqual(stderr, "pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000467 # This test is Linux specific for simplicity to at least have
468 # some coverage. It is not a platform specific bug.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000469 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
470 "Linux specific")
471 # Test for the fd leak reported in http://bugs.python.org/issue2791.
472 def test_communicate_pipe_fd_leak(self):
473 fd_directory = '/proc/%d/fd' % os.getpid()
474 num_fds_before_popen = len(os.listdir(fd_directory))
Martin Panterad6a99c2016-09-10 10:38:22 +0000475 p = subprocess.Popen([sys.executable, "-c", "print('')"],
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000476 stdout=subprocess.PIPE)
477 p.communicate()
478 num_fds_after_communicate = len(os.listdir(fd_directory))
479 del p
480 num_fds_after_destruction = len(os.listdir(fd_directory))
481 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
482 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000483
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000485 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000486 p = subprocess.Popen([sys.executable, "-c",
487 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488 (stdout, stderr) = p.communicate()
489 self.assertEqual(stdout, None)
490 self.assertEqual(stderr, None)
491
492 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000493 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000495 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000496 x, y = os.pipe()
497 if mswindows:
498 pipe_buf = 512
499 else:
500 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
501 os.close(x)
502 os.close(y)
503 p = subprocess.Popen([sys.executable, "-c",
Tim Peterse718f612004-10-12 21:51:32 +0000504 'import sys,os;'
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000505 'sys.stdout.write(sys.stdin.read(47));'
506 'sys.stderr.write("xyz"*%d);'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
Tim Peters3b01a702004-10-12 22:19:32 +0000508 stdin=subprocess.PIPE,
509 stdout=subprocess.PIPE,
510 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000511 self.addCleanup(p.stdout.close)
512 self.addCleanup(p.stderr.close)
513 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514 string_to_write = "abc"*pipe_buf
515 (stdout, stderr) = p.communicate(string_to_write)
516 self.assertEqual(stdout, string_to_write)
517
518 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000519 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000521 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000523 stdin=subprocess.PIPE,
524 stdout=subprocess.PIPE,
525 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000526 self.addCleanup(p.stdout.close)
527 self.addCleanup(p.stderr.close)
528 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000529 p.stdin.write("banana")
530 (stdout, stderr) = p.communicate("split")
531 self.assertEqual(stdout, "bananasplit")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000532 self.assertStderrEqual(stderr, "")
Tim Peterse718f612004-10-12 21:51:32 +0000533
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000535 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000536 'import sys,os;' + SETBINARY +
537 'sys.stdout.write("line1\\n");'
538 'sys.stdout.flush();'
539 'sys.stdout.write("line2\\r");'
540 'sys.stdout.flush();'
541 'sys.stdout.write("line3\\r\\n");'
542 'sys.stdout.flush();'
543 'sys.stdout.write("line4\\r");'
544 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000546 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 'sys.stdout.write("\\nline6");'],
548 stdout=subprocess.PIPE,
549 universal_newlines=1)
Brian Curtind117b562010-11-05 04:09:09 +0000550 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551 stdout = p.stdout.read()
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000552 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000553 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000554 self.assertEqual(stdout,
555 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556 else:
557 # Interpreter without universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000558 self.assertEqual(stdout,
559 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000560
561 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000562 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000564 'import sys,os;' + SETBINARY +
565 'sys.stdout.write("line1\\n");'
566 'sys.stdout.flush();'
567 'sys.stdout.write("line2\\r");'
568 'sys.stdout.flush();'
569 'sys.stdout.write("line3\\r\\n");'
570 'sys.stdout.flush();'
571 'sys.stdout.write("line4\\r");'
572 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000573 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000574 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000575 'sys.stdout.write("\\nline6");'],
576 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
577 universal_newlines=1)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000578 self.addCleanup(p.stdout.close)
579 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000580 (stdout, stderr) = p.communicate()
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000581 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000582 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000583 self.assertEqual(stdout,
584 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000585 else:
586 # Interpreter without universal newline support
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000587 self.assertEqual(stdout,
588 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589
590 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000591 # Make sure we leak no resources
Antoine Pitroub0b3bff2010-09-18 22:42:30 +0000592 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000593 max_handles = 1026 # too much for most UNIX systems
594 else:
Antoine Pitroub0b3bff2010-09-18 22:42:30 +0000595 max_handles = 2050 # too much for (at least some) Windows setups
596 handles = []
597 try:
598 for i in range(max_handles):
599 try:
600 handles.append(os.open(test_support.TESTFN,
601 os.O_WRONLY | os.O_CREAT))
602 except OSError as e:
603 if e.errno != errno.EMFILE:
604 raise
605 break
606 else:
607 self.skipTest("failed to reach the file descriptor limit "
608 "(tried %d)" % max_handles)
609 # Close a couple of them (should be enough for a subprocess)
610 for i in range(10):
611 os.close(handles.pop())
612 # Loop creating some subprocesses. If one of them leaks some fds,
613 # the next loop iteration will fail by reaching the max fd limit.
614 for i in range(15):
615 p = subprocess.Popen([sys.executable, "-c",
616 "import sys;"
617 "sys.stdout.write(sys.stdin.read())"],
618 stdin=subprocess.PIPE,
619 stdout=subprocess.PIPE,
620 stderr=subprocess.PIPE)
621 data = p.communicate(b"lime")[0]
622 self.assertEqual(data, b"lime")
623 finally:
624 for h in handles:
625 os.close(h)
Mark Dickinson313dc9b2012-10-07 15:41:38 +0100626 test_support.unlink(test_support.TESTFN)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000627
628 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000629 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
630 '"a b c" d e')
631 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
632 'ab\\"c \\ d')
Gregory P. Smithe047e6d2008-01-19 20:49:02 +0000633 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
634 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000635 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
636 'a\\\\\\b "de fg" h')
637 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
638 'a\\\\\\"b c d')
639 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
640 '"a\\\\b c" d e')
641 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
642 '"a\\\\b\\ c" d e')
Peter Astrand10514a72007-01-13 22:35:35 +0000643 self.assertEqual(subprocess.list2cmdline(['ab', '']),
644 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000645
646
647 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000648 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000649 "-c", "import time; time.sleep(1)"])
650 count = 0
651 while p.poll() is None:
652 time.sleep(0.1)
653 count += 1
654 # We expect that the poll loop probably went around about 10 times,
655 # but, based on system scheduling we can't control, it's possible
656 # poll() never returned None. It "should be" very rare that it
657 # didn't go around at least twice.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000658 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659 # Subsequent invocations should just return the returncode
660 self.assertEqual(p.poll(), 0)
661
662
663 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000664 p = subprocess.Popen([sys.executable,
665 "-c", "import time; time.sleep(2)"])
666 self.assertEqual(p.wait(), 0)
667 # Subsequent invocations should just return the returncode
668 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000669
Peter Astrand738131d2004-11-30 21:04:45 +0000670
671 def test_invalid_bufsize(self):
672 # an invalid type of the bufsize argument should raise
673 # TypeError.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000674 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000675 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000676
Georg Brandlf3715d22009-02-14 17:01:36 +0000677 def test_leaking_fds_on_error(self):
678 # see bug #5179: Popen leaks file descriptors to PIPEs if
679 # the child fails to execute; this will eventually exhaust
680 # the maximum number of open fds. 1024 seems a very common
681 # value for that limit, but Windows has 2048, so we loop
682 # 1024 times (each call leaked two fds).
683 for i in range(1024):
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000684 # Windows raises IOError. Others raise OSError.
685 with self.assertRaises(EnvironmentError) as c:
Georg Brandlf3715d22009-02-14 17:01:36 +0000686 subprocess.Popen(['nonexisting_i_hope'],
687 stdout=subprocess.PIPE,
688 stderr=subprocess.PIPE)
R David Murraycdd5fc92011-03-13 22:37:18 -0400689 # ignore errors that indicate the command was not found
690 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000691 raise c.exception
Georg Brandlf3715d22009-02-14 17:01:36 +0000692
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200693 @unittest.skipIf(threading is None, "threading required")
694 def test_double_close_on_error(self):
695 # Issue #18851
696 fds = []
697 def open_fds():
698 for i in range(20):
699 fds.extend(os.pipe())
700 time.sleep(0.001)
701 t = threading.Thread(target=open_fds)
702 t.start()
703 try:
704 with self.assertRaises(EnvironmentError):
705 subprocess.Popen(['nonexisting_i_hope'],
706 stdin=subprocess.PIPE,
707 stdout=subprocess.PIPE,
708 stderr=subprocess.PIPE)
709 finally:
710 t.join()
711 exc = None
712 for fd in fds:
713 # If a double close occurred, some of those fds will
714 # already have been closed by mistake, and os.close()
715 # here will raise.
716 try:
717 os.close(fd)
718 except OSError as e:
719 exc = e
720 if exc is not None:
721 raise exc
722
Tim Golden90374f52010-08-06 13:14:33 +0000723 def test_handles_closed_on_exception(self):
724 # If CreateProcess exits with an error, ensure the
725 # duplicate output handles are released
Berker Peksagb7c35152015-09-28 15:37:57 +0300726 ifhandle, ifname = tempfile.mkstemp()
727 ofhandle, ofname = tempfile.mkstemp()
728 efhandle, efname = tempfile.mkstemp()
Tim Golden90374f52010-08-06 13:14:33 +0000729 try:
730 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
731 stderr=efhandle)
732 except OSError:
733 os.close(ifhandle)
734 os.remove(ifname)
735 os.close(ofhandle)
736 os.remove(ofname)
737 os.close(efhandle)
738 os.remove(efname)
739 self.assertFalse(os.path.exists(ifname))
740 self.assertFalse(os.path.exists(ofname))
741 self.assertFalse(os.path.exists(efname))
742
Ross Lagerwall104c3f12011-04-05 15:24:34 +0200743 def test_communicate_epipe(self):
744 # Issue 10963: communicate() should hide EPIPE
745 p = subprocess.Popen([sys.executable, "-c", 'pass'],
746 stdin=subprocess.PIPE,
747 stdout=subprocess.PIPE,
748 stderr=subprocess.PIPE)
749 self.addCleanup(p.stdout.close)
750 self.addCleanup(p.stderr.close)
751 self.addCleanup(p.stdin.close)
752 p.communicate("x" * 2**20)
753
754 def test_communicate_epipe_only_stdin(self):
755 # Issue 10963: communicate() should hide EPIPE
756 p = subprocess.Popen([sys.executable, "-c", 'pass'],
757 stdin=subprocess.PIPE)
758 self.addCleanup(p.stdin.close)
759 time.sleep(2)
760 p.communicate("x" * 2**20)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000761
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -0800762 # This test is Linux-ish specific for simplicity to at least have
763 # some coverage. It is not a platform specific bug.
764 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
765 "Linux specific")
766 def test_failed_child_execute_fd_leak(self):
767 """Test for the fork() failure fd leak reported in issue16327."""
768 fd_directory = '/proc/%d/fd' % os.getpid()
769 fds_before_popen = os.listdir(fd_directory)
770 with self.assertRaises(PopenTestException):
771 PopenExecuteChildRaises(
772 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
773 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
774
775 # NOTE: This test doesn't verify that the real _execute_child
776 # does not close the file descriptors itself on the way out
777 # during an exception. Code inspection has confirmed that.
778
779 fds_after_exception = os.listdir(fd_directory)
780 self.assertEqual(fds_before_popen, fds_after_exception)
781
782
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000783# context manager
784class _SuppressCoreFiles(object):
785 """Try to prevent core files from being created."""
786 old_limit = None
787
788 def __enter__(self):
789 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson8b59c232011-12-10 12:31:42 -0500790 if resource is not None:
791 try:
792 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
793 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
794 except (ValueError, resource.error):
795 pass
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000796
Ronald Oussoren21b44e02010-07-23 12:26:30 +0000797 if sys.platform == 'darwin':
798 # Check if the 'Crash Reporter' on OSX was configured
799 # in 'Developer' mode and warn that it will get triggered
800 # when it is.
801 #
802 # This assumes that this context manager is used in tests
803 # that might trigger the next manager.
804 value = subprocess.Popen(['/usr/bin/defaults', 'read',
805 'com.apple.CrashReporter', 'DialogType'],
806 stdout=subprocess.PIPE).communicate()[0]
807 if value.strip() == b'developer':
808 print "this tests triggers the Crash Reporter, that is intentional"
809 sys.stdout.flush()
810
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000811 def __exit__(self, *args):
812 """Return core file behavior to default."""
813 if self.old_limit is None:
814 return
Benjamin Peterson8b59c232011-12-10 12:31:42 -0500815 if resource is not None:
816 try:
817 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
818 except (ValueError, resource.error):
819 pass
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000820
Victor Stinnerb78fed92011-07-05 14:50:35 +0200821 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
822 "Requires signal.SIGALRM")
Victor Stinnere7901312011-07-05 14:08:01 +0200823 def test_communicate_eintr(self):
824 # Issue #12493: communicate() should handle EINTR
825 def handler(signum, frame):
826 pass
827 old_handler = signal.signal(signal.SIGALRM, handler)
828 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
829
830 # the process is running for 2 seconds
831 args = [sys.executable, "-c", 'import time; time.sleep(2)']
832 for stream in ('stdout', 'stderr'):
833 kw = {stream: subprocess.PIPE}
834 with subprocess.Popen(args, **kw) as process:
835 signal.alarm(1)
836 # communicate() will be interrupted by SIGALRM
837 process.communicate()
838
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000839
Florent Xiclunabab22a72010-03-04 19:40:48 +0000840@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000841class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +0000842
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000843 def test_exceptions(self):
844 # caught & re-raised exceptions
845 with self.assertRaises(OSError) as c:
846 p = subprocess.Popen([sys.executable, "-c", ""],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 cwd="/this/path/does/not/exist")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000848 # The attribute child_traceback should contain "os.chdir" somewhere.
849 self.assertIn("os.chdir", c.exception.child_traceback)
Tim Peterse718f612004-10-12 21:51:32 +0000850
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000851 def test_run_abort(self):
852 # returncode handles signal termination
853 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000854 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000855 "import os; os.abort()"])
856 p.wait()
857 self.assertEqual(-p.returncode, signal.SIGABRT)
858
859 def test_preexec(self):
860 # preexec function
861 p = subprocess.Popen([sys.executable, "-c",
862 "import sys, os;"
863 "sys.stdout.write(os.getenv('FRUIT'))"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000864 stdout=subprocess.PIPE,
865 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtind117b562010-11-05 04:09:09 +0000866 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000867 self.assertEqual(p.stdout.read(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000868
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800869 class _TestExecuteChildPopen(subprocess.Popen):
870 """Used to test behavior at the end of _execute_child."""
871 def __init__(self, testcase, *args, **kwargs):
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800872 self._testcase = testcase
873 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith211248b2012-11-11 02:00:49 -0800874
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800875 def _execute_child(
876 self, args, executable, preexec_fn, close_fds, cwd, env,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200877 universal_newlines, startupinfo, creationflags, shell, to_close,
Gregory P. Smith211248b2012-11-11 02:00:49 -0800878 p2cread, p2cwrite,
879 c2pread, c2pwrite,
880 errread, errwrite):
881 try:
882 subprocess.Popen._execute_child(
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800883 self, args, executable, preexec_fn, close_fds,
Gregory P. Smith211248b2012-11-11 02:00:49 -0800884 cwd, env, universal_newlines,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200885 startupinfo, creationflags, shell, to_close,
Gregory P. Smith211248b2012-11-11 02:00:49 -0800886 p2cread, p2cwrite,
887 c2pread, c2pwrite,
888 errread, errwrite)
889 finally:
890 # Open a bunch of file descriptors and verify that
891 # none of them are the same as the ones the Popen
892 # instance is using for stdin/stdout/stderr.
893 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
894 for _ in range(8)]
895 try:
896 for fd in devzero_fds:
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800897 self._testcase.assertNotIn(
898 fd, (p2cwrite, c2pread, errread))
Gregory P. Smith211248b2012-11-11 02:00:49 -0800899 finally:
Richard Oudkerk045e4572013-06-10 16:27:45 +0100900 for fd in devzero_fds:
901 os.close(fd)
Gregory P. Smith211248b2012-11-11 02:00:49 -0800902
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800903 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
904 def test_preexec_errpipe_does_not_double_close_pipes(self):
905 """Issue16140: Don't double close pipes on preexec error."""
906
907 def raise_it():
908 raise RuntimeError("force the _execute_child() errpipe_data path.")
Gregory P. Smith211248b2012-11-11 02:00:49 -0800909
910 with self.assertRaises(RuntimeError):
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800911 self._TestExecuteChildPopen(
912 self, [sys.executable, "-c", "pass"],
913 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
914 stderr=subprocess.PIPE, preexec_fn=raise_it)
Gregory P. Smith211248b2012-11-11 02:00:49 -0800915
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000916 def test_args_string(self):
917 # args is a string
Berker Peksagb7c35152015-09-28 15:37:57 +0300918 f, fname = tempfile.mkstemp()
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000919 os.write(f, "#!/bin/sh\n")
920 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
921 sys.executable)
922 os.close(f)
923 os.chmod(fname, 0o700)
924 p = subprocess.Popen(fname)
925 p.wait()
926 os.remove(fname)
927 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000928
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000929 def test_invalid_args(self):
930 # invalid arguments should raise ValueError
931 self.assertRaises(ValueError, subprocess.call,
932 [sys.executable, "-c",
933 "import sys; sys.exit(47)"],
934 startupinfo=47)
935 self.assertRaises(ValueError, subprocess.call,
936 [sys.executable, "-c",
937 "import sys; sys.exit(47)"],
938 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000939
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000940 def test_shell_sequence(self):
941 # Run command through the shell (sequence)
942 newenv = os.environ.copy()
943 newenv["FRUIT"] = "apple"
944 p = subprocess.Popen(["echo $FRUIT"], shell=1,
945 stdout=subprocess.PIPE,
946 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000947 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000948 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000949
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000950 def test_shell_string(self):
951 # Run command through the shell (string)
952 newenv = os.environ.copy()
953 newenv["FRUIT"] = "apple"
954 p = subprocess.Popen("echo $FRUIT", shell=1,
955 stdout=subprocess.PIPE,
956 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000957 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000958 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000959
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000960 def test_call_string(self):
961 # call() function with string argument on UNIX
Berker Peksagb7c35152015-09-28 15:37:57 +0300962 f, fname = tempfile.mkstemp()
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000963 os.write(f, "#!/bin/sh\n")
964 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
965 sys.executable)
966 os.close(f)
967 os.chmod(fname, 0700)
968 rc = subprocess.call(fname)
969 os.remove(fname)
970 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000971
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000972 def test_specific_shell(self):
973 # Issue #9265: Incorrect name passed as arg[0].
974 shells = []
975 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
976 for name in ['bash', 'ksh']:
977 sh = os.path.join(prefix, name)
978 if os.path.isfile(sh):
979 shells.append(sh)
980 if not shells: # Will probably work for any shell but csh.
981 self.skipTest("bash or ksh required for this test")
982 sh = '/bin/sh'
983 if os.path.isfile(sh) and not os.path.islink(sh):
984 # Test will fail if /bin/sh is a symlink to csh.
985 shells.append(sh)
986 for sh in shells:
987 p = subprocess.Popen("echo $0", executable=sh, shell=True,
988 stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000989 self.addCleanup(p.stdout.close)
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000990 self.assertEqual(p.stdout.read().strip(), sh)
991
Florent Xiclunac0838642010-03-07 15:27:39 +0000992 def _kill_process(self, method, *args):
Florent Xiclunacecef392010-03-05 19:31:21 +0000993 # Do not inherit file handles from the parent.
994 # It should fix failures on some platforms.
Antoine Pitroua6166da2010-09-20 11:20:44 +0000995 p = subprocess.Popen([sys.executable, "-c", """if 1:
996 import sys, time
997 sys.stdout.write('x\\n')
998 sys.stdout.flush()
999 time.sleep(30)
1000 """],
1001 close_fds=True,
1002 stdin=subprocess.PIPE,
1003 stdout=subprocess.PIPE,
1004 stderr=subprocess.PIPE)
1005 # Wait for the interpreter to be completely initialized before
1006 # sending any signal.
1007 p.stdout.read(1)
1008 getattr(p, method)(*args)
Florent Xiclunac0838642010-03-07 15:27:39 +00001009 return p
1010
Charles-François Natalief2bd672013-01-12 16:52:20 +01001011 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1012 "Due to known OS bug (issue #16762)")
Antoine Pitrouf60845b2012-03-11 19:29:12 +01001013 def _kill_dead_process(self, method, *args):
1014 # Do not inherit file handles from the parent.
1015 # It should fix failures on some platforms.
1016 p = subprocess.Popen([sys.executable, "-c", """if 1:
1017 import sys, time
1018 sys.stdout.write('x\\n')
1019 sys.stdout.flush()
1020 """],
1021 close_fds=True,
1022 stdin=subprocess.PIPE,
1023 stdout=subprocess.PIPE,
1024 stderr=subprocess.PIPE)
1025 # Wait for the interpreter to be completely initialized before
1026 # sending any signal.
1027 p.stdout.read(1)
1028 # The process should end after this
1029 time.sleep(1)
1030 # This shouldn't raise even though the child is now dead
1031 getattr(p, method)(*args)
1032 p.communicate()
1033
Florent Xiclunac0838642010-03-07 15:27:39 +00001034 def test_send_signal(self):
1035 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunafc4d6d72010-03-23 14:36:45 +00001036 _, stderr = p.communicate()
Florent Xicluna3c919cf2010-03-23 19:19:16 +00001037 self.assertIn('KeyboardInterrupt', stderr)
Florent Xicluna446ff142010-03-23 15:05:30 +00001038 self.assertNotEqual(p.wait(), 0)
Christian Heimese74c8f22008-04-19 02:23:57 +00001039
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001040 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001041 p = self._kill_process('kill')
Florent Xicluna446ff142010-03-23 15:05:30 +00001042 _, stderr = p.communicate()
1043 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001044 self.assertEqual(p.wait(), -signal.SIGKILL)
Christian Heimese74c8f22008-04-19 02:23:57 +00001045
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001046 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001047 p = self._kill_process('terminate')
Florent Xicluna446ff142010-03-23 15:05:30 +00001048 _, stderr = p.communicate()
1049 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001050 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +00001051
Antoine Pitrouf60845b2012-03-11 19:29:12 +01001052 def test_send_signal_dead(self):
1053 # Sending a signal to a dead process
1054 self._kill_dead_process('send_signal', signal.SIGINT)
1055
1056 def test_kill_dead(self):
1057 # Killing a dead process
1058 self._kill_dead_process('kill')
1059
1060 def test_terminate_dead(self):
1061 # Terminating a dead process
1062 self._kill_dead_process('terminate')
1063
Antoine Pitrou91ce0d92011-01-03 18:45:09 +00001064 def check_close_std_fds(self, fds):
1065 # Issue #9905: test that subprocess pipes still work properly with
1066 # some standard fds closed
1067 stdin = 0
1068 newfds = []
1069 for a in fds:
1070 b = os.dup(a)
1071 newfds.append(b)
1072 if a == 0:
1073 stdin = b
1074 try:
1075 for fd in fds:
1076 os.close(fd)
1077 out, err = subprocess.Popen([sys.executable, "-c",
1078 'import sys;'
1079 'sys.stdout.write("apple");'
1080 'sys.stdout.flush();'
1081 'sys.stderr.write("orange")'],
1082 stdin=stdin,
1083 stdout=subprocess.PIPE,
1084 stderr=subprocess.PIPE).communicate()
1085 err = test_support.strip_python_stderr(err)
1086 self.assertEqual((out, err), (b'apple', b'orange'))
1087 finally:
1088 for b, a in zip(newfds, fds):
1089 os.dup2(b, a)
1090 for b in newfds:
1091 os.close(b)
1092
1093 def test_close_fd_0(self):
1094 self.check_close_std_fds([0])
1095
1096 def test_close_fd_1(self):
1097 self.check_close_std_fds([1])
1098
1099 def test_close_fd_2(self):
1100 self.check_close_std_fds([2])
1101
1102 def test_close_fds_0_1(self):
1103 self.check_close_std_fds([0, 1])
1104
1105 def test_close_fds_0_2(self):
1106 self.check_close_std_fds([0, 2])
1107
1108 def test_close_fds_1_2(self):
1109 self.check_close_std_fds([1, 2])
1110
1111 def test_close_fds_0_1_2(self):
1112 # Issue #10806: test that subprocess pipes still work properly with
1113 # all standard fds closed.
1114 self.check_close_std_fds([0, 1, 2])
1115
Ross Lagerwalld8e39012011-07-27 18:54:53 +02001116 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1117 # open up some temporary files
Berker Peksagb7c35152015-09-28 15:37:57 +03001118 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld8e39012011-07-27 18:54:53 +02001119 temp_fds = [fd for fd, fname in temps]
1120 try:
1121 # unlink the files -- we won't need to reopen them
1122 for fd, fname in temps:
1123 os.unlink(fname)
1124
1125 # save a copy of the standard file descriptors
1126 saved_fds = [os.dup(fd) for fd in range(3)]
1127 try:
1128 # duplicate the temp files over the standard fd's 0, 1, 2
1129 for fd, temp_fd in enumerate(temp_fds):
1130 os.dup2(temp_fd, fd)
1131
1132 # write some data to what will become stdin, and rewind
1133 os.write(stdin_no, b"STDIN")
1134 os.lseek(stdin_no, 0, 0)
1135
1136 # now use those files in the given order, so that subprocess
1137 # has to rearrange them in the child
1138 p = subprocess.Popen([sys.executable, "-c",
1139 'import sys; got = sys.stdin.read();'
1140 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1141 stdin=stdin_no,
1142 stdout=stdout_no,
1143 stderr=stderr_no)
1144 p.wait()
1145
1146 for fd in temp_fds:
1147 os.lseek(fd, 0, 0)
1148
1149 out = os.read(stdout_no, 1024)
1150 err = test_support.strip_python_stderr(os.read(stderr_no, 1024))
1151 finally:
1152 for std, saved in enumerate(saved_fds):
1153 os.dup2(saved, std)
1154 os.close(saved)
1155
1156 self.assertEqual(out, b"got STDIN")
1157 self.assertEqual(err, b"err")
1158
1159 finally:
1160 for fd in temp_fds:
1161 os.close(fd)
1162
1163 # When duping fds, if there arises a situation where one of the fds is
1164 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1165 # This tests all combinations of this.
1166 def test_swap_fds(self):
1167 self.check_swap_fds(0, 1, 2)
1168 self.check_swap_fds(0, 2, 1)
1169 self.check_swap_fds(1, 0, 2)
1170 self.check_swap_fds(1, 2, 0)
1171 self.check_swap_fds(2, 0, 1)
1172 self.check_swap_fds(2, 1, 0)
1173
Gregory P. Smith312efbc2010-12-14 15:02:53 +00001174 def test_wait_when_sigchild_ignored(self):
1175 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1176 sigchild_ignore = test_support.findfile("sigchild_ignore.py",
1177 subdir="subprocessdata")
1178 p = subprocess.Popen([sys.executable, sigchild_ignore],
1179 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1180 stdout, stderr = p.communicate()
1181 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
1182 " non-zero with this error:\n%s" % stderr)
1183
Charles-François Natali100df0f2011-08-18 17:56:02 +02001184 def test_zombie_fast_process_del(self):
1185 # Issue #12650: on Unix, if Popen.__del__() was called before the
1186 # process exited, it wouldn't be added to subprocess._active, and would
1187 # remain a zombie.
1188 # spawn a Popen, and delete its reference before it exits
1189 p = subprocess.Popen([sys.executable, "-c",
1190 'import sys, time;'
1191 'time.sleep(0.2)'],
1192 stdout=subprocess.PIPE,
1193 stderr=subprocess.PIPE)
Nadeem Vawda86059362011-08-19 05:22:24 +02001194 self.addCleanup(p.stdout.close)
1195 self.addCleanup(p.stderr.close)
Charles-François Natali100df0f2011-08-18 17:56:02 +02001196 ident = id(p)
1197 pid = p.pid
1198 del p
1199 # check that p is in the active processes list
1200 self.assertIn(ident, [id(o) for o in subprocess._active])
1201
Charles-François Natali100df0f2011-08-18 17:56:02 +02001202 def test_leak_fast_process_del_killed(self):
1203 # Issue #12650: on Unix, if Popen.__del__() was called before the
1204 # process exited, and the process got killed by a signal, it would never
1205 # be removed from subprocess._active, which triggered a FD and memory
1206 # leak.
1207 # spawn a Popen, delete its reference and kill it
1208 p = subprocess.Popen([sys.executable, "-c",
1209 'import time;'
1210 'time.sleep(3)'],
1211 stdout=subprocess.PIPE,
1212 stderr=subprocess.PIPE)
Nadeem Vawda86059362011-08-19 05:22:24 +02001213 self.addCleanup(p.stdout.close)
1214 self.addCleanup(p.stderr.close)
Charles-François Natali100df0f2011-08-18 17:56:02 +02001215 ident = id(p)
1216 pid = p.pid
1217 del p
1218 os.kill(pid, signal.SIGKILL)
1219 # check that p is in the active processes list
1220 self.assertIn(ident, [id(o) for o in subprocess._active])
1221
1222 # let some time for the process to exit, and create a new Popen: this
1223 # should trigger the wait() of p
1224 time.sleep(0.2)
1225 with self.assertRaises(EnvironmentError) as c:
1226 with subprocess.Popen(['nonexisting_i_hope'],
1227 stdout=subprocess.PIPE,
1228 stderr=subprocess.PIPE) as proc:
1229 pass
1230 # p should have been wait()ed on, and removed from the _active list
1231 self.assertRaises(OSError, os.waitpid, pid, 0)
1232 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1233
Charles-François Natali2a34eb32011-08-25 21:20:54 +02001234 def test_pipe_cloexec(self):
1235 # Issue 12786: check that the communication pipes' FDs are set CLOEXEC,
1236 # and are not inherited by another child process.
1237 p1 = subprocess.Popen([sys.executable, "-c",
1238 'import os;'
1239 'os.read(0, 1)'
1240 ],
1241 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1242 stderr=subprocess.PIPE)
1243
1244 p2 = subprocess.Popen([sys.executable, "-c", """if True:
1245 import os, errno, sys
1246 for fd in %r:
1247 try:
1248 os.close(fd)
1249 except OSError as e:
1250 if e.errno != errno.EBADF:
1251 raise
1252 else:
1253 sys.exit(1)
1254 sys.exit(0)
1255 """ % [f.fileno() for f in (p1.stdin, p1.stdout,
1256 p1.stderr)]
1257 ],
1258 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1259 stderr=subprocess.PIPE, close_fds=False)
1260 p1.communicate('foo')
1261 _, stderr = p2.communicate()
1262
1263 self.assertEqual(p2.returncode, 0, "Unexpected error: " + repr(stderr))
1264
Gregory P. Smithf0739cb2017-01-22 22:38:28 -08001265 _libc_file_extensions = {
1266 'Linux': 'so.6',
1267 'Darwin': 'dylib',
1268 }
1269 @unittest.skipIf(not ctypes, 'ctypes module required.')
1270 @unittest.skipIf(platform.uname()[0] not in _libc_file_extensions,
1271 'Test requires a libc this code can load with ctypes.')
1272 @unittest.skipIf(not sys.executable, 'Test requires sys.executable.')
1273 def test_child_terminated_in_stopped_state(self):
1274 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
1275 PTRACE_TRACEME = 0 # From glibc and MacOS (PT_TRACE_ME).
1276 libc_name = 'libc.' + self._libc_file_extensions[platform.uname()[0]]
1277 libc = ctypes.CDLL(libc_name)
1278 if not hasattr(libc, 'ptrace'):
1279 raise unittest.SkipTest('ptrace() required.')
1280 test_ptrace = subprocess.Popen(
1281 [sys.executable, '-c', """if True:
1282 import ctypes
1283 libc = ctypes.CDLL({libc_name!r})
1284 libc.ptrace({PTRACE_TRACEME}, 0, 0)
1285 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
1286 ])
1287 if test_ptrace.wait() != 0:
1288 raise unittest.SkipTest('ptrace() failed - unable to test.')
1289 child = subprocess.Popen(
1290 [sys.executable, '-c', """if True:
1291 import ctypes
1292 libc = ctypes.CDLL({libc_name!r})
1293 libc.ptrace({PTRACE_TRACEME}, 0, 0)
1294 libc.printf(ctypes.c_char_p(0xdeadbeef)) # Crash the process.
1295 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
1296 ])
1297 try:
1298 returncode = child.wait()
1299 except Exception as e:
1300 child.kill() # Clean up the hung stopped process.
1301 raise e
1302 self.assertNotEqual(0, returncode)
1303 self.assertLess(returncode, 0) # signal death, likely SIGSEGV.
1304
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001305
Florent Xiclunabab22a72010-03-04 19:40:48 +00001306@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +00001307class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +00001308
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001309 def test_startupinfo(self):
1310 # startupinfo argument
1311 # We uses hardcoded constants, because we do not want to
1312 # depend on win32all.
1313 STARTF_USESHOWWINDOW = 1
1314 SW_MAXIMIZE = 3
1315 startupinfo = subprocess.STARTUPINFO()
1316 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1317 startupinfo.wShowWindow = SW_MAXIMIZE
1318 # Since Python is a console process, it won't be affected
1319 # by wShowWindow, but the argument should be silently
1320 # ignored
1321 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001322 startupinfo=startupinfo)
1323
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001324 def test_creationflags(self):
1325 # creationflags argument
1326 CREATE_NEW_CONSOLE = 16
1327 sys.stderr.write(" a DOS box should flash briefly ...\n")
1328 subprocess.call(sys.executable +
1329 ' -c "import time; time.sleep(0.25)"',
1330 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001331
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001332 def test_invalid_args(self):
1333 # invalid arguments should raise ValueError
1334 self.assertRaises(ValueError, subprocess.call,
1335 [sys.executable, "-c",
1336 "import sys; sys.exit(47)"],
1337 preexec_fn=lambda: 1)
1338 self.assertRaises(ValueError, subprocess.call,
1339 [sys.executable, "-c",
1340 "import sys; sys.exit(47)"],
1341 stdout=subprocess.PIPE,
1342 close_fds=True)
1343
1344 def test_close_fds(self):
1345 # close file descriptors
1346 rc = subprocess.call([sys.executable, "-c",
1347 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001348 close_fds=True)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001349 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001350
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001351 def test_shell_sequence(self):
1352 # Run command through the shell (sequence)
1353 newenv = os.environ.copy()
1354 newenv["FRUIT"] = "physalis"
1355 p = subprocess.Popen(["set"], shell=1,
1356 stdout=subprocess.PIPE,
1357 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001358 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001359 self.assertIn("physalis", p.stdout.read())
Peter Astrand81a191b2007-05-26 22:18:20 +00001360
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001361 def test_shell_string(self):
1362 # Run command through the shell (string)
1363 newenv = os.environ.copy()
1364 newenv["FRUIT"] = "physalis"
1365 p = subprocess.Popen("set", shell=1,
1366 stdout=subprocess.PIPE,
1367 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001368 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001369 self.assertIn("physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001370
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001371 def test_call_string(self):
1372 # call() function with string argument on Windows
1373 rc = subprocess.call(sys.executable +
1374 ' -c "import sys; sys.exit(47)"')
1375 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001376
Florent Xiclunac0838642010-03-07 15:27:39 +00001377 def _kill_process(self, method, *args):
Florent Xicluna400efc22010-03-07 17:12:23 +00001378 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroudee00972010-09-24 19:00:29 +00001379 p = subprocess.Popen([sys.executable, "-c", """if 1:
1380 import sys, time
1381 sys.stdout.write('x\\n')
1382 sys.stdout.flush()
1383 time.sleep(30)
1384 """],
1385 stdin=subprocess.PIPE,
1386 stdout=subprocess.PIPE,
1387 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001388 self.addCleanup(p.stdout.close)
1389 self.addCleanup(p.stderr.close)
1390 self.addCleanup(p.stdin.close)
Antoine Pitroudee00972010-09-24 19:00:29 +00001391 # Wait for the interpreter to be completely initialized before
1392 # sending any signal.
1393 p.stdout.read(1)
1394 getattr(p, method)(*args)
Florent Xicluna446ff142010-03-23 15:05:30 +00001395 _, stderr = p.communicate()
1396 self.assertStderrEqual(stderr, '')
Antoine Pitroudee00972010-09-24 19:00:29 +00001397 returncode = p.wait()
Florent Xiclunafaf17532010-03-08 10:59:33 +00001398 self.assertNotEqual(returncode, 0)
Florent Xiclunac0838642010-03-07 15:27:39 +00001399
Antoine Pitrouf60845b2012-03-11 19:29:12 +01001400 def _kill_dead_process(self, method, *args):
1401 p = subprocess.Popen([sys.executable, "-c", """if 1:
1402 import sys, time
1403 sys.stdout.write('x\\n')
1404 sys.stdout.flush()
1405 sys.exit(42)
1406 """],
1407 stdin=subprocess.PIPE,
1408 stdout=subprocess.PIPE,
1409 stderr=subprocess.PIPE)
1410 self.addCleanup(p.stdout.close)
1411 self.addCleanup(p.stderr.close)
1412 self.addCleanup(p.stdin.close)
1413 # Wait for the interpreter to be completely initialized before
1414 # sending any signal.
1415 p.stdout.read(1)
1416 # The process should end after this
1417 time.sleep(1)
1418 # This shouldn't raise even though the child is now dead
1419 getattr(p, method)(*args)
1420 _, stderr = p.communicate()
1421 self.assertStderrEqual(stderr, b'')
1422 rc = p.wait()
1423 self.assertEqual(rc, 42)
1424
Florent Xiclunac0838642010-03-07 15:27:39 +00001425 def test_send_signal(self):
1426 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimese74c8f22008-04-19 02:23:57 +00001427
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001428 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001429 self._kill_process('kill')
Christian Heimese74c8f22008-04-19 02:23:57 +00001430
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001431 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001432 self._kill_process('terminate')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001433
Antoine Pitrouf60845b2012-03-11 19:29:12 +01001434 def test_send_signal_dead(self):
1435 self._kill_dead_process('send_signal', signal.SIGTERM)
1436
1437 def test_kill_dead(self):
1438 self._kill_dead_process('kill')
1439
1440 def test_terminate_dead(self):
1441 self._kill_dead_process('terminate')
1442
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001443
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001444@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1445 "poll system call not supported")
1446class ProcessTestCaseNoPoll(ProcessTestCase):
1447 def setUp(self):
1448 subprocess._has_poll = False
1449 ProcessTestCase.setUp(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001450
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001451 def tearDown(self):
1452 subprocess._has_poll = True
1453 ProcessTestCase.tearDown(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001454
1455
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001456class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithc1baf4a2010-03-01 02:53:24 +00001457 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001458 def test_eintr_retry_call(self):
1459 record_calls = []
1460 def fake_os_func(*args):
1461 record_calls.append(args)
1462 if len(record_calls) == 2:
1463 raise OSError(errno.EINTR, "fake interrupted system call")
1464 return tuple(reversed(args))
1465
1466 self.assertEqual((999, 256),
1467 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1468 self.assertEqual([(256, 999)], record_calls)
1469 # This time there will be an EINTR so it will loop once.
1470 self.assertEqual((666,),
1471 subprocess._eintr_retry_call(fake_os_func, 666))
1472 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1473
Tim Golden8e4756c2010-08-12 11:00:35 +00001474@unittest.skipUnless(mswindows, "mswindows only")
1475class CommandsWithSpaces (BaseTestCase):
1476
1477 def setUp(self):
1478 super(CommandsWithSpaces, self).setUp()
Berker Peksagb7c35152015-09-28 15:37:57 +03001479 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden8e4756c2010-08-12 11:00:35 +00001480 self.fname = fname.lower ()
1481 os.write(f, b"import sys;"
1482 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1483 )
1484 os.close(f)
1485
1486 def tearDown(self):
1487 os.remove(self.fname)
1488 super(CommandsWithSpaces, self).tearDown()
1489
1490 def with_spaces(self, *args, **kwargs):
1491 kwargs['stdout'] = subprocess.PIPE
1492 p = subprocess.Popen(*args, **kwargs)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001493 self.addCleanup(p.stdout.close)
Tim Golden8e4756c2010-08-12 11:00:35 +00001494 self.assertEqual(
1495 p.stdout.read ().decode("mbcs"),
1496 "2 [%r, 'ab cd']" % self.fname
1497 )
1498
1499 def test_shell_string_with_spaces(self):
1500 # call() function with string argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +00001501 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1502 "ab cd"), shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +00001503
1504 def test_shell_sequence_with_spaces(self):
1505 # call() function with sequence argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +00001506 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +00001507
1508 def test_noshell_string_with_spaces(self):
1509 # call() function with string argument with spaces on Windows
1510 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1511 "ab cd"))
1512
1513 def test_noshell_sequence_with_spaces(self):
1514 # call() function with sequence argument with spaces on Windows
1515 self.with_spaces([sys.executable, self.fname, "ab cd"])
1516
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001517def test_main():
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001518 unit_tests = (ProcessTestCase,
1519 POSIXProcessTestCase,
1520 Win32ProcessTestCase,
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001521 ProcessTestCaseNoPoll,
Tim Golden8e4756c2010-08-12 11:00:35 +00001522 HelperFunctionTests,
1523 CommandsWithSpaces)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001524
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001525 test_support.run_unittest(*unit_tests)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001526 test_support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001527
1528if __name__ == "__main__":
1529 test_main()