blob: 5f158b9b64fa9868447376dc5d4a65bf49b1796e [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 Kleckner80b92d12011-03-14 13:34:12 -0400133 timeout=1.5)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400134 self.fail("Expected TimeoutExpired.")
135 self.assertEqual(c.exception.output, b'BDFL')
136
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000137 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000138 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000139 newenv = os.environ.copy()
140 newenv["FRUIT"] = "banana"
141 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000142 'import sys, os;'
143 'sys.exit(os.getenv("FRUIT")=="banana")'],
144 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145 self.assertEqual(rc, 1)
146
147 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000148 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000149 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000150 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000151 self.addCleanup(p.stdout.close)
152 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000153 p.wait()
154 self.assertEqual(p.stdin, None)
155
156 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000157 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000158 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000159 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000160 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000161 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000162 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000163 self.addCleanup(p.stdin.close)
164 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165 p.wait()
166 self.assertEqual(p.stdout, None)
167
168 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000169 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000170 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000171 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000172 self.addCleanup(p.stdout.close)
173 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000174 p.wait()
175 self.assertEqual(p.stderr, None)
176
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000177 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000178 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000179 p = subprocess.Popen(["somethingyoudonthave", "-c",
180 "import sys; sys.exit(47)"],
181 executable=sys.executable, cwd=python_dir)
182 p.wait()
183 self.assertEqual(p.returncode, 47)
184
185 @unittest.skipIf(sysconfig.is_python_build(),
186 "need an installed Python. See #7774")
187 def test_executable_without_cwd(self):
188 # For a normal installation, it should work without 'cwd'
189 # argument. For test runs in the build directory, see #7774.
190 p = subprocess.Popen(["somethingyoudonthave", "-c",
191 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000192 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000193 p.wait()
194 self.assertEqual(p.returncode, 47)
195
196 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000197 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000198 p = subprocess.Popen([sys.executable, "-c",
199 'import sys; sys.exit(sys.stdin.read() == "pear")'],
200 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000201 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000202 p.stdin.close()
203 p.wait()
204 self.assertEqual(p.returncode, 1)
205
206 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000207 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000208 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000209 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000211 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000212 os.lseek(d, 0, 0)
213 p = subprocess.Popen([sys.executable, "-c",
214 'import sys; sys.exit(sys.stdin.read() == "pear")'],
215 stdin=d)
216 p.wait()
217 self.assertEqual(p.returncode, 1)
218
219 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000220 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000221 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000222 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000223 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000224 tf.seek(0)
225 p = subprocess.Popen([sys.executable, "-c",
226 'import sys; sys.exit(sys.stdin.read() == "pear")'],
227 stdin=tf)
228 p.wait()
229 self.assertEqual(p.returncode, 1)
230
231 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000232 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233 p = subprocess.Popen([sys.executable, "-c",
234 'import sys; sys.stdout.write("orange")'],
235 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000236 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000237 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238
239 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000240 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000241 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000242 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000243 d = tf.fileno()
244 p = subprocess.Popen([sys.executable, "-c",
245 'import sys; sys.stdout.write("orange")'],
246 stdout=d)
247 p.wait()
248 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000249 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000250
251 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000252 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000253 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000254 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000255 p = subprocess.Popen([sys.executable, "-c",
256 'import sys; sys.stdout.write("orange")'],
257 stdout=tf)
258 p.wait()
259 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000260 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000261
262 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000263 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000264 p = subprocess.Popen([sys.executable, "-c",
265 'import sys; sys.stderr.write("strawberry")'],
266 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000267 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000268 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269
270 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000271 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000272 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000273 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274 d = tf.fileno()
275 p = subprocess.Popen([sys.executable, "-c",
276 'import sys; sys.stderr.write("strawberry")'],
277 stderr=d)
278 p.wait()
279 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000280 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281
282 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000283 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000284 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000285 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000286 p = subprocess.Popen([sys.executable, "-c",
287 'import sys; sys.stderr.write("strawberry")'],
288 stderr=tf)
289 p.wait()
290 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000291 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000292
293 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000294 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000295 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000296 'import sys;'
297 'sys.stdout.write("apple");'
298 'sys.stdout.flush();'
299 'sys.stderr.write("orange")'],
300 stdout=subprocess.PIPE,
301 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000302 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000303 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000304
305 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000306 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000307 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000308 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000310 'import sys;'
311 'sys.stdout.write("apple");'
312 'sys.stdout.flush();'
313 'sys.stderr.write("orange")'],
314 stdout=tf,
315 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000316 p.wait()
317 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000318 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000319
Thomas Wouters89f507f2006-12-13 04:49:30 +0000320 def test_stdout_filedes_of_stdout(self):
321 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000322 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000323 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000324 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000325
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000326 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000327 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000328 # We cannot use os.path.realpath to canonicalize the path,
329 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
330 cwd = os.getcwd()
331 os.chdir(tmpdir)
332 tmpdir = os.getcwd()
333 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000335 'import sys,os;'
336 'sys.stdout.write(os.getcwd())'],
337 stdout=subprocess.PIPE,
338 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000339 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000340 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000341 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
342 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000343
344 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000345 newenv = os.environ.copy()
346 newenv["FRUIT"] = "orange"
347 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000348 'import sys,os;'
349 'sys.stdout.write(os.getenv("FRUIT"))'],
350 stdout=subprocess.PIPE,
351 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000352 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000353 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354
Peter Astrandcbac93c2005-03-03 20:24:28 +0000355 def test_communicate_stdin(self):
356 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000357 'import sys;'
358 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000359 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000360 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000361 self.assertEqual(p.returncode, 1)
362
363 def test_communicate_stdout(self):
364 p = subprocess.Popen([sys.executable, "-c",
365 'import sys; sys.stdout.write("pineapple")'],
366 stdout=subprocess.PIPE)
367 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000368 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000369 self.assertEqual(stderr, None)
370
371 def test_communicate_stderr(self):
372 p = subprocess.Popen([sys.executable, "-c",
373 'import sys; sys.stderr.write("pineapple")'],
374 stderr=subprocess.PIPE)
375 (stdout, stderr) = p.communicate()
376 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000377 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000378
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000379 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000380 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000381 'import sys,os;'
382 'sys.stderr.write("pineapple");'
383 'sys.stdout.write(sys.stdin.read())'],
384 stdin=subprocess.PIPE,
385 stdout=subprocess.PIPE,
386 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000387 self.addCleanup(p.stdout.close)
388 self.addCleanup(p.stderr.close)
389 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000390 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000391 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000392 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000393
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400394 def test_communicate_timeout(self):
395 p = subprocess.Popen([sys.executable, "-c",
396 'import sys,os,time;'
397 'sys.stderr.write("pineapple\\n");'
398 'time.sleep(1);'
399 'sys.stderr.write("pear\\n");'
400 'sys.stdout.write(sys.stdin.read())'],
401 universal_newlines=True,
402 stdin=subprocess.PIPE,
403 stdout=subprocess.PIPE,
404 stderr=subprocess.PIPE)
405 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
406 timeout=0.3)
407 # Make sure we can keep waiting for it, and that we get the whole output
408 # after it completes.
409 (stdout, stderr) = p.communicate()
410 self.assertEqual(stdout, "banana")
411 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
412
413 def test_communicate_timeout_large_ouput(self):
414 # Test a expring timeout while the child is outputting lots of data.
415 p = subprocess.Popen([sys.executable, "-c",
416 'import sys,os,time;'
417 'sys.stdout.write("a" * (64 * 1024));'
418 'time.sleep(0.2);'
419 'sys.stdout.write("a" * (64 * 1024));'
420 'time.sleep(0.2);'
421 'sys.stdout.write("a" * (64 * 1024));'
422 'time.sleep(0.2);'
423 'sys.stdout.write("a" * (64 * 1024));'],
424 stdout=subprocess.PIPE)
425 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
426 (stdout, _) = p.communicate()
427 self.assertEqual(len(stdout), 4 * 64 * 1024)
428
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000429 # Test for the fd leak reported in http://bugs.python.org/issue2791.
430 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000431 for stdin_pipe in (False, True):
432 for stdout_pipe in (False, True):
433 for stderr_pipe in (False, True):
434 options = {}
435 if stdin_pipe:
436 options['stdin'] = subprocess.PIPE
437 if stdout_pipe:
438 options['stdout'] = subprocess.PIPE
439 if stderr_pipe:
440 options['stderr'] = subprocess.PIPE
441 if not options:
442 continue
443 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
444 p.communicate()
445 if p.stdin is not None:
446 self.assertTrue(p.stdin.closed)
447 if p.stdout is not None:
448 self.assertTrue(p.stdout.closed)
449 if p.stderr is not None:
450 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000451
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000453 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000454 p = subprocess.Popen([sys.executable, "-c",
455 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000456 (stdout, stderr) = p.communicate()
457 self.assertEqual(stdout, None)
458 self.assertEqual(stderr, None)
459
460 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000461 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000462 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000463 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464 x, y = os.pipe()
465 if mswindows:
466 pipe_buf = 512
467 else:
468 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
469 os.close(x)
470 os.close(y)
471 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000472 'import sys,os;'
473 'sys.stdout.write(sys.stdin.read(47));'
474 'sys.stderr.write("xyz"*%d);'
475 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
476 stdin=subprocess.PIPE,
477 stdout=subprocess.PIPE,
478 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000479 self.addCleanup(p.stdout.close)
480 self.addCleanup(p.stderr.close)
481 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000482 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483 (stdout, stderr) = p.communicate(string_to_write)
484 self.assertEqual(stdout, string_to_write)
485
486 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000487 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000489 'import sys,os;'
490 'sys.stdout.write(sys.stdin.read())'],
491 stdin=subprocess.PIPE,
492 stdout=subprocess.PIPE,
493 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000494 self.addCleanup(p.stdout.close)
495 self.addCleanup(p.stderr.close)
496 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000497 p.stdin.write(b"banana")
498 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000499 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000500 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000501
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000503 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000504 'import sys,os;' + SETBINARY +
505 'sys.stdout.write("line1\\n");'
506 'sys.stdout.flush();'
507 'sys.stdout.write("line2\\n");'
508 'sys.stdout.flush();'
509 'sys.stdout.write("line3\\r\\n");'
510 'sys.stdout.flush();'
511 'sys.stdout.write("line4\\r");'
512 'sys.stdout.flush();'
513 'sys.stdout.write("\\nline5");'
514 'sys.stdout.flush();'
515 'sys.stdout.write("\\nline6");'],
516 stdout=subprocess.PIPE,
517 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000518 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000519 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000520 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000521
522 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000523 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000524 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000525 'import sys,os;' + SETBINARY +
526 'sys.stdout.write("line1\\n");'
527 'sys.stdout.flush();'
528 'sys.stdout.write("line2\\n");'
529 'sys.stdout.flush();'
530 'sys.stdout.write("line3\\r\\n");'
531 'sys.stdout.flush();'
532 'sys.stdout.write("line4\\r");'
533 'sys.stdout.flush();'
534 'sys.stdout.write("\\nline5");'
535 'sys.stdout.flush();'
536 'sys.stdout.write("\\nline6");'],
537 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
538 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000539 self.addCleanup(p.stdout.close)
540 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000541 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000542 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543
544 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000545 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000546 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000547 max_handles = 1026 # too much for most UNIX systems
548 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000549 max_handles = 2050 # too much for (at least some) Windows setups
550 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400551 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000552 try:
553 for i in range(max_handles):
554 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400555 tmpfile = os.path.join(tmpdir, support.TESTFN)
556 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000557 except OSError as e:
558 if e.errno != errno.EMFILE:
559 raise
560 break
561 else:
562 self.skipTest("failed to reach the file descriptor limit "
563 "(tried %d)" % max_handles)
564 # Close a couple of them (should be enough for a subprocess)
565 for i in range(10):
566 os.close(handles.pop())
567 # Loop creating some subprocesses. If one of them leaks some fds,
568 # the next loop iteration will fail by reaching the max fd limit.
569 for i in range(15):
570 p = subprocess.Popen([sys.executable, "-c",
571 "import sys;"
572 "sys.stdout.write(sys.stdin.read())"],
573 stdin=subprocess.PIPE,
574 stdout=subprocess.PIPE,
575 stderr=subprocess.PIPE)
576 data = p.communicate(b"lime")[0]
577 self.assertEqual(data, b"lime")
578 finally:
579 for h in handles:
580 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400581 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000582
583 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000584 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
585 '"a b c" d e')
586 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
587 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000588 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
589 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000590 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
591 'a\\\\\\b "de fg" h')
592 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
593 'a\\\\\\"b c d')
594 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
595 '"a\\\\b c" d e')
596 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
597 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000598 self.assertEqual(subprocess.list2cmdline(['ab', '']),
599 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000600
601
602 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000603 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000604 "-c", "import time; time.sleep(1)"])
605 count = 0
606 while p.poll() is None:
607 time.sleep(0.1)
608 count += 1
609 # We expect that the poll loop probably went around about 10 times,
610 # but, based on system scheduling we can't control, it's possible
611 # poll() never returned None. It "should be" very rare that it
612 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000613 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000614 # Subsequent invocations should just return the returncode
615 self.assertEqual(p.poll(), 0)
616
617
618 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619 p = subprocess.Popen([sys.executable,
620 "-c", "import time; time.sleep(2)"])
621 self.assertEqual(p.wait(), 0)
622 # Subsequent invocations should just return the returncode
623 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000624
Peter Astrand738131d2004-11-30 21:04:45 +0000625
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400626 def test_wait_timeout(self):
627 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400628 "-c", "import time; time.sleep(0.1)"])
629 self.assertRaises(subprocess.TimeoutExpired, p.wait, timeout=0.01)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400630 self.assertEqual(p.wait(timeout=2), 0)
631
632
Peter Astrand738131d2004-11-30 21:04:45 +0000633 def test_invalid_bufsize(self):
634 # an invalid type of the bufsize argument should raise
635 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000636 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000637 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000638
Guido van Rossum46a05a72007-06-07 21:56:45 +0000639 def test_bufsize_is_none(self):
640 # bufsize=None should be the same as bufsize=0.
641 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
642 self.assertEqual(p.wait(), 0)
643 # Again with keyword arg
644 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
645 self.assertEqual(p.wait(), 0)
646
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000647 def test_leaking_fds_on_error(self):
648 # see bug #5179: Popen leaks file descriptors to PIPEs if
649 # the child fails to execute; this will eventually exhaust
650 # the maximum number of open fds. 1024 seems a very common
651 # value for that limit, but Windows has 2048, so we loop
652 # 1024 times (each call leaked two fds).
653 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000654 # Windows raises IOError. Others raise OSError.
655 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000656 subprocess.Popen(['nonexisting_i_hope'],
657 stdout=subprocess.PIPE,
658 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400659 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400660 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000661 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000662
Victor Stinnerb3693582010-05-21 20:13:12 +0000663 def test_issue8780(self):
664 # Ensure that stdout is inherited from the parent
665 # if stdout=PIPE is not used
666 code = ';'.join((
667 'import subprocess, sys',
668 'retcode = subprocess.call('
669 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
670 'assert retcode == 0'))
671 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000672 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000673
Tim Goldenaf5ac392010-08-06 13:03:56 +0000674 def test_handles_closed_on_exception(self):
675 # If CreateProcess exits with an error, ensure the
676 # duplicate output handles are released
677 ifhandle, ifname = mkstemp()
678 ofhandle, ofname = mkstemp()
679 efhandle, efname = mkstemp()
680 try:
681 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
682 stderr=efhandle)
683 except OSError:
684 os.close(ifhandle)
685 os.remove(ifname)
686 os.close(ofhandle)
687 os.remove(ofname)
688 os.close(efhandle)
689 os.remove(efname)
690 self.assertFalse(os.path.exists(ifname))
691 self.assertFalse(os.path.exists(ofname))
692 self.assertFalse(os.path.exists(efname))
693
Tim Peterse718f612004-10-12 21:51:32 +0000694
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000695# context manager
696class _SuppressCoreFiles(object):
697 """Try to prevent core files from being created."""
698 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000699
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000700 def __enter__(self):
701 """Try to save previous ulimit, then set it to (0, 0)."""
702 try:
703 import resource
704 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
705 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
706 except (ImportError, ValueError, resource.error):
707 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000708
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000709 if sys.platform == 'darwin':
710 # Check if the 'Crash Reporter' on OSX was configured
711 # in 'Developer' mode and warn that it will get triggered
712 # when it is.
713 #
714 # This assumes that this context manager is used in tests
715 # that might trigger the next manager.
716 value = subprocess.Popen(['/usr/bin/defaults', 'read',
717 'com.apple.CrashReporter', 'DialogType'],
718 stdout=subprocess.PIPE).communicate()[0]
719 if value.strip() == b'developer':
720 print("this tests triggers the Crash Reporter, "
721 "that is intentional", end='')
722 sys.stdout.flush()
723
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000724 def __exit__(self, *args):
725 """Return core file behavior to default."""
726 if self.old_limit is None:
727 return
728 try:
729 import resource
730 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
731 except (ImportError, ValueError, resource.error):
732 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000733
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000734
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000735@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000736class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000737
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000738 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000739 nonexistent_dir = "/_this/pa.th/does/not/exist"
740 try:
741 os.chdir(nonexistent_dir)
742 except OSError as e:
743 # This avoids hard coding the errno value or the OS perror()
744 # string and instead capture the exception that we want to see
745 # below for comparison.
746 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000747 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000748 else:
749 self.fail("chdir to nonexistant directory %s succeeded." %
750 nonexistent_dir)
751
752 # Error in the child re-raised in the parent.
753 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000754 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000755 cwd=nonexistent_dir)
756 except OSError as e:
757 # Test that the child process chdir failure actually makes
758 # it up to the parent process as the correct exception.
759 self.assertEqual(desired_exception.errno, e.errno)
760 self.assertEqual(desired_exception.strerror, e.strerror)
761 else:
762 self.fail("Expected OSError: %s" % desired_exception)
763
764 def test_restore_signals(self):
765 # Code coverage for both values of restore_signals to make sure it
766 # at least does not blow up.
767 # A test for behavior would be complex. Contributions welcome.
768 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
769 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
770
771 def test_start_new_session(self):
772 # For code coverage of calling setsid(). We don't care if we get an
773 # EPERM error from it depending on the test execution environment, that
774 # still indicates that it was called.
775 try:
776 output = subprocess.check_output(
777 [sys.executable, "-c",
778 "import os; print(os.getpgid(os.getpid()))"],
779 start_new_session=True)
780 except OSError as e:
781 if e.errno != errno.EPERM:
782 raise
783 else:
784 parent_pgid = os.getpgid(os.getpid())
785 child_pgid = int(output)
786 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000787
788 def test_run_abort(self):
789 # returncode handles signal termination
790 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000791 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000792 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000793 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000794 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000795
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000796 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000797 # DISCLAIMER: Setting environment variables is *not* a good use
798 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000799 p = subprocess.Popen([sys.executable, "-c",
800 'import sys,os;'
801 'sys.stdout.write(os.getenv("FRUIT"))'],
802 stdout=subprocess.PIPE,
803 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000804 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000805 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000806
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000807 def test_preexec_exception(self):
808 def raise_it():
809 raise ValueError("What if two swallows carried a coconut?")
810 try:
811 p = subprocess.Popen([sys.executable, "-c", ""],
812 preexec_fn=raise_it)
813 except RuntimeError as e:
814 self.assertTrue(
815 subprocess._posixsubprocess,
816 "Expected a ValueError from the preexec_fn")
817 except ValueError as e:
818 self.assertIn("coconut", e.args[0])
819 else:
820 self.fail("Exception raised by preexec_fn did not make it "
821 "to the parent process.")
822
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000823 @unittest.skipUnless(gc, "Requires a gc module.")
824 def test_preexec_gc_module_failure(self):
825 # This tests the code that disables garbage collection if the child
826 # process will execute any Python.
827 def raise_runtime_error():
828 raise RuntimeError("this shouldn't escape")
829 enabled = gc.isenabled()
830 orig_gc_disable = gc.disable
831 orig_gc_isenabled = gc.isenabled
832 try:
833 gc.disable()
834 self.assertFalse(gc.isenabled())
835 subprocess.call([sys.executable, '-c', ''],
836 preexec_fn=lambda: None)
837 self.assertFalse(gc.isenabled(),
838 "Popen enabled gc when it shouldn't.")
839
840 gc.enable()
841 self.assertTrue(gc.isenabled())
842 subprocess.call([sys.executable, '-c', ''],
843 preexec_fn=lambda: None)
844 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
845
846 gc.disable = raise_runtime_error
847 self.assertRaises(RuntimeError, subprocess.Popen,
848 [sys.executable, '-c', ''],
849 preexec_fn=lambda: None)
850
851 del gc.isenabled # force an AttributeError
852 self.assertRaises(AttributeError, subprocess.Popen,
853 [sys.executable, '-c', ''],
854 preexec_fn=lambda: None)
855 finally:
856 gc.disable = orig_gc_disable
857 gc.isenabled = orig_gc_isenabled
858 if not enabled:
859 gc.disable()
860
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000861 def test_args_string(self):
862 # args is a string
863 fd, fname = mkstemp()
864 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000865 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000866 fobj.write("#!/bin/sh\n")
867 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
868 sys.executable)
869 os.chmod(fname, 0o700)
870 p = subprocess.Popen(fname)
871 p.wait()
872 os.remove(fname)
873 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000874
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000875 def test_invalid_args(self):
876 # invalid arguments should raise ValueError
877 self.assertRaises(ValueError, subprocess.call,
878 [sys.executable, "-c",
879 "import sys; sys.exit(47)"],
880 startupinfo=47)
881 self.assertRaises(ValueError, subprocess.call,
882 [sys.executable, "-c",
883 "import sys; sys.exit(47)"],
884 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000885
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000886 def test_shell_sequence(self):
887 # Run command through the shell (sequence)
888 newenv = os.environ.copy()
889 newenv["FRUIT"] = "apple"
890 p = subprocess.Popen(["echo $FRUIT"], shell=1,
891 stdout=subprocess.PIPE,
892 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000893 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000894 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000895
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000896 def test_shell_string(self):
897 # Run command through the shell (string)
898 newenv = os.environ.copy()
899 newenv["FRUIT"] = "apple"
900 p = subprocess.Popen("echo $FRUIT", shell=1,
901 stdout=subprocess.PIPE,
902 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000903 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000904 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000905
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000906 def test_call_string(self):
907 # call() function with string argument on UNIX
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 rc = subprocess.call(fname)
916 os.remove(fname)
917 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000918
Stefan Krah9542cc62010-07-19 14:20:53 +0000919 def test_specific_shell(self):
920 # Issue #9265: Incorrect name passed as arg[0].
921 shells = []
922 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
923 for name in ['bash', 'ksh']:
924 sh = os.path.join(prefix, name)
925 if os.path.isfile(sh):
926 shells.append(sh)
927 if not shells: # Will probably work for any shell but csh.
928 self.skipTest("bash or ksh required for this test")
929 sh = '/bin/sh'
930 if os.path.isfile(sh) and not os.path.islink(sh):
931 # Test will fail if /bin/sh is a symlink to csh.
932 shells.append(sh)
933 for sh in shells:
934 p = subprocess.Popen("echo $0", executable=sh, shell=True,
935 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000936 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000937 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
938
Florent Xicluna4886d242010-03-08 13:27:26 +0000939 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000940 # Do not inherit file handles from the parent.
941 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000942 p = subprocess.Popen([sys.executable, "-c", """if 1:
943 import sys, time
944 sys.stdout.write('x\\n')
945 sys.stdout.flush()
946 time.sleep(30)
947 """],
948 close_fds=True,
949 stdin=subprocess.PIPE,
950 stdout=subprocess.PIPE,
951 stderr=subprocess.PIPE)
952 # Wait for the interpreter to be completely initialized before
953 # sending any signal.
954 p.stdout.read(1)
955 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000956 return p
957
958 def test_send_signal(self):
959 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000960 _, stderr = p.communicate()
961 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000962 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000963
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000964 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000965 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000966 _, stderr = p.communicate()
967 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000968 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000969
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000970 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000971 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000972 _, stderr = p.communicate()
973 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000974 self.assertEqual(p.wait(), -signal.SIGTERM)
975
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000976 def check_close_std_fds(self, fds):
977 # Issue #9905: test that subprocess pipes still work properly with
978 # some standard fds closed
979 stdin = 0
980 newfds = []
981 for a in fds:
982 b = os.dup(a)
983 newfds.append(b)
984 if a == 0:
985 stdin = b
986 try:
987 for fd in fds:
988 os.close(fd)
989 out, err = subprocess.Popen([sys.executable, "-c",
990 'import sys;'
991 'sys.stdout.write("apple");'
992 'sys.stdout.flush();'
993 'sys.stderr.write("orange")'],
994 stdin=stdin,
995 stdout=subprocess.PIPE,
996 stderr=subprocess.PIPE).communicate()
997 err = support.strip_python_stderr(err)
998 self.assertEqual((out, err), (b'apple', b'orange'))
999 finally:
1000 for b, a in zip(newfds, fds):
1001 os.dup2(b, a)
1002 for b in newfds:
1003 os.close(b)
1004
1005 def test_close_fd_0(self):
1006 self.check_close_std_fds([0])
1007
1008 def test_close_fd_1(self):
1009 self.check_close_std_fds([1])
1010
1011 def test_close_fd_2(self):
1012 self.check_close_std_fds([2])
1013
1014 def test_close_fds_0_1(self):
1015 self.check_close_std_fds([0, 1])
1016
1017 def test_close_fds_0_2(self):
1018 self.check_close_std_fds([0, 2])
1019
1020 def test_close_fds_1_2(self):
1021 self.check_close_std_fds([1, 2])
1022
1023 def test_close_fds_0_1_2(self):
1024 # Issue #10806: test that subprocess pipes still work properly with
1025 # all standard fds closed.
1026 self.check_close_std_fds([0, 1, 2])
1027
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001028 def test_remapping_std_fds(self):
1029 # open up some temporary files
1030 temps = [mkstemp() for i in range(3)]
1031 try:
1032 temp_fds = [fd for fd, fname in temps]
1033
1034 # unlink the files -- we won't need to reopen them
1035 for fd, fname in temps:
1036 os.unlink(fname)
1037
1038 # write some data to what will become stdin, and rewind
1039 os.write(temp_fds[1], b"STDIN")
1040 os.lseek(temp_fds[1], 0, 0)
1041
1042 # move the standard file descriptors out of the way
1043 saved_fds = [os.dup(fd) for fd in range(3)]
1044 try:
1045 # duplicate the file objects over the standard fd's
1046 for fd, temp_fd in enumerate(temp_fds):
1047 os.dup2(temp_fd, fd)
1048
1049 # now use those files in the "wrong" order, so that subprocess
1050 # has to rearrange them in the child
1051 p = subprocess.Popen([sys.executable, "-c",
1052 'import sys; got = sys.stdin.read();'
1053 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1054 stdin=temp_fds[1],
1055 stdout=temp_fds[2],
1056 stderr=temp_fds[0])
1057 p.wait()
1058 finally:
1059 # restore the original fd's underneath sys.stdin, etc.
1060 for std, saved in enumerate(saved_fds):
1061 os.dup2(saved, std)
1062 os.close(saved)
1063
1064 for fd in temp_fds:
1065 os.lseek(fd, 0, 0)
1066
1067 out = os.read(temp_fds[2], 1024)
1068 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1069 self.assertEqual(out, b"got STDIN")
1070 self.assertEqual(err, b"err")
1071
1072 finally:
1073 for fd in temp_fds:
1074 os.close(fd)
1075
Victor Stinner13bb71c2010-04-23 21:41:56 +00001076 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001077 def prepare():
1078 raise ValueError("surrogate:\uDCff")
1079
1080 try:
1081 subprocess.call(
1082 [sys.executable, "-c", "pass"],
1083 preexec_fn=prepare)
1084 except ValueError as err:
1085 # Pure Python implementations keeps the message
1086 self.assertIsNone(subprocess._posixsubprocess)
1087 self.assertEqual(str(err), "surrogate:\uDCff")
1088 except RuntimeError as err:
1089 # _posixsubprocess uses a default message
1090 self.assertIsNotNone(subprocess._posixsubprocess)
1091 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1092 else:
1093 self.fail("Expected ValueError or RuntimeError")
1094
Victor Stinner13bb71c2010-04-23 21:41:56 +00001095 def test_undecodable_env(self):
1096 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001097 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001098 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001099 env = os.environ.copy()
1100 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001101 # Use C locale to get ascii for the locale encoding to force
1102 # surrogate-escaping of \xFF in the child process; otherwise it can
1103 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001104 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001105 stdout = subprocess.check_output(
1106 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001107 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001108 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001109 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001110
1111 # test bytes
1112 key = key.encode("ascii", "surrogateescape")
1113 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001114 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001115 env = os.environ.copy()
1116 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001117 stdout = subprocess.check_output(
1118 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001119 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001120 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001121 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001122
Victor Stinnerb745a742010-05-18 17:17:23 +00001123 def test_bytes_program(self):
1124 abs_program = os.fsencode(sys.executable)
1125 path, program = os.path.split(sys.executable)
1126 program = os.fsencode(program)
1127
1128 # absolute bytes path
1129 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001130 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001131
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001132 # absolute bytes path as a string
1133 cmd = b"'" + abs_program + b"' -c pass"
1134 exitcode = subprocess.call(cmd, shell=True)
1135 self.assertEqual(exitcode, 0)
1136
Victor Stinnerb745a742010-05-18 17:17:23 +00001137 # bytes program, unicode PATH
1138 env = os.environ.copy()
1139 env["PATH"] = path
1140 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001141 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001142
1143 # bytes program, bytes PATH
1144 envb = os.environb.copy()
1145 envb[b"PATH"] = os.fsencode(path)
1146 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001147 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001148
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001149 def test_pipe_cloexec(self):
1150 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1151 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1152
1153 p1 = subprocess.Popen([sys.executable, sleeper],
1154 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1155 stderr=subprocess.PIPE, close_fds=False)
1156
1157 self.addCleanup(p1.communicate, b'')
1158
1159 p2 = subprocess.Popen([sys.executable, fd_status],
1160 stdout=subprocess.PIPE, close_fds=False)
1161
1162 output, error = p2.communicate()
1163 result_fds = set(map(int, output.split(b',')))
1164 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1165 p1.stderr.fileno()])
1166
1167 self.assertFalse(result_fds & unwanted_fds,
1168 "Expected no fds from %r to be open in child, "
1169 "found %r" %
1170 (unwanted_fds, result_fds & unwanted_fds))
1171
1172 def test_pipe_cloexec_real_tools(self):
1173 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1174 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1175
1176 subdata = b'zxcvbn'
1177 data = subdata * 4 + b'\n'
1178
1179 p1 = subprocess.Popen([sys.executable, qcat],
1180 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1181 close_fds=False)
1182
1183 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1184 stdin=p1.stdout, stdout=subprocess.PIPE,
1185 close_fds=False)
1186
1187 self.addCleanup(p1.wait)
1188 self.addCleanup(p2.wait)
1189 self.addCleanup(p1.terminate)
1190 self.addCleanup(p2.terminate)
1191
1192 p1.stdin.write(data)
1193 p1.stdin.close()
1194
1195 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1196
1197 self.assertTrue(readfiles, "The child hung")
1198 self.assertEqual(p2.stdout.read(), data)
1199
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001200 p1.stdout.close()
1201 p2.stdout.close()
1202
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001203 def test_close_fds(self):
1204 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1205
1206 fds = os.pipe()
1207 self.addCleanup(os.close, fds[0])
1208 self.addCleanup(os.close, fds[1])
1209
1210 open_fds = set(fds)
1211
1212 p = subprocess.Popen([sys.executable, fd_status],
1213 stdout=subprocess.PIPE, close_fds=False)
1214 output, ignored = p.communicate()
1215 remaining_fds = set(map(int, output.split(b',')))
1216
1217 self.assertEqual(remaining_fds & open_fds, open_fds,
1218 "Some fds were closed")
1219
1220 p = subprocess.Popen([sys.executable, fd_status],
1221 stdout=subprocess.PIPE, close_fds=True)
1222 output, ignored = p.communicate()
1223 remaining_fds = set(map(int, output.split(b',')))
1224
1225 self.assertFalse(remaining_fds & open_fds,
1226 "Some fds were left open")
1227 self.assertIn(1, remaining_fds, "Subprocess failed")
1228
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001229 def test_pass_fds(self):
1230 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1231
1232 open_fds = set()
1233
1234 for x in range(5):
1235 fds = os.pipe()
1236 self.addCleanup(os.close, fds[0])
1237 self.addCleanup(os.close, fds[1])
1238 open_fds.update(fds)
1239
1240 for fd in open_fds:
1241 p = subprocess.Popen([sys.executable, fd_status],
1242 stdout=subprocess.PIPE, close_fds=True,
1243 pass_fds=(fd, ))
1244 output, ignored = p.communicate()
1245
1246 remaining_fds = set(map(int, output.split(b',')))
1247 to_be_closed = open_fds - {fd}
1248
1249 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1250 self.assertFalse(remaining_fds & to_be_closed,
1251 "fd to be closed passed")
1252
1253 # pass_fds overrides close_fds with a warning.
1254 with self.assertWarns(RuntimeWarning) as context:
1255 self.assertFalse(subprocess.call(
1256 [sys.executable, "-c", "import sys; sys.exit(0)"],
1257 close_fds=False, pass_fds=(fd, )))
1258 self.assertIn('overriding close_fds', str(context.warning))
1259
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001260 def test_stdout_stdin_are_single_inout_fd(self):
1261 with io.open(os.devnull, "r+") as inout:
1262 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1263 stdout=inout, stdin=inout)
1264 p.wait()
1265
1266 def test_stdout_stderr_are_single_inout_fd(self):
1267 with io.open(os.devnull, "r+") as inout:
1268 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1269 stdout=inout, stderr=inout)
1270 p.wait()
1271
1272 def test_stderr_stdin_are_single_inout_fd(self):
1273 with io.open(os.devnull, "r+") as inout:
1274 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1275 stderr=inout, stdin=inout)
1276 p.wait()
1277
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001278 def test_wait_when_sigchild_ignored(self):
1279 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1280 sigchild_ignore = support.findfile("sigchild_ignore.py",
1281 subdir="subprocessdata")
1282 p = subprocess.Popen([sys.executable, sigchild_ignore],
1283 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1284 stdout, stderr = p.communicate()
1285 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001286 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001287 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001288
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001289
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001290@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001291class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001292
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001293 def test_startupinfo(self):
1294 # startupinfo argument
1295 # We uses hardcoded constants, because we do not want to
1296 # depend on win32all.
1297 STARTF_USESHOWWINDOW = 1
1298 SW_MAXIMIZE = 3
1299 startupinfo = subprocess.STARTUPINFO()
1300 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1301 startupinfo.wShowWindow = SW_MAXIMIZE
1302 # Since Python is a console process, it won't be affected
1303 # by wShowWindow, but the argument should be silently
1304 # ignored
1305 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001306 startupinfo=startupinfo)
1307
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001308 def test_creationflags(self):
1309 # creationflags argument
1310 CREATE_NEW_CONSOLE = 16
1311 sys.stderr.write(" a DOS box should flash briefly ...\n")
1312 subprocess.call(sys.executable +
1313 ' -c "import time; time.sleep(0.25)"',
1314 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001315
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001316 def test_invalid_args(self):
1317 # invalid arguments should raise ValueError
1318 self.assertRaises(ValueError, subprocess.call,
1319 [sys.executable, "-c",
1320 "import sys; sys.exit(47)"],
1321 preexec_fn=lambda: 1)
1322 self.assertRaises(ValueError, subprocess.call,
1323 [sys.executable, "-c",
1324 "import sys; sys.exit(47)"],
1325 stdout=subprocess.PIPE,
1326 close_fds=True)
1327
1328 def test_close_fds(self):
1329 # close file descriptors
1330 rc = subprocess.call([sys.executable, "-c",
1331 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001332 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001333 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001334
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001335 def test_shell_sequence(self):
1336 # Run command through the shell (sequence)
1337 newenv = os.environ.copy()
1338 newenv["FRUIT"] = "physalis"
1339 p = subprocess.Popen(["set"], shell=1,
1340 stdout=subprocess.PIPE,
1341 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001342 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001343 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001344
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001345 def test_shell_string(self):
1346 # Run command through the shell (string)
1347 newenv = os.environ.copy()
1348 newenv["FRUIT"] = "physalis"
1349 p = subprocess.Popen("set", shell=1,
1350 stdout=subprocess.PIPE,
1351 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001352 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001353 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001354
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001355 def test_call_string(self):
1356 # call() function with string argument on Windows
1357 rc = subprocess.call(sys.executable +
1358 ' -c "import sys; sys.exit(47)"')
1359 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001360
Florent Xicluna4886d242010-03-08 13:27:26 +00001361 def _kill_process(self, method, *args):
1362 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001363 p = subprocess.Popen([sys.executable, "-c", """if 1:
1364 import sys, time
1365 sys.stdout.write('x\\n')
1366 sys.stdout.flush()
1367 time.sleep(30)
1368 """],
1369 stdin=subprocess.PIPE,
1370 stdout=subprocess.PIPE,
1371 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001372 self.addCleanup(p.stdout.close)
1373 self.addCleanup(p.stderr.close)
1374 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001375 # Wait for the interpreter to be completely initialized before
1376 # sending any signal.
1377 p.stdout.read(1)
1378 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001379 _, stderr = p.communicate()
1380 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001381 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001382 self.assertNotEqual(returncode, 0)
1383
1384 def test_send_signal(self):
1385 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001386
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001387 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001388 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001389
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001390 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001391 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001392
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001393
Brett Cannona23810f2008-05-26 19:04:21 +00001394# The module says:
1395# "NB This only works (and is only relevant) for UNIX."
1396#
1397# Actually, getoutput should work on any platform with an os.popen, but
1398# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001399@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001400class CommandTests(unittest.TestCase):
1401 def test_getoutput(self):
1402 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1403 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1404 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001405
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001406 # we use mkdtemp in the next line to create an empty directory
1407 # under our exclusive control; from that, we can invent a pathname
1408 # that we _know_ won't exist. This is guaranteed to fail.
1409 dir = None
1410 try:
1411 dir = tempfile.mkdtemp()
1412 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001413
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001414 status, output = subprocess.getstatusoutput('cat ' + name)
1415 self.assertNotEqual(status, 0)
1416 finally:
1417 if dir is not None:
1418 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001419
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001420
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001421@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1422 "poll system call not supported")
1423class ProcessTestCaseNoPoll(ProcessTestCase):
1424 def setUp(self):
1425 subprocess._has_poll = False
1426 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001427
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001428 def tearDown(self):
1429 subprocess._has_poll = True
1430 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001431
1432
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001433@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1434 "_posixsubprocess extension module not found.")
1435class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
1436 def setUp(self):
1437 subprocess._posixsubprocess = None
1438 ProcessTestCase.setUp(self)
1439 POSIXProcessTestCase.setUp(self)
1440
1441 def tearDown(self):
1442 subprocess._posixsubprocess = sys.modules['_posixsubprocess']
1443 POSIXProcessTestCase.tearDown(self)
1444 ProcessTestCase.tearDown(self)
1445
1446
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001447class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001448 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001449 def test_eintr_retry_call(self):
1450 record_calls = []
1451 def fake_os_func(*args):
1452 record_calls.append(args)
1453 if len(record_calls) == 2:
1454 raise OSError(errno.EINTR, "fake interrupted system call")
1455 return tuple(reversed(args))
1456
1457 self.assertEqual((999, 256),
1458 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1459 self.assertEqual([(256, 999)], record_calls)
1460 # This time there will be an EINTR so it will loop once.
1461 self.assertEqual((666,),
1462 subprocess._eintr_retry_call(fake_os_func, 666))
1463 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1464
1465
Tim Golden126c2962010-08-11 14:20:40 +00001466@unittest.skipUnless(mswindows, "Windows-specific tests")
1467class CommandsWithSpaces (BaseTestCase):
1468
1469 def setUp(self):
1470 super().setUp()
1471 f, fname = mkstemp(".py", "te st")
1472 self.fname = fname.lower ()
1473 os.write(f, b"import sys;"
1474 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1475 )
1476 os.close(f)
1477
1478 def tearDown(self):
1479 os.remove(self.fname)
1480 super().tearDown()
1481
1482 def with_spaces(self, *args, **kwargs):
1483 kwargs['stdout'] = subprocess.PIPE
1484 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001485 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001486 self.assertEqual(
1487 p.stdout.read ().decode("mbcs"),
1488 "2 [%r, 'ab cd']" % self.fname
1489 )
1490
1491 def test_shell_string_with_spaces(self):
1492 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001493 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1494 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001495
1496 def test_shell_sequence_with_spaces(self):
1497 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001498 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001499
1500 def test_noshell_string_with_spaces(self):
1501 # call() function with string argument with spaces on Windows
1502 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1503 "ab cd"))
1504
1505 def test_noshell_sequence_with_spaces(self):
1506 # call() function with sequence argument with spaces on Windows
1507 self.with_spaces([sys.executable, self.fname, "ab cd"])
1508
Brian Curtin79cdb662010-12-03 02:46:02 +00001509
1510class ContextManagerTests(ProcessTestCase):
1511
1512 def test_pipe(self):
1513 with subprocess.Popen([sys.executable, "-c",
1514 "import sys;"
1515 "sys.stdout.write('stdout');"
1516 "sys.stderr.write('stderr');"],
1517 stdout=subprocess.PIPE,
1518 stderr=subprocess.PIPE) as proc:
1519 self.assertEqual(proc.stdout.read(), b"stdout")
1520 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1521
1522 self.assertTrue(proc.stdout.closed)
1523 self.assertTrue(proc.stderr.closed)
1524
1525 def test_returncode(self):
1526 with subprocess.Popen([sys.executable, "-c",
1527 "import sys; sys.exit(100)"]) as proc:
1528 proc.wait()
1529 self.assertEqual(proc.returncode, 100)
1530
1531 def test_communicate_stdin(self):
1532 with subprocess.Popen([sys.executable, "-c",
1533 "import sys;"
1534 "sys.exit(sys.stdin.read() == 'context')"],
1535 stdin=subprocess.PIPE) as proc:
1536 proc.communicate(b"context")
1537 self.assertEqual(proc.returncode, 1)
1538
1539 def test_invalid_args(self):
1540 with self.assertRaises(EnvironmentError) as c:
1541 with subprocess.Popen(['nonexisting_i_hope'],
1542 stdout=subprocess.PIPE,
1543 stderr=subprocess.PIPE) as proc:
1544 pass
1545
1546 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1547 raise c.exception
1548
1549
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001550def test_main():
1551 unit_tests = (ProcessTestCase,
1552 POSIXProcessTestCase,
1553 Win32ProcessTestCase,
1554 ProcessTestCasePOSIXPurePython,
1555 CommandTests,
1556 ProcessTestCaseNoPoll,
1557 HelperFunctionTests,
1558 CommandsWithSpaces,
1559 ContextManagerTests)
1560
1561 support.run_unittest(*unit_tests)
1562 support.reap_children()
1563
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001564if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001565 unittest.main()