blob: e8abfef82979c6550ae2bc7cede3d6647c3a2654 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003import subprocess
4import sys
5import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04006import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00008import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import tempfile
10import time
Tim Peters3761e8d2004-10-13 04:07:12 +000011import re
Ezio Melotti184bdfb2010-02-18 09:37:05 +000012import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000013import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000014import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040015import shutil
Gregory P. Smith32ec9da2010-03-19 16:53:08 +000016try:
17 import gc
18except ImportError:
19 gc = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000020
21mswindows = (sys.platform == "win32")
22
23#
24# Depends on the following external programs: Python
25#
26
27if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000028 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
29 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000030else:
31 SETBINARY = ''
32
Florent Xiclunab1e94e82010-02-27 22:12:37 +000033
34try:
35 mkstemp = tempfile.mkstemp
36except AttributeError:
37 # tempfile.mkstemp is not available
38 def mkstemp():
39 """Replacement for mkstemp, calling mktemp."""
40 fname = tempfile.mktemp()
41 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
42
Tim Peters3761e8d2004-10-13 04:07:12 +000043
Florent Xiclunac049d872010-03-27 22:47:23 +000044class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045 def setUp(self):
46 # Try to minimize the number of children we have so this test
47 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000048 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000050 def tearDown(self):
51 for inst in subprocess._active:
52 inst.wait()
53 subprocess._cleanup()
54 self.assertFalse(subprocess._active, "subprocess._active not empty")
55
Florent Xiclunab1e94e82010-02-27 22:12:37 +000056 def assertStderrEqual(self, stderr, expected, msg=None):
57 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
58 # shutdown time. That frustrates tests trying to check stderr produced
59 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000060 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040061 # strip_python_stderr also strips whitespace, so we do too.
62 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000063 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000064
Florent Xiclunac049d872010-03-27 22:47:23 +000065
66class ProcessTestCase(BaseTestCase):
67
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000068 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000069 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000070 rc = subprocess.call([sys.executable, "-c",
71 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000072 self.assertEqual(rc, 47)
73
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040074 def test_call_timeout(self):
75 # call() function with timeout argument; we want to test that the child
76 # process gets killed when the timeout expires. If the child isn't
77 # killed, this call will deadlock since subprocess.call waits for the
78 # child.
79 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
80 [sys.executable, "-c", "while True: pass"],
81 timeout=0.1)
82
Peter Astrand454f7672005-01-01 09:36:35 +000083 def test_check_call_zero(self):
84 # check_call() function with zero return code
85 rc = subprocess.check_call([sys.executable, "-c",
86 "import sys; sys.exit(0)"])
87 self.assertEqual(rc, 0)
88
89 def test_check_call_nonzero(self):
90 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000091 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000092 subprocess.check_call([sys.executable, "-c",
93 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000094 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000095
Georg Brandlf9734072008-12-07 15:30:06 +000096 def test_check_output(self):
97 # check_output() function with zero return code
98 output = subprocess.check_output(
99 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000100 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000101
102 def test_check_output_nonzero(self):
103 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000104 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000105 subprocess.check_output(
106 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000107 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000108
109 def test_check_output_stderr(self):
110 # check_output() function stderr redirected to stdout
111 output = subprocess.check_output(
112 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
113 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000114 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000115
116 def test_check_output_stdout_arg(self):
117 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000118 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000119 output = subprocess.check_output(
120 [sys.executable, "-c", "print('will not be run')"],
121 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000122 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000123 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000124
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400125 def test_check_output_timeout(self):
126 # check_output() function with timeout arg
127 with self.assertRaises(subprocess.TimeoutExpired) as c:
128 output = subprocess.check_output(
129 [sys.executable, "-c",
130 "import sys; sys.stdout.write('BDFL')\n"
131 "sys.stdout.flush()\n"
132 "while True: pass"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400133 # Some heavily loaded buildbots (sparc Debian 3.x) require
134 # this much time to start and print.
135 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400136 self.fail("Expected TimeoutExpired.")
137 self.assertEqual(c.exception.output, b'BDFL')
138
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000139 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000140 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000141 newenv = os.environ.copy()
142 newenv["FRUIT"] = "banana"
143 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000144 'import sys, os;'
145 'sys.exit(os.getenv("FRUIT")=="banana")'],
146 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000147 self.assertEqual(rc, 1)
148
149 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000150 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000151 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000152 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000153 self.addCleanup(p.stdout.close)
154 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000155 p.wait()
156 self.assertEqual(p.stdin, None)
157
158 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000159 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000160 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000161 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000162 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000163 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000164 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000165 self.addCleanup(p.stdin.close)
166 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000167 p.wait()
168 self.assertEqual(p.stdout, None)
169
170 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000171 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000172 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000173 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000174 self.addCleanup(p.stdout.close)
175 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000176 p.wait()
177 self.assertEqual(p.stderr, None)
178
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000179 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000180 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000181 p = subprocess.Popen(["somethingyoudonthave", "-c",
182 "import sys; sys.exit(47)"],
183 executable=sys.executable, cwd=python_dir)
184 p.wait()
185 self.assertEqual(p.returncode, 47)
186
187 @unittest.skipIf(sysconfig.is_python_build(),
188 "need an installed Python. See #7774")
189 def test_executable_without_cwd(self):
190 # For a normal installation, it should work without 'cwd'
191 # argument. For test runs in the build directory, see #7774.
192 p = subprocess.Popen(["somethingyoudonthave", "-c",
193 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000194 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000195 p.wait()
196 self.assertEqual(p.returncode, 47)
197
198 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000199 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000200 p = subprocess.Popen([sys.executable, "-c",
201 'import sys; sys.exit(sys.stdin.read() == "pear")'],
202 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000203 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000204 p.stdin.close()
205 p.wait()
206 self.assertEqual(p.returncode, 1)
207
208 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000209 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000210 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000211 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000212 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000213 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000214 os.lseek(d, 0, 0)
215 p = subprocess.Popen([sys.executable, "-c",
216 'import sys; sys.exit(sys.stdin.read() == "pear")'],
217 stdin=d)
218 p.wait()
219 self.assertEqual(p.returncode, 1)
220
221 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000222 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000224 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000225 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000226 tf.seek(0)
227 p = subprocess.Popen([sys.executable, "-c",
228 'import sys; sys.exit(sys.stdin.read() == "pear")'],
229 stdin=tf)
230 p.wait()
231 self.assertEqual(p.returncode, 1)
232
233 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000234 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000235 p = subprocess.Popen([sys.executable, "-c",
236 'import sys; sys.stdout.write("orange")'],
237 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000238 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000239 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000240
241 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000242 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000243 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000244 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 d = tf.fileno()
246 p = subprocess.Popen([sys.executable, "-c",
247 'import sys; sys.stdout.write("orange")'],
248 stdout=d)
249 p.wait()
250 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000251 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000252
253 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000254 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000255 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000256 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000257 p = subprocess.Popen([sys.executable, "-c",
258 'import sys; sys.stdout.write("orange")'],
259 stdout=tf)
260 p.wait()
261 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000262 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263
264 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000265 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000266 p = subprocess.Popen([sys.executable, "-c",
267 'import sys; sys.stderr.write("strawberry")'],
268 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000269 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000270 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271
272 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000273 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000274 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000275 self.addCleanup(tf.close)
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 Xiclunab1e94e82010-02-27 22:12:37 +0000282 self.assertStderrEqual(os.read(d, 1024), b"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()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000287 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000288 p = subprocess.Popen([sys.executable, "-c",
289 'import sys; sys.stderr.write("strawberry")'],
290 stderr=tf)
291 p.wait()
292 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000293 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294
295 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000296 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000297 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000298 'import sys;'
299 'sys.stdout.write("apple");'
300 'sys.stdout.flush();'
301 'sys.stderr.write("orange")'],
302 stdout=subprocess.PIPE,
303 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000304 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000305 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306
307 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000308 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000310 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000311 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000312 'import sys;'
313 'sys.stdout.write("apple");'
314 'sys.stdout.flush();'
315 'sys.stderr.write("orange")'],
316 stdout=tf,
317 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318 p.wait()
319 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000320 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000321
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322 def test_stdout_filedes_of_stdout(self):
323 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000324 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000325 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000326 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000327
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200328 def test_stdout_devnull(self):
329 p = subprocess.Popen([sys.executable, "-c",
330 'for i in range(10240):'
331 'print("x" * 1024)'],
332 stdout=subprocess.DEVNULL)
333 p.wait()
334 self.assertEqual(p.stdout, None)
335
336 def test_stderr_devnull(self):
337 p = subprocess.Popen([sys.executable, "-c",
338 'import sys\n'
339 'for i in range(10240):'
340 'sys.stderr.write("x" * 1024)'],
341 stderr=subprocess.DEVNULL)
342 p.wait()
343 self.assertEqual(p.stderr, None)
344
345 def test_stdin_devnull(self):
346 p = subprocess.Popen([sys.executable, "-c",
347 'import sys;'
348 'sys.stdin.read(1)'],
349 stdin=subprocess.DEVNULL)
350 p.wait()
351 self.assertEqual(p.stdin, None)
352
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000353 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000354 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000355 # We cannot use os.path.realpath to canonicalize the path,
356 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
357 cwd = os.getcwd()
358 os.chdir(tmpdir)
359 tmpdir = os.getcwd()
360 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000362 'import sys,os;'
363 'sys.stdout.write(os.getcwd())'],
364 stdout=subprocess.PIPE,
365 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000366 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000367 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000368 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
369 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370
371 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000372 newenv = os.environ.copy()
373 newenv["FRUIT"] = "orange"
374 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000375 'import sys,os;'
376 'sys.stdout.write(os.getenv("FRUIT"))'],
377 stdout=subprocess.PIPE,
378 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000379 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000380 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000381
Peter Astrandcbac93c2005-03-03 20:24:28 +0000382 def test_communicate_stdin(self):
383 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000384 'import sys;'
385 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000386 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000387 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000388 self.assertEqual(p.returncode, 1)
389
390 def test_communicate_stdout(self):
391 p = subprocess.Popen([sys.executable, "-c",
392 'import sys; sys.stdout.write("pineapple")'],
393 stdout=subprocess.PIPE)
394 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000395 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000396 self.assertEqual(stderr, None)
397
398 def test_communicate_stderr(self):
399 p = subprocess.Popen([sys.executable, "-c",
400 'import sys; sys.stderr.write("pineapple")'],
401 stderr=subprocess.PIPE)
402 (stdout, stderr) = p.communicate()
403 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000404 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000405
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000406 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000407 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000408 'import sys,os;'
409 'sys.stderr.write("pineapple");'
410 'sys.stdout.write(sys.stdin.read())'],
411 stdin=subprocess.PIPE,
412 stdout=subprocess.PIPE,
413 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000414 self.addCleanup(p.stdout.close)
415 self.addCleanup(p.stderr.close)
416 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000417 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000418 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000419 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000420
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400421 def test_communicate_timeout(self):
422 p = subprocess.Popen([sys.executable, "-c",
423 'import sys,os,time;'
424 'sys.stderr.write("pineapple\\n");'
425 'time.sleep(1);'
426 'sys.stderr.write("pear\\n");'
427 'sys.stdout.write(sys.stdin.read())'],
428 universal_newlines=True,
429 stdin=subprocess.PIPE,
430 stdout=subprocess.PIPE,
431 stderr=subprocess.PIPE)
432 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
433 timeout=0.3)
434 # Make sure we can keep waiting for it, and that we get the whole output
435 # after it completes.
436 (stdout, stderr) = p.communicate()
437 self.assertEqual(stdout, "banana")
438 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
439
440 def test_communicate_timeout_large_ouput(self):
441 # Test a expring timeout while the child is outputting lots of data.
442 p = subprocess.Popen([sys.executable, "-c",
443 'import sys,os,time;'
444 'sys.stdout.write("a" * (64 * 1024));'
445 'time.sleep(0.2);'
446 'sys.stdout.write("a" * (64 * 1024));'
447 'time.sleep(0.2);'
448 'sys.stdout.write("a" * (64 * 1024));'
449 'time.sleep(0.2);'
450 'sys.stdout.write("a" * (64 * 1024));'],
451 stdout=subprocess.PIPE)
452 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
453 (stdout, _) = p.communicate()
454 self.assertEqual(len(stdout), 4 * 64 * 1024)
455
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000456 # Test for the fd leak reported in http://bugs.python.org/issue2791.
457 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000458 for stdin_pipe in (False, True):
459 for stdout_pipe in (False, True):
460 for stderr_pipe in (False, True):
461 options = {}
462 if stdin_pipe:
463 options['stdin'] = subprocess.PIPE
464 if stdout_pipe:
465 options['stdout'] = subprocess.PIPE
466 if stderr_pipe:
467 options['stderr'] = subprocess.PIPE
468 if not options:
469 continue
470 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
471 p.communicate()
472 if p.stdin is not None:
473 self.assertTrue(p.stdin.closed)
474 if p.stdout is not None:
475 self.assertTrue(p.stdout.closed)
476 if p.stderr is not None:
477 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000478
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000480 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000481 p = subprocess.Popen([sys.executable, "-c",
482 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483 (stdout, stderr) = p.communicate()
484 self.assertEqual(stdout, None)
485 self.assertEqual(stderr, None)
486
487 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000488 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000490 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000491 x, y = os.pipe()
492 if mswindows:
493 pipe_buf = 512
494 else:
495 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
496 os.close(x)
497 os.close(y)
498 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000499 'import sys,os;'
500 'sys.stdout.write(sys.stdin.read(47));'
501 'sys.stderr.write("xyz"*%d);'
502 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
503 stdin=subprocess.PIPE,
504 stdout=subprocess.PIPE,
505 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000506 self.addCleanup(p.stdout.close)
507 self.addCleanup(p.stderr.close)
508 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000509 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000510 (stdout, stderr) = p.communicate(string_to_write)
511 self.assertEqual(stdout, string_to_write)
512
513 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000514 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000515 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000516 'import sys,os;'
517 'sys.stdout.write(sys.stdin.read())'],
518 stdin=subprocess.PIPE,
519 stdout=subprocess.PIPE,
520 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000521 self.addCleanup(p.stdout.close)
522 self.addCleanup(p.stderr.close)
523 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000524 p.stdin.write(b"banana")
525 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000526 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000527 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000528
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000529 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000531 'import sys,os;' + SETBINARY +
532 'sys.stdout.write("line1\\n");'
533 'sys.stdout.flush();'
534 'sys.stdout.write("line2\\n");'
535 'sys.stdout.flush();'
536 'sys.stdout.write("line3\\r\\n");'
537 'sys.stdout.flush();'
538 'sys.stdout.write("line4\\r");'
539 'sys.stdout.flush();'
540 'sys.stdout.write("\\nline5");'
541 'sys.stdout.flush();'
542 'sys.stdout.write("\\nline6");'],
543 stdout=subprocess.PIPE,
544 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000545 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000547 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548
549 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000550 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000552 'import sys,os;' + SETBINARY +
553 'sys.stdout.write("line1\\n");'
554 'sys.stdout.flush();'
555 'sys.stdout.write("line2\\n");'
556 'sys.stdout.flush();'
557 'sys.stdout.write("line3\\r\\n");'
558 'sys.stdout.flush();'
559 'sys.stdout.write("line4\\r");'
560 'sys.stdout.flush();'
561 'sys.stdout.write("\\nline5");'
562 'sys.stdout.flush();'
563 'sys.stdout.write("\\nline6");'],
564 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
565 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000566 self.addCleanup(p.stdout.close)
567 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000569 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000570
571 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000572 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000573 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000574 max_handles = 1026 # too much for most UNIX systems
575 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000576 max_handles = 2050 # too much for (at least some) Windows setups
577 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400578 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000579 try:
580 for i in range(max_handles):
581 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400582 tmpfile = os.path.join(tmpdir, support.TESTFN)
583 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000584 except OSError as e:
585 if e.errno != errno.EMFILE:
586 raise
587 break
588 else:
589 self.skipTest("failed to reach the file descriptor limit "
590 "(tried %d)" % max_handles)
591 # Close a couple of them (should be enough for a subprocess)
592 for i in range(10):
593 os.close(handles.pop())
594 # Loop creating some subprocesses. If one of them leaks some fds,
595 # the next loop iteration will fail by reaching the max fd limit.
596 for i in range(15):
597 p = subprocess.Popen([sys.executable, "-c",
598 "import sys;"
599 "sys.stdout.write(sys.stdin.read())"],
600 stdin=subprocess.PIPE,
601 stdout=subprocess.PIPE,
602 stderr=subprocess.PIPE)
603 data = p.communicate(b"lime")[0]
604 self.assertEqual(data, b"lime")
605 finally:
606 for h in handles:
607 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400608 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000609
610 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000611 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
612 '"a b c" d e')
613 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
614 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000615 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
616 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000617 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
618 'a\\\\\\b "de fg" h')
619 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
620 'a\\\\\\"b c d')
621 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
622 '"a\\\\b c" d e')
623 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
624 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000625 self.assertEqual(subprocess.list2cmdline(['ab', '']),
626 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000627
628
629 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000630 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000631 "-c", "import time; time.sleep(1)"])
632 count = 0
633 while p.poll() is None:
634 time.sleep(0.1)
635 count += 1
636 # We expect that the poll loop probably went around about 10 times,
637 # but, based on system scheduling we can't control, it's possible
638 # poll() never returned None. It "should be" very rare that it
639 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000640 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000641 # Subsequent invocations should just return the returncode
642 self.assertEqual(p.poll(), 0)
643
644
645 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646 p = subprocess.Popen([sys.executable,
647 "-c", "import time; time.sleep(2)"])
648 self.assertEqual(p.wait(), 0)
649 # Subsequent invocations should just return the returncode
650 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000651
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400652 def test_wait_timeout(self):
653 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400654 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400655 with self.assertRaises(subprocess.TimeoutExpired) as c:
656 p.wait(timeout=0.01)
657 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400658 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
659 # time to start.
660 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400661
Peter Astrand738131d2004-11-30 21:04:45 +0000662 def test_invalid_bufsize(self):
663 # an invalid type of the bufsize argument should raise
664 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000665 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000666 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000667
Guido van Rossum46a05a72007-06-07 21:56:45 +0000668 def test_bufsize_is_none(self):
669 # bufsize=None should be the same as bufsize=0.
670 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
671 self.assertEqual(p.wait(), 0)
672 # Again with keyword arg
673 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
674 self.assertEqual(p.wait(), 0)
675
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000676 def test_leaking_fds_on_error(self):
677 # see bug #5179: Popen leaks file descriptors to PIPEs if
678 # the child fails to execute; this will eventually exhaust
679 # the maximum number of open fds. 1024 seems a very common
680 # value for that limit, but Windows has 2048, so we loop
681 # 1024 times (each call leaked two fds).
682 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000683 # Windows raises IOError. Others raise OSError.
684 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000685 subprocess.Popen(['nonexisting_i_hope'],
686 stdout=subprocess.PIPE,
687 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400688 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400689 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000690 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000691
Victor Stinnerb3693582010-05-21 20:13:12 +0000692 def test_issue8780(self):
693 # Ensure that stdout is inherited from the parent
694 # if stdout=PIPE is not used
695 code = ';'.join((
696 'import subprocess, sys',
697 'retcode = subprocess.call('
698 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
699 'assert retcode == 0'))
700 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000701 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000702
Tim Goldenaf5ac392010-08-06 13:03:56 +0000703 def test_handles_closed_on_exception(self):
704 # If CreateProcess exits with an error, ensure the
705 # duplicate output handles are released
706 ifhandle, ifname = mkstemp()
707 ofhandle, ofname = mkstemp()
708 efhandle, efname = mkstemp()
709 try:
710 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
711 stderr=efhandle)
712 except OSError:
713 os.close(ifhandle)
714 os.remove(ifname)
715 os.close(ofhandle)
716 os.remove(ofname)
717 os.close(efhandle)
718 os.remove(efname)
719 self.assertFalse(os.path.exists(ifname))
720 self.assertFalse(os.path.exists(ofname))
721 self.assertFalse(os.path.exists(efname))
722
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200723 def test_communicate_epipe(self):
724 # Issue 10963: communicate() should hide EPIPE
725 p = subprocess.Popen([sys.executable, "-c", 'pass'],
726 stdin=subprocess.PIPE,
727 stdout=subprocess.PIPE,
728 stderr=subprocess.PIPE)
729 self.addCleanup(p.stdout.close)
730 self.addCleanup(p.stderr.close)
731 self.addCleanup(p.stdin.close)
732 p.communicate(b"x" * 2**20)
733
734 def test_communicate_epipe_only_stdin(self):
735 # Issue 10963: communicate() should hide EPIPE
736 p = subprocess.Popen([sys.executable, "-c", 'pass'],
737 stdin=subprocess.PIPE)
738 self.addCleanup(p.stdin.close)
739 time.sleep(2)
740 p.communicate(b"x" * 2**20)
741
Tim Peterse718f612004-10-12 21:51:32 +0000742
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000743# context manager
744class _SuppressCoreFiles(object):
745 """Try to prevent core files from being created."""
746 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000747
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000748 def __enter__(self):
749 """Try to save previous ulimit, then set it to (0, 0)."""
750 try:
751 import resource
752 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
753 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
754 except (ImportError, ValueError, resource.error):
755 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000756
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000757 if sys.platform == 'darwin':
758 # Check if the 'Crash Reporter' on OSX was configured
759 # in 'Developer' mode and warn that it will get triggered
760 # when it is.
761 #
762 # This assumes that this context manager is used in tests
763 # that might trigger the next manager.
764 value = subprocess.Popen(['/usr/bin/defaults', 'read',
765 'com.apple.CrashReporter', 'DialogType'],
766 stdout=subprocess.PIPE).communicate()[0]
767 if value.strip() == b'developer':
768 print("this tests triggers the Crash Reporter, "
769 "that is intentional", end='')
770 sys.stdout.flush()
771
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000772 def __exit__(self, *args):
773 """Return core file behavior to default."""
774 if self.old_limit is None:
775 return
776 try:
777 import resource
778 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
779 except (ImportError, ValueError, resource.error):
780 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000781
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000782
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000783@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000784class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000785
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000786 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000787 nonexistent_dir = "/_this/pa.th/does/not/exist"
788 try:
789 os.chdir(nonexistent_dir)
790 except OSError as e:
791 # This avoids hard coding the errno value or the OS perror()
792 # string and instead capture the exception that we want to see
793 # below for comparison.
794 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000795 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000796 else:
797 self.fail("chdir to nonexistant directory %s succeeded." %
798 nonexistent_dir)
799
800 # Error in the child re-raised in the parent.
801 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000802 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000803 cwd=nonexistent_dir)
804 except OSError as e:
805 # Test that the child process chdir failure actually makes
806 # it up to the parent process as the correct exception.
807 self.assertEqual(desired_exception.errno, e.errno)
808 self.assertEqual(desired_exception.strerror, e.strerror)
809 else:
810 self.fail("Expected OSError: %s" % desired_exception)
811
812 def test_restore_signals(self):
813 # Code coverage for both values of restore_signals to make sure it
814 # at least does not blow up.
815 # A test for behavior would be complex. Contributions welcome.
816 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
817 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
818
819 def test_start_new_session(self):
820 # For code coverage of calling setsid(). We don't care if we get an
821 # EPERM error from it depending on the test execution environment, that
822 # still indicates that it was called.
823 try:
824 output = subprocess.check_output(
825 [sys.executable, "-c",
826 "import os; print(os.getpgid(os.getpid()))"],
827 start_new_session=True)
828 except OSError as e:
829 if e.errno != errno.EPERM:
830 raise
831 else:
832 parent_pgid = os.getpgid(os.getpid())
833 child_pgid = int(output)
834 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000835
836 def test_run_abort(self):
837 # returncode handles signal termination
838 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000839 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000840 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000841 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000842 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000844 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000845 # DISCLAIMER: Setting environment variables is *not* a good use
846 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000847 p = subprocess.Popen([sys.executable, "-c",
848 'import sys,os;'
849 'sys.stdout.write(os.getenv("FRUIT"))'],
850 stdout=subprocess.PIPE,
851 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000852 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000853 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000854
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000855 def test_preexec_exception(self):
856 def raise_it():
857 raise ValueError("What if two swallows carried a coconut?")
858 try:
859 p = subprocess.Popen([sys.executable, "-c", ""],
860 preexec_fn=raise_it)
861 except RuntimeError as e:
862 self.assertTrue(
863 subprocess._posixsubprocess,
864 "Expected a ValueError from the preexec_fn")
865 except ValueError as e:
866 self.assertIn("coconut", e.args[0])
867 else:
868 self.fail("Exception raised by preexec_fn did not make it "
869 "to the parent process.")
870
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000871 @unittest.skipUnless(gc, "Requires a gc module.")
872 def test_preexec_gc_module_failure(self):
873 # This tests the code that disables garbage collection if the child
874 # process will execute any Python.
875 def raise_runtime_error():
876 raise RuntimeError("this shouldn't escape")
877 enabled = gc.isenabled()
878 orig_gc_disable = gc.disable
879 orig_gc_isenabled = gc.isenabled
880 try:
881 gc.disable()
882 self.assertFalse(gc.isenabled())
883 subprocess.call([sys.executable, '-c', ''],
884 preexec_fn=lambda: None)
885 self.assertFalse(gc.isenabled(),
886 "Popen enabled gc when it shouldn't.")
887
888 gc.enable()
889 self.assertTrue(gc.isenabled())
890 subprocess.call([sys.executable, '-c', ''],
891 preexec_fn=lambda: None)
892 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
893
894 gc.disable = raise_runtime_error
895 self.assertRaises(RuntimeError, subprocess.Popen,
896 [sys.executable, '-c', ''],
897 preexec_fn=lambda: None)
898
899 del gc.isenabled # force an AttributeError
900 self.assertRaises(AttributeError, subprocess.Popen,
901 [sys.executable, '-c', ''],
902 preexec_fn=lambda: None)
903 finally:
904 gc.disable = orig_gc_disable
905 gc.isenabled = orig_gc_isenabled
906 if not enabled:
907 gc.disable()
908
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000909 def test_args_string(self):
910 # args is a string
911 fd, fname = mkstemp()
912 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000913 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000914 fobj.write("#!/bin/sh\n")
915 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
916 sys.executable)
917 os.chmod(fname, 0o700)
918 p = subprocess.Popen(fname)
919 p.wait()
920 os.remove(fname)
921 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000922
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000923 def test_invalid_args(self):
924 # invalid arguments should raise ValueError
925 self.assertRaises(ValueError, subprocess.call,
926 [sys.executable, "-c",
927 "import sys; sys.exit(47)"],
928 startupinfo=47)
929 self.assertRaises(ValueError, subprocess.call,
930 [sys.executable, "-c",
931 "import sys; sys.exit(47)"],
932 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000933
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000934 def test_shell_sequence(self):
935 # Run command through the shell (sequence)
936 newenv = os.environ.copy()
937 newenv["FRUIT"] = "apple"
938 p = subprocess.Popen(["echo $FRUIT"], shell=1,
939 stdout=subprocess.PIPE,
940 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000941 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000942 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000943
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000944 def test_shell_string(self):
945 # Run command through the shell (string)
946 newenv = os.environ.copy()
947 newenv["FRUIT"] = "apple"
948 p = subprocess.Popen("echo $FRUIT", shell=1,
949 stdout=subprocess.PIPE,
950 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000951 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000952 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000953
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000954 def test_call_string(self):
955 # call() function with string argument on UNIX
956 fd, fname = mkstemp()
957 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000958 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000959 fobj.write("#!/bin/sh\n")
960 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
961 sys.executable)
962 os.chmod(fname, 0o700)
963 rc = subprocess.call(fname)
964 os.remove(fname)
965 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000966
Stefan Krah9542cc62010-07-19 14:20:53 +0000967 def test_specific_shell(self):
968 # Issue #9265: Incorrect name passed as arg[0].
969 shells = []
970 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
971 for name in ['bash', 'ksh']:
972 sh = os.path.join(prefix, name)
973 if os.path.isfile(sh):
974 shells.append(sh)
975 if not shells: # Will probably work for any shell but csh.
976 self.skipTest("bash or ksh required for this test")
977 sh = '/bin/sh'
978 if os.path.isfile(sh) and not os.path.islink(sh):
979 # Test will fail if /bin/sh is a symlink to csh.
980 shells.append(sh)
981 for sh in shells:
982 p = subprocess.Popen("echo $0", executable=sh, shell=True,
983 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000984 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000985 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
986
Florent Xicluna4886d242010-03-08 13:27:26 +0000987 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000988 # Do not inherit file handles from the parent.
989 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000990 p = subprocess.Popen([sys.executable, "-c", """if 1:
991 import sys, time
992 sys.stdout.write('x\\n')
993 sys.stdout.flush()
994 time.sleep(30)
995 """],
996 close_fds=True,
997 stdin=subprocess.PIPE,
998 stdout=subprocess.PIPE,
999 stderr=subprocess.PIPE)
1000 # Wait for the interpreter to be completely initialized before
1001 # sending any signal.
1002 p.stdout.read(1)
1003 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001004 return p
1005
1006 def test_send_signal(self):
1007 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001008 _, stderr = p.communicate()
1009 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001010 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001011
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001012 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001013 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001014 _, stderr = p.communicate()
1015 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001016 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001017
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001018 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001019 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001020 _, stderr = p.communicate()
1021 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001022 self.assertEqual(p.wait(), -signal.SIGTERM)
1023
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001024 def check_close_std_fds(self, fds):
1025 # Issue #9905: test that subprocess pipes still work properly with
1026 # some standard fds closed
1027 stdin = 0
1028 newfds = []
1029 for a in fds:
1030 b = os.dup(a)
1031 newfds.append(b)
1032 if a == 0:
1033 stdin = b
1034 try:
1035 for fd in fds:
1036 os.close(fd)
1037 out, err = subprocess.Popen([sys.executable, "-c",
1038 'import sys;'
1039 'sys.stdout.write("apple");'
1040 'sys.stdout.flush();'
1041 'sys.stderr.write("orange")'],
1042 stdin=stdin,
1043 stdout=subprocess.PIPE,
1044 stderr=subprocess.PIPE).communicate()
1045 err = support.strip_python_stderr(err)
1046 self.assertEqual((out, err), (b'apple', b'orange'))
1047 finally:
1048 for b, a in zip(newfds, fds):
1049 os.dup2(b, a)
1050 for b in newfds:
1051 os.close(b)
1052
1053 def test_close_fd_0(self):
1054 self.check_close_std_fds([0])
1055
1056 def test_close_fd_1(self):
1057 self.check_close_std_fds([1])
1058
1059 def test_close_fd_2(self):
1060 self.check_close_std_fds([2])
1061
1062 def test_close_fds_0_1(self):
1063 self.check_close_std_fds([0, 1])
1064
1065 def test_close_fds_0_2(self):
1066 self.check_close_std_fds([0, 2])
1067
1068 def test_close_fds_1_2(self):
1069 self.check_close_std_fds([1, 2])
1070
1071 def test_close_fds_0_1_2(self):
1072 # Issue #10806: test that subprocess pipes still work properly with
1073 # all standard fds closed.
1074 self.check_close_std_fds([0, 1, 2])
1075
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001076 def test_remapping_std_fds(self):
1077 # open up some temporary files
1078 temps = [mkstemp() for i in range(3)]
1079 try:
1080 temp_fds = [fd for fd, fname in temps]
1081
1082 # unlink the files -- we won't need to reopen them
1083 for fd, fname in temps:
1084 os.unlink(fname)
1085
1086 # write some data to what will become stdin, and rewind
1087 os.write(temp_fds[1], b"STDIN")
1088 os.lseek(temp_fds[1], 0, 0)
1089
1090 # move the standard file descriptors out of the way
1091 saved_fds = [os.dup(fd) for fd in range(3)]
1092 try:
1093 # duplicate the file objects over the standard fd's
1094 for fd, temp_fd in enumerate(temp_fds):
1095 os.dup2(temp_fd, fd)
1096
1097 # now use those files in the "wrong" order, so that subprocess
1098 # has to rearrange them in the child
1099 p = subprocess.Popen([sys.executable, "-c",
1100 'import sys; got = sys.stdin.read();'
1101 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1102 stdin=temp_fds[1],
1103 stdout=temp_fds[2],
1104 stderr=temp_fds[0])
1105 p.wait()
1106 finally:
1107 # restore the original fd's underneath sys.stdin, etc.
1108 for std, saved in enumerate(saved_fds):
1109 os.dup2(saved, std)
1110 os.close(saved)
1111
1112 for fd in temp_fds:
1113 os.lseek(fd, 0, 0)
1114
1115 out = os.read(temp_fds[2], 1024)
1116 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1117 self.assertEqual(out, b"got STDIN")
1118 self.assertEqual(err, b"err")
1119
1120 finally:
1121 for fd in temp_fds:
1122 os.close(fd)
1123
Victor Stinner13bb71c2010-04-23 21:41:56 +00001124 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001125 def prepare():
1126 raise ValueError("surrogate:\uDCff")
1127
1128 try:
1129 subprocess.call(
1130 [sys.executable, "-c", "pass"],
1131 preexec_fn=prepare)
1132 except ValueError as err:
1133 # Pure Python implementations keeps the message
1134 self.assertIsNone(subprocess._posixsubprocess)
1135 self.assertEqual(str(err), "surrogate:\uDCff")
1136 except RuntimeError as err:
1137 # _posixsubprocess uses a default message
1138 self.assertIsNotNone(subprocess._posixsubprocess)
1139 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1140 else:
1141 self.fail("Expected ValueError or RuntimeError")
1142
Victor Stinner13bb71c2010-04-23 21:41:56 +00001143 def test_undecodable_env(self):
1144 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001145 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001146 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001147 env = os.environ.copy()
1148 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001149 # Use C locale to get ascii for the locale encoding to force
1150 # surrogate-escaping of \xFF in the child process; otherwise it can
1151 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001152 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001153 stdout = subprocess.check_output(
1154 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001155 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001156 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001157 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001158
1159 # test bytes
1160 key = key.encode("ascii", "surrogateescape")
1161 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001162 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001163 env = os.environ.copy()
1164 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001165 stdout = subprocess.check_output(
1166 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001167 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001168 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001169 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001170
Victor Stinnerb745a742010-05-18 17:17:23 +00001171 def test_bytes_program(self):
1172 abs_program = os.fsencode(sys.executable)
1173 path, program = os.path.split(sys.executable)
1174 program = os.fsencode(program)
1175
1176 # absolute bytes path
1177 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001178 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001179
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001180 # absolute bytes path as a string
1181 cmd = b"'" + abs_program + b"' -c pass"
1182 exitcode = subprocess.call(cmd, shell=True)
1183 self.assertEqual(exitcode, 0)
1184
Victor Stinnerb745a742010-05-18 17:17:23 +00001185 # bytes program, unicode PATH
1186 env = os.environ.copy()
1187 env["PATH"] = path
1188 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001189 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001190
1191 # bytes program, bytes PATH
1192 envb = os.environb.copy()
1193 envb[b"PATH"] = os.fsencode(path)
1194 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001195 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001196
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001197 def test_pipe_cloexec(self):
1198 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1199 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1200
1201 p1 = subprocess.Popen([sys.executable, sleeper],
1202 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1203 stderr=subprocess.PIPE, close_fds=False)
1204
1205 self.addCleanup(p1.communicate, b'')
1206
1207 p2 = subprocess.Popen([sys.executable, fd_status],
1208 stdout=subprocess.PIPE, close_fds=False)
1209
1210 output, error = p2.communicate()
1211 result_fds = set(map(int, output.split(b',')))
1212 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1213 p1.stderr.fileno()])
1214
1215 self.assertFalse(result_fds & unwanted_fds,
1216 "Expected no fds from %r to be open in child, "
1217 "found %r" %
1218 (unwanted_fds, result_fds & unwanted_fds))
1219
1220 def test_pipe_cloexec_real_tools(self):
1221 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1222 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1223
1224 subdata = b'zxcvbn'
1225 data = subdata * 4 + b'\n'
1226
1227 p1 = subprocess.Popen([sys.executable, qcat],
1228 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1229 close_fds=False)
1230
1231 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1232 stdin=p1.stdout, stdout=subprocess.PIPE,
1233 close_fds=False)
1234
1235 self.addCleanup(p1.wait)
1236 self.addCleanup(p2.wait)
1237 self.addCleanup(p1.terminate)
1238 self.addCleanup(p2.terminate)
1239
1240 p1.stdin.write(data)
1241 p1.stdin.close()
1242
1243 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1244
1245 self.assertTrue(readfiles, "The child hung")
1246 self.assertEqual(p2.stdout.read(), data)
1247
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001248 p1.stdout.close()
1249 p2.stdout.close()
1250
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001251 def test_close_fds(self):
1252 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1253
1254 fds = os.pipe()
1255 self.addCleanup(os.close, fds[0])
1256 self.addCleanup(os.close, fds[1])
1257
1258 open_fds = set(fds)
1259
1260 p = subprocess.Popen([sys.executable, fd_status],
1261 stdout=subprocess.PIPE, close_fds=False)
1262 output, ignored = p.communicate()
1263 remaining_fds = set(map(int, output.split(b',')))
1264
1265 self.assertEqual(remaining_fds & open_fds, open_fds,
1266 "Some fds were closed")
1267
1268 p = subprocess.Popen([sys.executable, fd_status],
1269 stdout=subprocess.PIPE, close_fds=True)
1270 output, ignored = p.communicate()
1271 remaining_fds = set(map(int, output.split(b',')))
1272
1273 self.assertFalse(remaining_fds & open_fds,
1274 "Some fds were left open")
1275 self.assertIn(1, remaining_fds, "Subprocess failed")
1276
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001277 def test_pass_fds(self):
1278 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1279
1280 open_fds = set()
1281
1282 for x in range(5):
1283 fds = os.pipe()
1284 self.addCleanup(os.close, fds[0])
1285 self.addCleanup(os.close, fds[1])
1286 open_fds.update(fds)
1287
1288 for fd in open_fds:
1289 p = subprocess.Popen([sys.executable, fd_status],
1290 stdout=subprocess.PIPE, close_fds=True,
1291 pass_fds=(fd, ))
1292 output, ignored = p.communicate()
1293
1294 remaining_fds = set(map(int, output.split(b',')))
1295 to_be_closed = open_fds - {fd}
1296
1297 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1298 self.assertFalse(remaining_fds & to_be_closed,
1299 "fd to be closed passed")
1300
1301 # pass_fds overrides close_fds with a warning.
1302 with self.assertWarns(RuntimeWarning) as context:
1303 self.assertFalse(subprocess.call(
1304 [sys.executable, "-c", "import sys; sys.exit(0)"],
1305 close_fds=False, pass_fds=(fd, )))
1306 self.assertIn('overriding close_fds', str(context.warning))
1307
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001308 def test_stdout_stdin_are_single_inout_fd(self):
1309 with io.open(os.devnull, "r+") as inout:
1310 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1311 stdout=inout, stdin=inout)
1312 p.wait()
1313
1314 def test_stdout_stderr_are_single_inout_fd(self):
1315 with io.open(os.devnull, "r+") as inout:
1316 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1317 stdout=inout, stderr=inout)
1318 p.wait()
1319
1320 def test_stderr_stdin_are_single_inout_fd(self):
1321 with io.open(os.devnull, "r+") as inout:
1322 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1323 stderr=inout, stdin=inout)
1324 p.wait()
1325
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001326 def test_wait_when_sigchild_ignored(self):
1327 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1328 sigchild_ignore = support.findfile("sigchild_ignore.py",
1329 subdir="subprocessdata")
1330 p = subprocess.Popen([sys.executable, sigchild_ignore],
1331 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1332 stdout, stderr = p.communicate()
1333 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001334 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001335 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001336
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001337 def test_select_unbuffered(self):
1338 # Issue #11459: bufsize=0 should really set the pipes as
1339 # unbuffered (and therefore let select() work properly).
1340 select = support.import_module("select")
1341 p = subprocess.Popen([sys.executable, "-c",
1342 'import sys;'
1343 'sys.stdout.write("apple")'],
1344 stdout=subprocess.PIPE,
1345 bufsize=0)
1346 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001347 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001348 try:
1349 self.assertEqual(f.read(4), b"appl")
1350 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1351 finally:
1352 p.wait()
1353
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001354
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001355@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001356class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001357
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001358 def test_startupinfo(self):
1359 # startupinfo argument
1360 # We uses hardcoded constants, because we do not want to
1361 # depend on win32all.
1362 STARTF_USESHOWWINDOW = 1
1363 SW_MAXIMIZE = 3
1364 startupinfo = subprocess.STARTUPINFO()
1365 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1366 startupinfo.wShowWindow = SW_MAXIMIZE
1367 # Since Python is a console process, it won't be affected
1368 # by wShowWindow, but the argument should be silently
1369 # ignored
1370 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001371 startupinfo=startupinfo)
1372
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001373 def test_creationflags(self):
1374 # creationflags argument
1375 CREATE_NEW_CONSOLE = 16
1376 sys.stderr.write(" a DOS box should flash briefly ...\n")
1377 subprocess.call(sys.executable +
1378 ' -c "import time; time.sleep(0.25)"',
1379 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001380
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001381 def test_invalid_args(self):
1382 # invalid arguments should raise ValueError
1383 self.assertRaises(ValueError, subprocess.call,
1384 [sys.executable, "-c",
1385 "import sys; sys.exit(47)"],
1386 preexec_fn=lambda: 1)
1387 self.assertRaises(ValueError, subprocess.call,
1388 [sys.executable, "-c",
1389 "import sys; sys.exit(47)"],
1390 stdout=subprocess.PIPE,
1391 close_fds=True)
1392
1393 def test_close_fds(self):
1394 # close file descriptors
1395 rc = subprocess.call([sys.executable, "-c",
1396 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001397 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001398 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001399
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001400 def test_shell_sequence(self):
1401 # Run command through the shell (sequence)
1402 newenv = os.environ.copy()
1403 newenv["FRUIT"] = "physalis"
1404 p = subprocess.Popen(["set"], shell=1,
1405 stdout=subprocess.PIPE,
1406 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001407 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001408 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001409
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001410 def test_shell_string(self):
1411 # Run command through the shell (string)
1412 newenv = os.environ.copy()
1413 newenv["FRUIT"] = "physalis"
1414 p = subprocess.Popen("set", shell=1,
1415 stdout=subprocess.PIPE,
1416 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001417 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001418 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001419
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001420 def test_call_string(self):
1421 # call() function with string argument on Windows
1422 rc = subprocess.call(sys.executable +
1423 ' -c "import sys; sys.exit(47)"')
1424 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001425
Florent Xicluna4886d242010-03-08 13:27:26 +00001426 def _kill_process(self, method, *args):
1427 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001428 p = subprocess.Popen([sys.executable, "-c", """if 1:
1429 import sys, time
1430 sys.stdout.write('x\\n')
1431 sys.stdout.flush()
1432 time.sleep(30)
1433 """],
1434 stdin=subprocess.PIPE,
1435 stdout=subprocess.PIPE,
1436 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001437 self.addCleanup(p.stdout.close)
1438 self.addCleanup(p.stderr.close)
1439 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001440 # Wait for the interpreter to be completely initialized before
1441 # sending any signal.
1442 p.stdout.read(1)
1443 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001444 _, stderr = p.communicate()
1445 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001446 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001447 self.assertNotEqual(returncode, 0)
1448
1449 def test_send_signal(self):
1450 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001451
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001452 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001453 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001454
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001455 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001456 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001457
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001458
Brett Cannona23810f2008-05-26 19:04:21 +00001459# The module says:
1460# "NB This only works (and is only relevant) for UNIX."
1461#
1462# Actually, getoutput should work on any platform with an os.popen, but
1463# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001464@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001465class CommandTests(unittest.TestCase):
1466 def test_getoutput(self):
1467 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1468 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1469 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001470
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001471 # we use mkdtemp in the next line to create an empty directory
1472 # under our exclusive control; from that, we can invent a pathname
1473 # that we _know_ won't exist. This is guaranteed to fail.
1474 dir = None
1475 try:
1476 dir = tempfile.mkdtemp()
1477 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001478
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001479 status, output = subprocess.getstatusoutput('cat ' + name)
1480 self.assertNotEqual(status, 0)
1481 finally:
1482 if dir is not None:
1483 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001484
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001485
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001486@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1487 "poll system call not supported")
1488class ProcessTestCaseNoPoll(ProcessTestCase):
1489 def setUp(self):
1490 subprocess._has_poll = False
1491 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001492
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001493 def tearDown(self):
1494 subprocess._has_poll = True
1495 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001496
1497
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001498@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1499 "_posixsubprocess extension module not found.")
1500class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
1501 def setUp(self):
1502 subprocess._posixsubprocess = None
1503 ProcessTestCase.setUp(self)
1504 POSIXProcessTestCase.setUp(self)
1505
1506 def tearDown(self):
1507 subprocess._posixsubprocess = sys.modules['_posixsubprocess']
1508 POSIXProcessTestCase.tearDown(self)
1509 ProcessTestCase.tearDown(self)
1510
1511
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001512class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001513 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001514 def test_eintr_retry_call(self):
1515 record_calls = []
1516 def fake_os_func(*args):
1517 record_calls.append(args)
1518 if len(record_calls) == 2:
1519 raise OSError(errno.EINTR, "fake interrupted system call")
1520 return tuple(reversed(args))
1521
1522 self.assertEqual((999, 256),
1523 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1524 self.assertEqual([(256, 999)], record_calls)
1525 # This time there will be an EINTR so it will loop once.
1526 self.assertEqual((666,),
1527 subprocess._eintr_retry_call(fake_os_func, 666))
1528 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1529
1530
Tim Golden126c2962010-08-11 14:20:40 +00001531@unittest.skipUnless(mswindows, "Windows-specific tests")
1532class CommandsWithSpaces (BaseTestCase):
1533
1534 def setUp(self):
1535 super().setUp()
1536 f, fname = mkstemp(".py", "te st")
1537 self.fname = fname.lower ()
1538 os.write(f, b"import sys;"
1539 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1540 )
1541 os.close(f)
1542
1543 def tearDown(self):
1544 os.remove(self.fname)
1545 super().tearDown()
1546
1547 def with_spaces(self, *args, **kwargs):
1548 kwargs['stdout'] = subprocess.PIPE
1549 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001550 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001551 self.assertEqual(
1552 p.stdout.read ().decode("mbcs"),
1553 "2 [%r, 'ab cd']" % self.fname
1554 )
1555
1556 def test_shell_string_with_spaces(self):
1557 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001558 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1559 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001560
1561 def test_shell_sequence_with_spaces(self):
1562 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001563 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001564
1565 def test_noshell_string_with_spaces(self):
1566 # call() function with string argument with spaces on Windows
1567 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1568 "ab cd"))
1569
1570 def test_noshell_sequence_with_spaces(self):
1571 # call() function with sequence argument with spaces on Windows
1572 self.with_spaces([sys.executable, self.fname, "ab cd"])
1573
Brian Curtin79cdb662010-12-03 02:46:02 +00001574
1575class ContextManagerTests(ProcessTestCase):
1576
1577 def test_pipe(self):
1578 with subprocess.Popen([sys.executable, "-c",
1579 "import sys;"
1580 "sys.stdout.write('stdout');"
1581 "sys.stderr.write('stderr');"],
1582 stdout=subprocess.PIPE,
1583 stderr=subprocess.PIPE) as proc:
1584 self.assertEqual(proc.stdout.read(), b"stdout")
1585 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1586
1587 self.assertTrue(proc.stdout.closed)
1588 self.assertTrue(proc.stderr.closed)
1589
1590 def test_returncode(self):
1591 with subprocess.Popen([sys.executable, "-c",
1592 "import sys; sys.exit(100)"]) as proc:
1593 proc.wait()
1594 self.assertEqual(proc.returncode, 100)
1595
1596 def test_communicate_stdin(self):
1597 with subprocess.Popen([sys.executable, "-c",
1598 "import sys;"
1599 "sys.exit(sys.stdin.read() == 'context')"],
1600 stdin=subprocess.PIPE) as proc:
1601 proc.communicate(b"context")
1602 self.assertEqual(proc.returncode, 1)
1603
1604 def test_invalid_args(self):
1605 with self.assertRaises(EnvironmentError) as c:
1606 with subprocess.Popen(['nonexisting_i_hope'],
1607 stdout=subprocess.PIPE,
1608 stderr=subprocess.PIPE) as proc:
1609 pass
1610
1611 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1612 raise c.exception
1613
1614
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001615def test_main():
1616 unit_tests = (ProcessTestCase,
1617 POSIXProcessTestCase,
1618 Win32ProcessTestCase,
1619 ProcessTestCasePOSIXPurePython,
1620 CommandTests,
1621 ProcessTestCaseNoPoll,
1622 HelperFunctionTests,
1623 CommandsWithSpaces,
1624 ContextManagerTests)
1625
1626 support.run_unittest(*unit_tests)
1627 support.reap_children()
1628
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001629if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001630 unittest.main()