blob: 686c1b14c9dc6bd5d0248664944f15b6ae784cca [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()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492 os.close(x)
493 os.close(y)
494 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000495 'import sys,os;'
496 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200497 'sys.stderr.write("x" * %d);'
498 'sys.stdout.write(sys.stdin.read())' %
499 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000500 stdin=subprocess.PIPE,
501 stdout=subprocess.PIPE,
502 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000503 self.addCleanup(p.stdout.close)
504 self.addCleanup(p.stderr.close)
505 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200506 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507 (stdout, stderr) = p.communicate(string_to_write)
508 self.assertEqual(stdout, string_to_write)
509
510 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000511 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000513 'import sys,os;'
514 'sys.stdout.write(sys.stdin.read())'],
515 stdin=subprocess.PIPE,
516 stdout=subprocess.PIPE,
517 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000518 self.addCleanup(p.stdout.close)
519 self.addCleanup(p.stderr.close)
520 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000521 p.stdin.write(b"banana")
522 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000523 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000524 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000525
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000528 'import sys,os;' + SETBINARY +
529 'sys.stdout.write("line1\\n");'
530 'sys.stdout.flush();'
531 'sys.stdout.write("line2\\n");'
532 'sys.stdout.flush();'
533 'sys.stdout.write("line3\\r\\n");'
534 'sys.stdout.flush();'
535 'sys.stdout.write("line4\\r");'
536 'sys.stdout.flush();'
537 'sys.stdout.write("\\nline5");'
538 'sys.stdout.flush();'
539 'sys.stdout.write("\\nline6");'],
540 stdout=subprocess.PIPE,
541 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000542 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000544 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545
546 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000547 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000549 'import sys,os;' + SETBINARY +
550 'sys.stdout.write("line1\\n");'
551 'sys.stdout.flush();'
552 'sys.stdout.write("line2\\n");'
553 'sys.stdout.flush();'
554 'sys.stdout.write("line3\\r\\n");'
555 'sys.stdout.flush();'
556 'sys.stdout.write("line4\\r");'
557 'sys.stdout.flush();'
558 'sys.stdout.write("\\nline5");'
559 'sys.stdout.flush();'
560 'sys.stdout.write("\\nline6");'],
561 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
562 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000563 self.addCleanup(p.stdout.close)
564 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000566 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000567
568 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000569 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000570 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000571 max_handles = 1026 # too much for most UNIX systems
572 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000573 max_handles = 2050 # too much for (at least some) Windows setups
574 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400575 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000576 try:
577 for i in range(max_handles):
578 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400579 tmpfile = os.path.join(tmpdir, support.TESTFN)
580 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000581 except OSError as e:
582 if e.errno != errno.EMFILE:
583 raise
584 break
585 else:
586 self.skipTest("failed to reach the file descriptor limit "
587 "(tried %d)" % max_handles)
588 # Close a couple of them (should be enough for a subprocess)
589 for i in range(10):
590 os.close(handles.pop())
591 # Loop creating some subprocesses. If one of them leaks some fds,
592 # the next loop iteration will fail by reaching the max fd limit.
593 for i in range(15):
594 p = subprocess.Popen([sys.executable, "-c",
595 "import sys;"
596 "sys.stdout.write(sys.stdin.read())"],
597 stdin=subprocess.PIPE,
598 stdout=subprocess.PIPE,
599 stderr=subprocess.PIPE)
600 data = p.communicate(b"lime")[0]
601 self.assertEqual(data, b"lime")
602 finally:
603 for h in handles:
604 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400605 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000606
607 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000608 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
609 '"a b c" d e')
610 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
611 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000612 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
613 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000614 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
615 'a\\\\\\b "de fg" h')
616 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
617 'a\\\\\\"b c d')
618 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
619 '"a\\\\b c" d e')
620 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
621 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000622 self.assertEqual(subprocess.list2cmdline(['ab', '']),
623 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624
625
626 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000627 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000628 "-c", "import time; time.sleep(1)"])
629 count = 0
630 while p.poll() is None:
631 time.sleep(0.1)
632 count += 1
633 # We expect that the poll loop probably went around about 10 times,
634 # but, based on system scheduling we can't control, it's possible
635 # poll() never returned None. It "should be" very rare that it
636 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000637 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000638 # Subsequent invocations should just return the returncode
639 self.assertEqual(p.poll(), 0)
640
641
642 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643 p = subprocess.Popen([sys.executable,
644 "-c", "import time; time.sleep(2)"])
645 self.assertEqual(p.wait(), 0)
646 # Subsequent invocations should just return the returncode
647 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000648
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400649 def test_wait_timeout(self):
650 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400651 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400652 with self.assertRaises(subprocess.TimeoutExpired) as c:
653 p.wait(timeout=0.01)
654 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400655 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
656 # time to start.
657 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400658
Peter Astrand738131d2004-11-30 21:04:45 +0000659 def test_invalid_bufsize(self):
660 # an invalid type of the bufsize argument should raise
661 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000662 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000663 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000664
Guido van Rossum46a05a72007-06-07 21:56:45 +0000665 def test_bufsize_is_none(self):
666 # bufsize=None should be the same as bufsize=0.
667 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
668 self.assertEqual(p.wait(), 0)
669 # Again with keyword arg
670 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
671 self.assertEqual(p.wait(), 0)
672
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000673 def test_leaking_fds_on_error(self):
674 # see bug #5179: Popen leaks file descriptors to PIPEs if
675 # the child fails to execute; this will eventually exhaust
676 # the maximum number of open fds. 1024 seems a very common
677 # value for that limit, but Windows has 2048, so we loop
678 # 1024 times (each call leaked two fds).
679 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000680 # Windows raises IOError. Others raise OSError.
681 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000682 subprocess.Popen(['nonexisting_i_hope'],
683 stdout=subprocess.PIPE,
684 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400685 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400686 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000687 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000688
Victor Stinnerb3693582010-05-21 20:13:12 +0000689 def test_issue8780(self):
690 # Ensure that stdout is inherited from the parent
691 # if stdout=PIPE is not used
692 code = ';'.join((
693 'import subprocess, sys',
694 'retcode = subprocess.call('
695 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
696 'assert retcode == 0'))
697 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000698 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000699
Tim Goldenaf5ac392010-08-06 13:03:56 +0000700 def test_handles_closed_on_exception(self):
701 # If CreateProcess exits with an error, ensure the
702 # duplicate output handles are released
703 ifhandle, ifname = mkstemp()
704 ofhandle, ofname = mkstemp()
705 efhandle, efname = mkstemp()
706 try:
707 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
708 stderr=efhandle)
709 except OSError:
710 os.close(ifhandle)
711 os.remove(ifname)
712 os.close(ofhandle)
713 os.remove(ofname)
714 os.close(efhandle)
715 os.remove(efname)
716 self.assertFalse(os.path.exists(ifname))
717 self.assertFalse(os.path.exists(ofname))
718 self.assertFalse(os.path.exists(efname))
719
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200720 def test_communicate_epipe(self):
721 # Issue 10963: communicate() should hide EPIPE
722 p = subprocess.Popen([sys.executable, "-c", 'pass'],
723 stdin=subprocess.PIPE,
724 stdout=subprocess.PIPE,
725 stderr=subprocess.PIPE)
726 self.addCleanup(p.stdout.close)
727 self.addCleanup(p.stderr.close)
728 self.addCleanup(p.stdin.close)
729 p.communicate(b"x" * 2**20)
730
731 def test_communicate_epipe_only_stdin(self):
732 # Issue 10963: communicate() should hide EPIPE
733 p = subprocess.Popen([sys.executable, "-c", 'pass'],
734 stdin=subprocess.PIPE)
735 self.addCleanup(p.stdin.close)
736 time.sleep(2)
737 p.communicate(b"x" * 2**20)
738
Tim Peterse718f612004-10-12 21:51:32 +0000739
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000740# context manager
741class _SuppressCoreFiles(object):
742 """Try to prevent core files from being created."""
743 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000744
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000745 def __enter__(self):
746 """Try to save previous ulimit, then set it to (0, 0)."""
747 try:
748 import resource
749 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
750 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
751 except (ImportError, ValueError, resource.error):
752 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000753
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000754 if sys.platform == 'darwin':
755 # Check if the 'Crash Reporter' on OSX was configured
756 # in 'Developer' mode and warn that it will get triggered
757 # when it is.
758 #
759 # This assumes that this context manager is used in tests
760 # that might trigger the next manager.
761 value = subprocess.Popen(['/usr/bin/defaults', 'read',
762 'com.apple.CrashReporter', 'DialogType'],
763 stdout=subprocess.PIPE).communicate()[0]
764 if value.strip() == b'developer':
765 print("this tests triggers the Crash Reporter, "
766 "that is intentional", end='')
767 sys.stdout.flush()
768
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000769 def __exit__(self, *args):
770 """Return core file behavior to default."""
771 if self.old_limit is None:
772 return
773 try:
774 import resource
775 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
776 except (ImportError, ValueError, resource.error):
777 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000778
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000779
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000780@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000781class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000782
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000783 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000784 nonexistent_dir = "/_this/pa.th/does/not/exist"
785 try:
786 os.chdir(nonexistent_dir)
787 except OSError as e:
788 # This avoids hard coding the errno value or the OS perror()
789 # string and instead capture the exception that we want to see
790 # below for comparison.
791 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000792 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000793 else:
794 self.fail("chdir to nonexistant directory %s succeeded." %
795 nonexistent_dir)
796
797 # Error in the child re-raised in the parent.
798 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000799 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000800 cwd=nonexistent_dir)
801 except OSError as e:
802 # Test that the child process chdir failure actually makes
803 # it up to the parent process as the correct exception.
804 self.assertEqual(desired_exception.errno, e.errno)
805 self.assertEqual(desired_exception.strerror, e.strerror)
806 else:
807 self.fail("Expected OSError: %s" % desired_exception)
808
809 def test_restore_signals(self):
810 # Code coverage for both values of restore_signals to make sure it
811 # at least does not blow up.
812 # A test for behavior would be complex. Contributions welcome.
813 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
814 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
815
816 def test_start_new_session(self):
817 # For code coverage of calling setsid(). We don't care if we get an
818 # EPERM error from it depending on the test execution environment, that
819 # still indicates that it was called.
820 try:
821 output = subprocess.check_output(
822 [sys.executable, "-c",
823 "import os; print(os.getpgid(os.getpid()))"],
824 start_new_session=True)
825 except OSError as e:
826 if e.errno != errno.EPERM:
827 raise
828 else:
829 parent_pgid = os.getpgid(os.getpid())
830 child_pgid = int(output)
831 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000832
833 def test_run_abort(self):
834 # returncode handles signal termination
835 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000836 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000837 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000838 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000839 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000840
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000841 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000842 # DISCLAIMER: Setting environment variables is *not* a good use
843 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000844 p = subprocess.Popen([sys.executable, "-c",
845 'import sys,os;'
846 'sys.stdout.write(os.getenv("FRUIT"))'],
847 stdout=subprocess.PIPE,
848 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000849 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000850 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000851
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000852 def test_preexec_exception(self):
853 def raise_it():
854 raise ValueError("What if two swallows carried a coconut?")
855 try:
856 p = subprocess.Popen([sys.executable, "-c", ""],
857 preexec_fn=raise_it)
858 except RuntimeError as e:
859 self.assertTrue(
860 subprocess._posixsubprocess,
861 "Expected a ValueError from the preexec_fn")
862 except ValueError as e:
863 self.assertIn("coconut", e.args[0])
864 else:
865 self.fail("Exception raised by preexec_fn did not make it "
866 "to the parent process.")
867
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000868 @unittest.skipUnless(gc, "Requires a gc module.")
869 def test_preexec_gc_module_failure(self):
870 # This tests the code that disables garbage collection if the child
871 # process will execute any Python.
872 def raise_runtime_error():
873 raise RuntimeError("this shouldn't escape")
874 enabled = gc.isenabled()
875 orig_gc_disable = gc.disable
876 orig_gc_isenabled = gc.isenabled
877 try:
878 gc.disable()
879 self.assertFalse(gc.isenabled())
880 subprocess.call([sys.executable, '-c', ''],
881 preexec_fn=lambda: None)
882 self.assertFalse(gc.isenabled(),
883 "Popen enabled gc when it shouldn't.")
884
885 gc.enable()
886 self.assertTrue(gc.isenabled())
887 subprocess.call([sys.executable, '-c', ''],
888 preexec_fn=lambda: None)
889 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
890
891 gc.disable = raise_runtime_error
892 self.assertRaises(RuntimeError, subprocess.Popen,
893 [sys.executable, '-c', ''],
894 preexec_fn=lambda: None)
895
896 del gc.isenabled # force an AttributeError
897 self.assertRaises(AttributeError, subprocess.Popen,
898 [sys.executable, '-c', ''],
899 preexec_fn=lambda: None)
900 finally:
901 gc.disable = orig_gc_disable
902 gc.isenabled = orig_gc_isenabled
903 if not enabled:
904 gc.disable()
905
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000906 def test_args_string(self):
907 # args is a string
908 fd, fname = mkstemp()
909 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000910 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000911 fobj.write("#!/bin/sh\n")
912 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
913 sys.executable)
914 os.chmod(fname, 0o700)
915 p = subprocess.Popen(fname)
916 p.wait()
917 os.remove(fname)
918 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000920 def test_invalid_args(self):
921 # invalid arguments should raise ValueError
922 self.assertRaises(ValueError, subprocess.call,
923 [sys.executable, "-c",
924 "import sys; sys.exit(47)"],
925 startupinfo=47)
926 self.assertRaises(ValueError, subprocess.call,
927 [sys.executable, "-c",
928 "import sys; sys.exit(47)"],
929 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000930
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000931 def test_shell_sequence(self):
932 # Run command through the shell (sequence)
933 newenv = os.environ.copy()
934 newenv["FRUIT"] = "apple"
935 p = subprocess.Popen(["echo $FRUIT"], shell=1,
936 stdout=subprocess.PIPE,
937 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000938 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000939 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000941 def test_shell_string(self):
942 # Run command through the shell (string)
943 newenv = os.environ.copy()
944 newenv["FRUIT"] = "apple"
945 p = subprocess.Popen("echo $FRUIT", shell=1,
946 stdout=subprocess.PIPE,
947 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000948 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000949 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000950
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000951 def test_call_string(self):
952 # call() function with string argument on UNIX
953 fd, fname = mkstemp()
954 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000955 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000956 fobj.write("#!/bin/sh\n")
957 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
958 sys.executable)
959 os.chmod(fname, 0o700)
960 rc = subprocess.call(fname)
961 os.remove(fname)
962 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000963
Stefan Krah9542cc62010-07-19 14:20:53 +0000964 def test_specific_shell(self):
965 # Issue #9265: Incorrect name passed as arg[0].
966 shells = []
967 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
968 for name in ['bash', 'ksh']:
969 sh = os.path.join(prefix, name)
970 if os.path.isfile(sh):
971 shells.append(sh)
972 if not shells: # Will probably work for any shell but csh.
973 self.skipTest("bash or ksh required for this test")
974 sh = '/bin/sh'
975 if os.path.isfile(sh) and not os.path.islink(sh):
976 # Test will fail if /bin/sh is a symlink to csh.
977 shells.append(sh)
978 for sh in shells:
979 p = subprocess.Popen("echo $0", executable=sh, shell=True,
980 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000981 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000982 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
983
Florent Xicluna4886d242010-03-08 13:27:26 +0000984 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000985 # Do not inherit file handles from the parent.
986 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000987 p = subprocess.Popen([sys.executable, "-c", """if 1:
988 import sys, time
989 sys.stdout.write('x\\n')
990 sys.stdout.flush()
991 time.sleep(30)
992 """],
993 close_fds=True,
994 stdin=subprocess.PIPE,
995 stdout=subprocess.PIPE,
996 stderr=subprocess.PIPE)
997 # Wait for the interpreter to be completely initialized before
998 # sending any signal.
999 p.stdout.read(1)
1000 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001001 return p
1002
1003 def test_send_signal(self):
1004 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001005 _, stderr = p.communicate()
1006 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001007 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001008
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001009 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001010 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001011 _, stderr = p.communicate()
1012 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001013 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001014
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001015 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001016 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001017 _, stderr = p.communicate()
1018 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001019 self.assertEqual(p.wait(), -signal.SIGTERM)
1020
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001021 def check_close_std_fds(self, fds):
1022 # Issue #9905: test that subprocess pipes still work properly with
1023 # some standard fds closed
1024 stdin = 0
1025 newfds = []
1026 for a in fds:
1027 b = os.dup(a)
1028 newfds.append(b)
1029 if a == 0:
1030 stdin = b
1031 try:
1032 for fd in fds:
1033 os.close(fd)
1034 out, err = subprocess.Popen([sys.executable, "-c",
1035 'import sys;'
1036 'sys.stdout.write("apple");'
1037 'sys.stdout.flush();'
1038 'sys.stderr.write("orange")'],
1039 stdin=stdin,
1040 stdout=subprocess.PIPE,
1041 stderr=subprocess.PIPE).communicate()
1042 err = support.strip_python_stderr(err)
1043 self.assertEqual((out, err), (b'apple', b'orange'))
1044 finally:
1045 for b, a in zip(newfds, fds):
1046 os.dup2(b, a)
1047 for b in newfds:
1048 os.close(b)
1049
1050 def test_close_fd_0(self):
1051 self.check_close_std_fds([0])
1052
1053 def test_close_fd_1(self):
1054 self.check_close_std_fds([1])
1055
1056 def test_close_fd_2(self):
1057 self.check_close_std_fds([2])
1058
1059 def test_close_fds_0_1(self):
1060 self.check_close_std_fds([0, 1])
1061
1062 def test_close_fds_0_2(self):
1063 self.check_close_std_fds([0, 2])
1064
1065 def test_close_fds_1_2(self):
1066 self.check_close_std_fds([1, 2])
1067
1068 def test_close_fds_0_1_2(self):
1069 # Issue #10806: test that subprocess pipes still work properly with
1070 # all standard fds closed.
1071 self.check_close_std_fds([0, 1, 2])
1072
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001073 def test_remapping_std_fds(self):
1074 # open up some temporary files
1075 temps = [mkstemp() for i in range(3)]
1076 try:
1077 temp_fds = [fd for fd, fname in temps]
1078
1079 # unlink the files -- we won't need to reopen them
1080 for fd, fname in temps:
1081 os.unlink(fname)
1082
1083 # write some data to what will become stdin, and rewind
1084 os.write(temp_fds[1], b"STDIN")
1085 os.lseek(temp_fds[1], 0, 0)
1086
1087 # move the standard file descriptors out of the way
1088 saved_fds = [os.dup(fd) for fd in range(3)]
1089 try:
1090 # duplicate the file objects over the standard fd's
1091 for fd, temp_fd in enumerate(temp_fds):
1092 os.dup2(temp_fd, fd)
1093
1094 # now use those files in the "wrong" order, so that subprocess
1095 # has to rearrange them in the child
1096 p = subprocess.Popen([sys.executable, "-c",
1097 'import sys; got = sys.stdin.read();'
1098 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1099 stdin=temp_fds[1],
1100 stdout=temp_fds[2],
1101 stderr=temp_fds[0])
1102 p.wait()
1103 finally:
1104 # restore the original fd's underneath sys.stdin, etc.
1105 for std, saved in enumerate(saved_fds):
1106 os.dup2(saved, std)
1107 os.close(saved)
1108
1109 for fd in temp_fds:
1110 os.lseek(fd, 0, 0)
1111
1112 out = os.read(temp_fds[2], 1024)
1113 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1114 self.assertEqual(out, b"got STDIN")
1115 self.assertEqual(err, b"err")
1116
1117 finally:
1118 for fd in temp_fds:
1119 os.close(fd)
1120
Victor Stinner13bb71c2010-04-23 21:41:56 +00001121 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001122 def prepare():
1123 raise ValueError("surrogate:\uDCff")
1124
1125 try:
1126 subprocess.call(
1127 [sys.executable, "-c", "pass"],
1128 preexec_fn=prepare)
1129 except ValueError as err:
1130 # Pure Python implementations keeps the message
1131 self.assertIsNone(subprocess._posixsubprocess)
1132 self.assertEqual(str(err), "surrogate:\uDCff")
1133 except RuntimeError as err:
1134 # _posixsubprocess uses a default message
1135 self.assertIsNotNone(subprocess._posixsubprocess)
1136 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1137 else:
1138 self.fail("Expected ValueError or RuntimeError")
1139
Victor Stinner13bb71c2010-04-23 21:41:56 +00001140 def test_undecodable_env(self):
1141 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001142 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001143 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001144 env = os.environ.copy()
1145 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001146 # Use C locale to get ascii for the locale encoding to force
1147 # surrogate-escaping of \xFF in the child process; otherwise it can
1148 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001149 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001150 stdout = subprocess.check_output(
1151 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001152 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001153 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001154 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001155
1156 # test bytes
1157 key = key.encode("ascii", "surrogateescape")
1158 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001159 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001160 env = os.environ.copy()
1161 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001162 stdout = subprocess.check_output(
1163 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001164 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001165 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001166 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001167
Victor Stinnerb745a742010-05-18 17:17:23 +00001168 def test_bytes_program(self):
1169 abs_program = os.fsencode(sys.executable)
1170 path, program = os.path.split(sys.executable)
1171 program = os.fsencode(program)
1172
1173 # absolute bytes path
1174 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001175 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001176
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001177 # absolute bytes path as a string
1178 cmd = b"'" + abs_program + b"' -c pass"
1179 exitcode = subprocess.call(cmd, shell=True)
1180 self.assertEqual(exitcode, 0)
1181
Victor Stinnerb745a742010-05-18 17:17:23 +00001182 # bytes program, unicode PATH
1183 env = os.environ.copy()
1184 env["PATH"] = path
1185 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001186 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001187
1188 # bytes program, bytes PATH
1189 envb = os.environb.copy()
1190 envb[b"PATH"] = os.fsencode(path)
1191 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001192 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001193
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001194 def test_pipe_cloexec(self):
1195 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1196 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1197
1198 p1 = subprocess.Popen([sys.executable, sleeper],
1199 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1200 stderr=subprocess.PIPE, close_fds=False)
1201
1202 self.addCleanup(p1.communicate, b'')
1203
1204 p2 = subprocess.Popen([sys.executable, fd_status],
1205 stdout=subprocess.PIPE, close_fds=False)
1206
1207 output, error = p2.communicate()
1208 result_fds = set(map(int, output.split(b',')))
1209 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1210 p1.stderr.fileno()])
1211
1212 self.assertFalse(result_fds & unwanted_fds,
1213 "Expected no fds from %r to be open in child, "
1214 "found %r" %
1215 (unwanted_fds, result_fds & unwanted_fds))
1216
1217 def test_pipe_cloexec_real_tools(self):
1218 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1219 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1220
1221 subdata = b'zxcvbn'
1222 data = subdata * 4 + b'\n'
1223
1224 p1 = subprocess.Popen([sys.executable, qcat],
1225 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1226 close_fds=False)
1227
1228 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1229 stdin=p1.stdout, stdout=subprocess.PIPE,
1230 close_fds=False)
1231
1232 self.addCleanup(p1.wait)
1233 self.addCleanup(p2.wait)
1234 self.addCleanup(p1.terminate)
1235 self.addCleanup(p2.terminate)
1236
1237 p1.stdin.write(data)
1238 p1.stdin.close()
1239
1240 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1241
1242 self.assertTrue(readfiles, "The child hung")
1243 self.assertEqual(p2.stdout.read(), data)
1244
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001245 p1.stdout.close()
1246 p2.stdout.close()
1247
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001248 def test_close_fds(self):
1249 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1250
1251 fds = os.pipe()
1252 self.addCleanup(os.close, fds[0])
1253 self.addCleanup(os.close, fds[1])
1254
1255 open_fds = set(fds)
1256
1257 p = subprocess.Popen([sys.executable, fd_status],
1258 stdout=subprocess.PIPE, close_fds=False)
1259 output, ignored = p.communicate()
1260 remaining_fds = set(map(int, output.split(b',')))
1261
1262 self.assertEqual(remaining_fds & open_fds, open_fds,
1263 "Some fds were closed")
1264
1265 p = subprocess.Popen([sys.executable, fd_status],
1266 stdout=subprocess.PIPE, close_fds=True)
1267 output, ignored = p.communicate()
1268 remaining_fds = set(map(int, output.split(b',')))
1269
1270 self.assertFalse(remaining_fds & open_fds,
1271 "Some fds were left open")
1272 self.assertIn(1, remaining_fds, "Subprocess failed")
1273
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001274 def test_pass_fds(self):
1275 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1276
1277 open_fds = set()
1278
1279 for x in range(5):
1280 fds = os.pipe()
1281 self.addCleanup(os.close, fds[0])
1282 self.addCleanup(os.close, fds[1])
1283 open_fds.update(fds)
1284
1285 for fd in open_fds:
1286 p = subprocess.Popen([sys.executable, fd_status],
1287 stdout=subprocess.PIPE, close_fds=True,
1288 pass_fds=(fd, ))
1289 output, ignored = p.communicate()
1290
1291 remaining_fds = set(map(int, output.split(b',')))
1292 to_be_closed = open_fds - {fd}
1293
1294 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1295 self.assertFalse(remaining_fds & to_be_closed,
1296 "fd to be closed passed")
1297
1298 # pass_fds overrides close_fds with a warning.
1299 with self.assertWarns(RuntimeWarning) as context:
1300 self.assertFalse(subprocess.call(
1301 [sys.executable, "-c", "import sys; sys.exit(0)"],
1302 close_fds=False, pass_fds=(fd, )))
1303 self.assertIn('overriding close_fds', str(context.warning))
1304
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001305 def test_stdout_stdin_are_single_inout_fd(self):
1306 with io.open(os.devnull, "r+") as inout:
1307 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1308 stdout=inout, stdin=inout)
1309 p.wait()
1310
1311 def test_stdout_stderr_are_single_inout_fd(self):
1312 with io.open(os.devnull, "r+") as inout:
1313 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1314 stdout=inout, stderr=inout)
1315 p.wait()
1316
1317 def test_stderr_stdin_are_single_inout_fd(self):
1318 with io.open(os.devnull, "r+") as inout:
1319 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1320 stderr=inout, stdin=inout)
1321 p.wait()
1322
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001323 def test_wait_when_sigchild_ignored(self):
1324 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1325 sigchild_ignore = support.findfile("sigchild_ignore.py",
1326 subdir="subprocessdata")
1327 p = subprocess.Popen([sys.executable, sigchild_ignore],
1328 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1329 stdout, stderr = p.communicate()
1330 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001331 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001332 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001333
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001334 def test_select_unbuffered(self):
1335 # Issue #11459: bufsize=0 should really set the pipes as
1336 # unbuffered (and therefore let select() work properly).
1337 select = support.import_module("select")
1338 p = subprocess.Popen([sys.executable, "-c",
1339 'import sys;'
1340 'sys.stdout.write("apple")'],
1341 stdout=subprocess.PIPE,
1342 bufsize=0)
1343 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001344 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001345 try:
1346 self.assertEqual(f.read(4), b"appl")
1347 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1348 finally:
1349 p.wait()
1350
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001351
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001352@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001353class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001354
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001355 def test_startupinfo(self):
1356 # startupinfo argument
1357 # We uses hardcoded constants, because we do not want to
1358 # depend on win32all.
1359 STARTF_USESHOWWINDOW = 1
1360 SW_MAXIMIZE = 3
1361 startupinfo = subprocess.STARTUPINFO()
1362 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1363 startupinfo.wShowWindow = SW_MAXIMIZE
1364 # Since Python is a console process, it won't be affected
1365 # by wShowWindow, but the argument should be silently
1366 # ignored
1367 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001368 startupinfo=startupinfo)
1369
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001370 def test_creationflags(self):
1371 # creationflags argument
1372 CREATE_NEW_CONSOLE = 16
1373 sys.stderr.write(" a DOS box should flash briefly ...\n")
1374 subprocess.call(sys.executable +
1375 ' -c "import time; time.sleep(0.25)"',
1376 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001377
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001378 def test_invalid_args(self):
1379 # invalid arguments should raise ValueError
1380 self.assertRaises(ValueError, subprocess.call,
1381 [sys.executable, "-c",
1382 "import sys; sys.exit(47)"],
1383 preexec_fn=lambda: 1)
1384 self.assertRaises(ValueError, subprocess.call,
1385 [sys.executable, "-c",
1386 "import sys; sys.exit(47)"],
1387 stdout=subprocess.PIPE,
1388 close_fds=True)
1389
1390 def test_close_fds(self):
1391 # close file descriptors
1392 rc = subprocess.call([sys.executable, "-c",
1393 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001394 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001395 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001396
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001397 def test_shell_sequence(self):
1398 # Run command through the shell (sequence)
1399 newenv = os.environ.copy()
1400 newenv["FRUIT"] = "physalis"
1401 p = subprocess.Popen(["set"], shell=1,
1402 stdout=subprocess.PIPE,
1403 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001404 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001405 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001406
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001407 def test_shell_string(self):
1408 # Run command through the shell (string)
1409 newenv = os.environ.copy()
1410 newenv["FRUIT"] = "physalis"
1411 p = subprocess.Popen("set", shell=1,
1412 stdout=subprocess.PIPE,
1413 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001414 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001415 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001416
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001417 def test_call_string(self):
1418 # call() function with string argument on Windows
1419 rc = subprocess.call(sys.executable +
1420 ' -c "import sys; sys.exit(47)"')
1421 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001422
Florent Xicluna4886d242010-03-08 13:27:26 +00001423 def _kill_process(self, method, *args):
1424 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001425 p = subprocess.Popen([sys.executable, "-c", """if 1:
1426 import sys, time
1427 sys.stdout.write('x\\n')
1428 sys.stdout.flush()
1429 time.sleep(30)
1430 """],
1431 stdin=subprocess.PIPE,
1432 stdout=subprocess.PIPE,
1433 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001434 self.addCleanup(p.stdout.close)
1435 self.addCleanup(p.stderr.close)
1436 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001437 # Wait for the interpreter to be completely initialized before
1438 # sending any signal.
1439 p.stdout.read(1)
1440 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001441 _, stderr = p.communicate()
1442 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001443 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001444 self.assertNotEqual(returncode, 0)
1445
1446 def test_send_signal(self):
1447 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001448
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001449 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001450 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001451
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001452 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001453 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001454
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001455
Brett Cannona23810f2008-05-26 19:04:21 +00001456# The module says:
1457# "NB This only works (and is only relevant) for UNIX."
1458#
1459# Actually, getoutput should work on any platform with an os.popen, but
1460# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001461@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001462class CommandTests(unittest.TestCase):
1463 def test_getoutput(self):
1464 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1465 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1466 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001467
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001468 # we use mkdtemp in the next line to create an empty directory
1469 # under our exclusive control; from that, we can invent a pathname
1470 # that we _know_ won't exist. This is guaranteed to fail.
1471 dir = None
1472 try:
1473 dir = tempfile.mkdtemp()
1474 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001475
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001476 status, output = subprocess.getstatusoutput('cat ' + name)
1477 self.assertNotEqual(status, 0)
1478 finally:
1479 if dir is not None:
1480 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001481
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001482
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001483@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1484 "poll system call not supported")
1485class ProcessTestCaseNoPoll(ProcessTestCase):
1486 def setUp(self):
1487 subprocess._has_poll = False
1488 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001489
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001490 def tearDown(self):
1491 subprocess._has_poll = True
1492 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001493
1494
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001495class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001496 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001497 def test_eintr_retry_call(self):
1498 record_calls = []
1499 def fake_os_func(*args):
1500 record_calls.append(args)
1501 if len(record_calls) == 2:
1502 raise OSError(errno.EINTR, "fake interrupted system call")
1503 return tuple(reversed(args))
1504
1505 self.assertEqual((999, 256),
1506 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1507 self.assertEqual([(256, 999)], record_calls)
1508 # This time there will be an EINTR so it will loop once.
1509 self.assertEqual((666,),
1510 subprocess._eintr_retry_call(fake_os_func, 666))
1511 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1512
1513
Tim Golden126c2962010-08-11 14:20:40 +00001514@unittest.skipUnless(mswindows, "Windows-specific tests")
1515class CommandsWithSpaces (BaseTestCase):
1516
1517 def setUp(self):
1518 super().setUp()
1519 f, fname = mkstemp(".py", "te st")
1520 self.fname = fname.lower ()
1521 os.write(f, b"import sys;"
1522 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1523 )
1524 os.close(f)
1525
1526 def tearDown(self):
1527 os.remove(self.fname)
1528 super().tearDown()
1529
1530 def with_spaces(self, *args, **kwargs):
1531 kwargs['stdout'] = subprocess.PIPE
1532 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001533 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001534 self.assertEqual(
1535 p.stdout.read ().decode("mbcs"),
1536 "2 [%r, 'ab cd']" % self.fname
1537 )
1538
1539 def test_shell_string_with_spaces(self):
1540 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001541 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1542 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001543
1544 def test_shell_sequence_with_spaces(self):
1545 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001546 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001547
1548 def test_noshell_string_with_spaces(self):
1549 # call() function with string argument with spaces on Windows
1550 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1551 "ab cd"))
1552
1553 def test_noshell_sequence_with_spaces(self):
1554 # call() function with sequence argument with spaces on Windows
1555 self.with_spaces([sys.executable, self.fname, "ab cd"])
1556
Brian Curtin79cdb662010-12-03 02:46:02 +00001557
1558class ContextManagerTests(ProcessTestCase):
1559
1560 def test_pipe(self):
1561 with subprocess.Popen([sys.executable, "-c",
1562 "import sys;"
1563 "sys.stdout.write('stdout');"
1564 "sys.stderr.write('stderr');"],
1565 stdout=subprocess.PIPE,
1566 stderr=subprocess.PIPE) as proc:
1567 self.assertEqual(proc.stdout.read(), b"stdout")
1568 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1569
1570 self.assertTrue(proc.stdout.closed)
1571 self.assertTrue(proc.stderr.closed)
1572
1573 def test_returncode(self):
1574 with subprocess.Popen([sys.executable, "-c",
1575 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07001576 pass
1577 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001578 self.assertEqual(proc.returncode, 100)
1579
1580 def test_communicate_stdin(self):
1581 with subprocess.Popen([sys.executable, "-c",
1582 "import sys;"
1583 "sys.exit(sys.stdin.read() == 'context')"],
1584 stdin=subprocess.PIPE) as proc:
1585 proc.communicate(b"context")
1586 self.assertEqual(proc.returncode, 1)
1587
1588 def test_invalid_args(self):
1589 with self.assertRaises(EnvironmentError) as c:
1590 with subprocess.Popen(['nonexisting_i_hope'],
1591 stdout=subprocess.PIPE,
1592 stderr=subprocess.PIPE) as proc:
1593 pass
1594
1595 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1596 raise c.exception
1597
1598
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001599def test_main():
1600 unit_tests = (ProcessTestCase,
1601 POSIXProcessTestCase,
1602 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001603 CommandTests,
1604 ProcessTestCaseNoPoll,
1605 HelperFunctionTests,
1606 CommandsWithSpaces,
1607 ContextManagerTests)
1608
1609 support.run_unittest(*unit_tests)
1610 support.reap_children()
1611
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001612if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001613 unittest.main()