blob: 46e50c350bf103f6394c0d4a744ccd74a72536c6 [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. Smithe14e9c22011-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)
Florent Xiclunab1e94e82010-02-27 22:12:37 +000061 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000062
Florent Xiclunac049d872010-03-27 22:47:23 +000063
64class ProcessTestCase(BaseTestCase):
65
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000066 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000067 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000068 rc = subprocess.call([sys.executable, "-c",
69 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000070 self.assertEqual(rc, 47)
71
Peter Astrand454f7672005-01-01 09:36:35 +000072 def test_check_call_zero(self):
73 # check_call() function with zero return code
74 rc = subprocess.check_call([sys.executable, "-c",
75 "import sys; sys.exit(0)"])
76 self.assertEqual(rc, 0)
77
78 def test_check_call_nonzero(self):
79 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000080 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000081 subprocess.check_call([sys.executable, "-c",
82 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000083 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000084
Georg Brandlf9734072008-12-07 15:30:06 +000085 def test_check_output(self):
86 # check_output() function with zero return code
87 output = subprocess.check_output(
88 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000089 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000090
91 def test_check_output_nonzero(self):
92 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000093 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +000094 subprocess.check_output(
95 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000096 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +000097
98 def test_check_output_stderr(self):
99 # check_output() function stderr redirected to stdout
100 output = subprocess.check_output(
101 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
102 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000103 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000104
105 def test_check_output_stdout_arg(self):
106 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000107 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000108 output = subprocess.check_output(
109 [sys.executable, "-c", "print('will not be run')"],
110 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000111 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000112 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000113
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000115 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000116 newenv = os.environ.copy()
117 newenv["FRUIT"] = "banana"
118 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000119 'import sys, os;'
120 'sys.exit(os.getenv("FRUIT")=="banana")'],
121 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000122 self.assertEqual(rc, 1)
123
124 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000125 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000126 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000127 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000128 self.addCleanup(p.stdout.close)
129 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000130 p.wait()
131 self.assertEqual(p.stdin, None)
132
133 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000134 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000135 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000136 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000137 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000138 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000139 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000140 self.addCleanup(p.stdin.close)
141 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000142 p.wait()
143 self.assertEqual(p.stdout, None)
144
145 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000146 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000147 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000148 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000149 self.addCleanup(p.stdout.close)
150 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000151 p.wait()
152 self.assertEqual(p.stderr, None)
153
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000154 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000155 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000156 p = subprocess.Popen(["somethingyoudonthave", "-c",
157 "import sys; sys.exit(47)"],
158 executable=sys.executable, cwd=python_dir)
159 p.wait()
160 self.assertEqual(p.returncode, 47)
161
162 @unittest.skipIf(sysconfig.is_python_build(),
163 "need an installed Python. See #7774")
164 def test_executable_without_cwd(self):
165 # For a normal installation, it should work without 'cwd'
166 # argument. For test runs in the build directory, see #7774.
167 p = subprocess.Popen(["somethingyoudonthave", "-c",
168 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000169 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000170 p.wait()
171 self.assertEqual(p.returncode, 47)
172
173 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000174 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000175 p = subprocess.Popen([sys.executable, "-c",
176 'import sys; sys.exit(sys.stdin.read() == "pear")'],
177 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000178 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000179 p.stdin.close()
180 p.wait()
181 self.assertEqual(p.returncode, 1)
182
183 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000184 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000185 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000186 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000187 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000188 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 os.lseek(d, 0, 0)
190 p = subprocess.Popen([sys.executable, "-c",
191 'import sys; sys.exit(sys.stdin.read() == "pear")'],
192 stdin=d)
193 p.wait()
194 self.assertEqual(p.returncode, 1)
195
196 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000197 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000198 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000199 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000200 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000201 tf.seek(0)
202 p = subprocess.Popen([sys.executable, "-c",
203 'import sys; sys.exit(sys.stdin.read() == "pear")'],
204 stdin=tf)
205 p.wait()
206 self.assertEqual(p.returncode, 1)
207
208 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000209 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210 p = subprocess.Popen([sys.executable, "-c",
211 'import sys; sys.stdout.write("orange")'],
212 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000213 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000214 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000215
216 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000217 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000218 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000219 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000220 d = tf.fileno()
221 p = subprocess.Popen([sys.executable, "-c",
222 'import sys; sys.stdout.write("orange")'],
223 stdout=d)
224 p.wait()
225 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000226 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227
228 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000229 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000230 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000231 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000232 p = subprocess.Popen([sys.executable, "-c",
233 'import sys; sys.stdout.write("orange")'],
234 stdout=tf)
235 p.wait()
236 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000237 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238
239 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000240 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000241 p = subprocess.Popen([sys.executable, "-c",
242 'import sys; sys.stderr.write("strawberry")'],
243 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000244 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000245 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000246
247 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000248 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000249 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000250 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251 d = tf.fileno()
252 p = subprocess.Popen([sys.executable, "-c",
253 'import sys; sys.stderr.write("strawberry")'],
254 stderr=d)
255 p.wait()
256 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000257 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000258
259 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000260 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000261 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000262 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263 p = subprocess.Popen([sys.executable, "-c",
264 'import sys; sys.stderr.write("strawberry")'],
265 stderr=tf)
266 p.wait()
267 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000268 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269
270 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000271 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000272 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000273 'import sys;'
274 'sys.stdout.write("apple");'
275 'sys.stdout.flush();'
276 'sys.stderr.write("orange")'],
277 stdout=subprocess.PIPE,
278 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000279 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000280 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281
282 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000283 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +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",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000287 'import sys;'
288 'sys.stdout.write("apple");'
289 'sys.stdout.flush();'
290 'sys.stderr.write("orange")'],
291 stdout=tf,
292 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293 p.wait()
294 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000295 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296
Thomas Wouters89f507f2006-12-13 04:49:30 +0000297 def test_stdout_filedes_of_stdout(self):
298 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000299 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000300 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000301 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000302
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000303 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000304 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000305 # We cannot use os.path.realpath to canonicalize the path,
306 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
307 cwd = os.getcwd()
308 os.chdir(tmpdir)
309 tmpdir = os.getcwd()
310 os.chdir(cwd)
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,os;'
313 'sys.stdout.write(os.getcwd())'],
314 stdout=subprocess.PIPE,
315 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000316 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000317 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000318 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
319 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000320
321 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000322 newenv = os.environ.copy()
323 newenv["FRUIT"] = "orange"
324 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000325 'import sys,os;'
326 'sys.stdout.write(os.getenv("FRUIT"))'],
327 stdout=subprocess.PIPE,
328 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000329 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000330 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000331
Peter Astrandcbac93c2005-03-03 20:24:28 +0000332 def test_communicate_stdin(self):
333 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000334 'import sys;'
335 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000336 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000337 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000338 self.assertEqual(p.returncode, 1)
339
340 def test_communicate_stdout(self):
341 p = subprocess.Popen([sys.executable, "-c",
342 'import sys; sys.stdout.write("pineapple")'],
343 stdout=subprocess.PIPE)
344 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000345 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000346 self.assertEqual(stderr, None)
347
348 def test_communicate_stderr(self):
349 p = subprocess.Popen([sys.executable, "-c",
350 'import sys; sys.stderr.write("pineapple")'],
351 stderr=subprocess.PIPE)
352 (stdout, stderr) = p.communicate()
353 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000354 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000355
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000356 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000357 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000358 'import sys,os;'
359 'sys.stderr.write("pineapple");'
360 'sys.stdout.write(sys.stdin.read())'],
361 stdin=subprocess.PIPE,
362 stdout=subprocess.PIPE,
363 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000364 self.addCleanup(p.stdout.close)
365 self.addCleanup(p.stderr.close)
366 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000367 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000368 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000369 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000371 # Test for the fd leak reported in http://bugs.python.org/issue2791.
372 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000373 for stdin_pipe in (False, True):
374 for stdout_pipe in (False, True):
375 for stderr_pipe in (False, True):
376 options = {}
377 if stdin_pipe:
378 options['stdin'] = subprocess.PIPE
379 if stdout_pipe:
380 options['stdout'] = subprocess.PIPE
381 if stderr_pipe:
382 options['stderr'] = subprocess.PIPE
383 if not options:
384 continue
385 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
386 p.communicate()
387 if p.stdin is not None:
388 self.assertTrue(p.stdin.closed)
389 if p.stdout is not None:
390 self.assertTrue(p.stdout.closed)
391 if p.stderr is not None:
392 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000393
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000394 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000395 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000396 p = subprocess.Popen([sys.executable, "-c",
397 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000398 (stdout, stderr) = p.communicate()
399 self.assertEqual(stdout, None)
400 self.assertEqual(stderr, None)
401
402 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000403 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000404 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000405 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000406 x, y = os.pipe()
407 if mswindows:
408 pipe_buf = 512
409 else:
410 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
411 os.close(x)
412 os.close(y)
413 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000414 'import sys,os;'
415 'sys.stdout.write(sys.stdin.read(47));'
416 'sys.stderr.write("xyz"*%d);'
417 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
418 stdin=subprocess.PIPE,
419 stdout=subprocess.PIPE,
420 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000421 self.addCleanup(p.stdout.close)
422 self.addCleanup(p.stderr.close)
423 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000424 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000425 (stdout, stderr) = p.communicate(string_to_write)
426 self.assertEqual(stdout, string_to_write)
427
428 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000429 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000430 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000431 'import sys,os;'
432 'sys.stdout.write(sys.stdin.read())'],
433 stdin=subprocess.PIPE,
434 stdout=subprocess.PIPE,
435 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000436 self.addCleanup(p.stdout.close)
437 self.addCleanup(p.stderr.close)
438 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000439 p.stdin.write(b"banana")
440 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000441 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000442 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000443
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000445 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000446 'import sys,os;' + SETBINARY +
447 'sys.stdout.write("line1\\n");'
448 'sys.stdout.flush();'
449 'sys.stdout.write("line2\\n");'
450 'sys.stdout.flush();'
451 'sys.stdout.write("line3\\r\\n");'
452 'sys.stdout.flush();'
453 'sys.stdout.write("line4\\r");'
454 'sys.stdout.flush();'
455 'sys.stdout.write("\\nline5");'
456 'sys.stdout.flush();'
457 'sys.stdout.write("\\nline6");'],
458 stdout=subprocess.PIPE,
459 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000460 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000461 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000462 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463
464 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000465 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000467 'import sys,os;' + SETBINARY +
468 'sys.stdout.write("line1\\n");'
469 'sys.stdout.flush();'
470 'sys.stdout.write("line2\\n");'
471 'sys.stdout.flush();'
472 'sys.stdout.write("line3\\r\\n");'
473 'sys.stdout.flush();'
474 'sys.stdout.write("line4\\r");'
475 'sys.stdout.flush();'
476 'sys.stdout.write("\\nline5");'
477 'sys.stdout.flush();'
478 'sys.stdout.write("\\nline6");'],
479 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
480 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000481 self.addCleanup(p.stdout.close)
482 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000484 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485
486 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000487 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000488 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000489 max_handles = 1026 # too much for most UNIX systems
490 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000491 max_handles = 2050 # too much for (at least some) Windows setups
492 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400493 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000494 try:
495 for i in range(max_handles):
496 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400497 tmpfile = os.path.join(tmpdir, support.TESTFN)
498 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000499 except OSError as e:
500 if e.errno != errno.EMFILE:
501 raise
502 break
503 else:
504 self.skipTest("failed to reach the file descriptor limit "
505 "(tried %d)" % max_handles)
506 # Close a couple of them (should be enough for a subprocess)
507 for i in range(10):
508 os.close(handles.pop())
509 # Loop creating some subprocesses. If one of them leaks some fds,
510 # the next loop iteration will fail by reaching the max fd limit.
511 for i in range(15):
512 p = subprocess.Popen([sys.executable, "-c",
513 "import sys;"
514 "sys.stdout.write(sys.stdin.read())"],
515 stdin=subprocess.PIPE,
516 stdout=subprocess.PIPE,
517 stderr=subprocess.PIPE)
518 data = p.communicate(b"lime")[0]
519 self.assertEqual(data, b"lime")
520 finally:
521 for h in handles:
522 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400523 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000524
525 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
527 '"a b c" d e')
528 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
529 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000530 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
531 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
533 'a\\\\\\b "de fg" h')
534 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
535 'a\\\\\\"b c d')
536 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
537 '"a\\\\b c" d e')
538 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
539 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000540 self.assertEqual(subprocess.list2cmdline(['ab', '']),
541 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542
543
544 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000546 "-c", "import time; time.sleep(1)"])
547 count = 0
548 while p.poll() is None:
549 time.sleep(0.1)
550 count += 1
551 # We expect that the poll loop probably went around about 10 times,
552 # but, based on system scheduling we can't control, it's possible
553 # poll() never returned None. It "should be" very rare that it
554 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000555 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556 # Subsequent invocations should just return the returncode
557 self.assertEqual(p.poll(), 0)
558
559
560 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561 p = subprocess.Popen([sys.executable,
562 "-c", "import time; time.sleep(2)"])
563 self.assertEqual(p.wait(), 0)
564 # Subsequent invocations should just return the returncode
565 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000566
Peter Astrand738131d2004-11-30 21:04:45 +0000567
568 def test_invalid_bufsize(self):
569 # an invalid type of the bufsize argument should raise
570 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000571 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000572 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000573
Guido van Rossum46a05a72007-06-07 21:56:45 +0000574 def test_bufsize_is_none(self):
575 # bufsize=None should be the same as bufsize=0.
576 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
577 self.assertEqual(p.wait(), 0)
578 # Again with keyword arg
579 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
580 self.assertEqual(p.wait(), 0)
581
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000582 def test_leaking_fds_on_error(self):
583 # see bug #5179: Popen leaks file descriptors to PIPEs if
584 # the child fails to execute; this will eventually exhaust
585 # the maximum number of open fds. 1024 seems a very common
586 # value for that limit, but Windows has 2048, so we loop
587 # 1024 times (each call leaked two fds).
588 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000589 # Windows raises IOError. Others raise OSError.
590 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000591 subprocess.Popen(['nonexisting_i_hope'],
592 stdout=subprocess.PIPE,
593 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400594 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400595 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000596 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000597
Victor Stinnerb3693582010-05-21 20:13:12 +0000598 def test_issue8780(self):
599 # Ensure that stdout is inherited from the parent
600 # if stdout=PIPE is not used
601 code = ';'.join((
602 'import subprocess, sys',
603 'retcode = subprocess.call('
604 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
605 'assert retcode == 0'))
606 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000607 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000608
Tim Goldenaf5ac392010-08-06 13:03:56 +0000609 def test_handles_closed_on_exception(self):
610 # If CreateProcess exits with an error, ensure the
611 # duplicate output handles are released
612 ifhandle, ifname = mkstemp()
613 ofhandle, ofname = mkstemp()
614 efhandle, efname = mkstemp()
615 try:
616 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
617 stderr=efhandle)
618 except OSError:
619 os.close(ifhandle)
620 os.remove(ifname)
621 os.close(ofhandle)
622 os.remove(ofname)
623 os.close(efhandle)
624 os.remove(efname)
625 self.assertFalse(os.path.exists(ifname))
626 self.assertFalse(os.path.exists(ofname))
627 self.assertFalse(os.path.exists(efname))
628
Tim Peterse718f612004-10-12 21:51:32 +0000629
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000630# context manager
631class _SuppressCoreFiles(object):
632 """Try to prevent core files from being created."""
633 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000634
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000635 def __enter__(self):
636 """Try to save previous ulimit, then set it to (0, 0)."""
637 try:
638 import resource
639 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
640 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
641 except (ImportError, ValueError, resource.error):
642 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000643
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000644 if sys.platform == 'darwin':
645 # Check if the 'Crash Reporter' on OSX was configured
646 # in 'Developer' mode and warn that it will get triggered
647 # when it is.
648 #
649 # This assumes that this context manager is used in tests
650 # that might trigger the next manager.
651 value = subprocess.Popen(['/usr/bin/defaults', 'read',
652 'com.apple.CrashReporter', 'DialogType'],
653 stdout=subprocess.PIPE).communicate()[0]
654 if value.strip() == b'developer':
655 print("this tests triggers the Crash Reporter, "
656 "that is intentional", end='')
657 sys.stdout.flush()
658
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000659 def __exit__(self, *args):
660 """Return core file behavior to default."""
661 if self.old_limit is None:
662 return
663 try:
664 import resource
665 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
666 except (ImportError, ValueError, resource.error):
667 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000668
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000669
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000670@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000671class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000672
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000673 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000674 nonexistent_dir = "/_this/pa.th/does/not/exist"
675 try:
676 os.chdir(nonexistent_dir)
677 except OSError as e:
678 # This avoids hard coding the errno value or the OS perror()
679 # string and instead capture the exception that we want to see
680 # below for comparison.
681 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000682 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000683 else:
684 self.fail("chdir to nonexistant directory %s succeeded." %
685 nonexistent_dir)
686
687 # Error in the child re-raised in the parent.
688 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000689 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000690 cwd=nonexistent_dir)
691 except OSError as e:
692 # Test that the child process chdir failure actually makes
693 # it up to the parent process as the correct exception.
694 self.assertEqual(desired_exception.errno, e.errno)
695 self.assertEqual(desired_exception.strerror, e.strerror)
696 else:
697 self.fail("Expected OSError: %s" % desired_exception)
698
699 def test_restore_signals(self):
700 # Code coverage for both values of restore_signals to make sure it
701 # at least does not blow up.
702 # A test for behavior would be complex. Contributions welcome.
703 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
704 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
705
706 def test_start_new_session(self):
707 # For code coverage of calling setsid(). We don't care if we get an
708 # EPERM error from it depending on the test execution environment, that
709 # still indicates that it was called.
710 try:
711 output = subprocess.check_output(
712 [sys.executable, "-c",
713 "import os; print(os.getpgid(os.getpid()))"],
714 start_new_session=True)
715 except OSError as e:
716 if e.errno != errno.EPERM:
717 raise
718 else:
719 parent_pgid = os.getpgid(os.getpid())
720 child_pgid = int(output)
721 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000722
723 def test_run_abort(self):
724 # returncode handles signal termination
725 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000726 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000727 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000728 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000729 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000731 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000732 # DISCLAIMER: Setting environment variables is *not* a good use
733 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000734 p = subprocess.Popen([sys.executable, "-c",
735 'import sys,os;'
736 'sys.stdout.write(os.getenv("FRUIT"))'],
737 stdout=subprocess.PIPE,
738 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000739 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000740 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000741
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000742 def test_preexec_exception(self):
743 def raise_it():
744 raise ValueError("What if two swallows carried a coconut?")
745 try:
746 p = subprocess.Popen([sys.executable, "-c", ""],
747 preexec_fn=raise_it)
748 except RuntimeError as e:
749 self.assertTrue(
750 subprocess._posixsubprocess,
751 "Expected a ValueError from the preexec_fn")
752 except ValueError as e:
753 self.assertIn("coconut", e.args[0])
754 else:
755 self.fail("Exception raised by preexec_fn did not make it "
756 "to the parent process.")
757
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000758 @unittest.skipUnless(gc, "Requires a gc module.")
759 def test_preexec_gc_module_failure(self):
760 # This tests the code that disables garbage collection if the child
761 # process will execute any Python.
762 def raise_runtime_error():
763 raise RuntimeError("this shouldn't escape")
764 enabled = gc.isenabled()
765 orig_gc_disable = gc.disable
766 orig_gc_isenabled = gc.isenabled
767 try:
768 gc.disable()
769 self.assertFalse(gc.isenabled())
770 subprocess.call([sys.executable, '-c', ''],
771 preexec_fn=lambda: None)
772 self.assertFalse(gc.isenabled(),
773 "Popen enabled gc when it shouldn't.")
774
775 gc.enable()
776 self.assertTrue(gc.isenabled())
777 subprocess.call([sys.executable, '-c', ''],
778 preexec_fn=lambda: None)
779 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
780
781 gc.disable = raise_runtime_error
782 self.assertRaises(RuntimeError, subprocess.Popen,
783 [sys.executable, '-c', ''],
784 preexec_fn=lambda: None)
785
786 del gc.isenabled # force an AttributeError
787 self.assertRaises(AttributeError, subprocess.Popen,
788 [sys.executable, '-c', ''],
789 preexec_fn=lambda: None)
790 finally:
791 gc.disable = orig_gc_disable
792 gc.isenabled = orig_gc_isenabled
793 if not enabled:
794 gc.disable()
795
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000796 def test_args_string(self):
797 # args is a string
798 fd, fname = mkstemp()
799 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000800 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000801 fobj.write("#!/bin/sh\n")
802 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
803 sys.executable)
804 os.chmod(fname, 0o700)
805 p = subprocess.Popen(fname)
806 p.wait()
807 os.remove(fname)
808 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000809
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000810 def test_invalid_args(self):
811 # invalid arguments should raise ValueError
812 self.assertRaises(ValueError, subprocess.call,
813 [sys.executable, "-c",
814 "import sys; sys.exit(47)"],
815 startupinfo=47)
816 self.assertRaises(ValueError, subprocess.call,
817 [sys.executable, "-c",
818 "import sys; sys.exit(47)"],
819 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000820
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000821 def test_shell_sequence(self):
822 # Run command through the shell (sequence)
823 newenv = os.environ.copy()
824 newenv["FRUIT"] = "apple"
825 p = subprocess.Popen(["echo $FRUIT"], shell=1,
826 stdout=subprocess.PIPE,
827 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000828 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000829 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000830
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000831 def test_shell_string(self):
832 # Run command through the shell (string)
833 newenv = os.environ.copy()
834 newenv["FRUIT"] = "apple"
835 p = subprocess.Popen("echo $FRUIT", shell=1,
836 stdout=subprocess.PIPE,
837 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000838 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000839 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000840
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000841 def test_call_string(self):
842 # call() function with string argument on UNIX
843 fd, fname = mkstemp()
844 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000845 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000846 fobj.write("#!/bin/sh\n")
847 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
848 sys.executable)
849 os.chmod(fname, 0o700)
850 rc = subprocess.call(fname)
851 os.remove(fname)
852 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000853
Stefan Krah9542cc62010-07-19 14:20:53 +0000854 def test_specific_shell(self):
855 # Issue #9265: Incorrect name passed as arg[0].
856 shells = []
857 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
858 for name in ['bash', 'ksh']:
859 sh = os.path.join(prefix, name)
860 if os.path.isfile(sh):
861 shells.append(sh)
862 if not shells: # Will probably work for any shell but csh.
863 self.skipTest("bash or ksh required for this test")
864 sh = '/bin/sh'
865 if os.path.isfile(sh) and not os.path.islink(sh):
866 # Test will fail if /bin/sh is a symlink to csh.
867 shells.append(sh)
868 for sh in shells:
869 p = subprocess.Popen("echo $0", executable=sh, shell=True,
870 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000871 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000872 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
873
Florent Xicluna4886d242010-03-08 13:27:26 +0000874 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000875 # Do not inherit file handles from the parent.
876 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000877 p = subprocess.Popen([sys.executable, "-c", """if 1:
878 import sys, time
879 sys.stdout.write('x\\n')
880 sys.stdout.flush()
881 time.sleep(30)
882 """],
883 close_fds=True,
884 stdin=subprocess.PIPE,
885 stdout=subprocess.PIPE,
886 stderr=subprocess.PIPE)
887 # Wait for the interpreter to be completely initialized before
888 # sending any signal.
889 p.stdout.read(1)
890 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000891 return p
892
893 def test_send_signal(self):
894 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000895 _, stderr = p.communicate()
896 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000897 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000898
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000899 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000900 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000901 _, stderr = p.communicate()
902 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000903 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000904
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000905 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000906 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000907 _, stderr = p.communicate()
908 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000909 self.assertEqual(p.wait(), -signal.SIGTERM)
910
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000911 def check_close_std_fds(self, fds):
912 # Issue #9905: test that subprocess pipes still work properly with
913 # some standard fds closed
914 stdin = 0
915 newfds = []
916 for a in fds:
917 b = os.dup(a)
918 newfds.append(b)
919 if a == 0:
920 stdin = b
921 try:
922 for fd in fds:
923 os.close(fd)
924 out, err = subprocess.Popen([sys.executable, "-c",
925 'import sys;'
926 'sys.stdout.write("apple");'
927 'sys.stdout.flush();'
928 'sys.stderr.write("orange")'],
929 stdin=stdin,
930 stdout=subprocess.PIPE,
931 stderr=subprocess.PIPE).communicate()
932 err = support.strip_python_stderr(err)
933 self.assertEqual((out, err), (b'apple', b'orange'))
934 finally:
935 for b, a in zip(newfds, fds):
936 os.dup2(b, a)
937 for b in newfds:
938 os.close(b)
939
940 def test_close_fd_0(self):
941 self.check_close_std_fds([0])
942
943 def test_close_fd_1(self):
944 self.check_close_std_fds([1])
945
946 def test_close_fd_2(self):
947 self.check_close_std_fds([2])
948
949 def test_close_fds_0_1(self):
950 self.check_close_std_fds([0, 1])
951
952 def test_close_fds_0_2(self):
953 self.check_close_std_fds([0, 2])
954
955 def test_close_fds_1_2(self):
956 self.check_close_std_fds([1, 2])
957
958 def test_close_fds_0_1_2(self):
959 # Issue #10806: test that subprocess pipes still work properly with
960 # all standard fds closed.
961 self.check_close_std_fds([0, 1, 2])
962
Antoine Pitrou95aaeee2011-01-03 21:15:48 +0000963 def test_remapping_std_fds(self):
964 # open up some temporary files
965 temps = [mkstemp() for i in range(3)]
966 try:
967 temp_fds = [fd for fd, fname in temps]
968
969 # unlink the files -- we won't need to reopen them
970 for fd, fname in temps:
971 os.unlink(fname)
972
973 # write some data to what will become stdin, and rewind
974 os.write(temp_fds[1], b"STDIN")
975 os.lseek(temp_fds[1], 0, 0)
976
977 # move the standard file descriptors out of the way
978 saved_fds = [os.dup(fd) for fd in range(3)]
979 try:
980 # duplicate the file objects over the standard fd's
981 for fd, temp_fd in enumerate(temp_fds):
982 os.dup2(temp_fd, fd)
983
984 # now use those files in the "wrong" order, so that subprocess
985 # has to rearrange them in the child
986 p = subprocess.Popen([sys.executable, "-c",
987 'import sys; got = sys.stdin.read();'
988 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
989 stdin=temp_fds[1],
990 stdout=temp_fds[2],
991 stderr=temp_fds[0])
992 p.wait()
993 finally:
994 # restore the original fd's underneath sys.stdin, etc.
995 for std, saved in enumerate(saved_fds):
996 os.dup2(saved, std)
997 os.close(saved)
998
999 for fd in temp_fds:
1000 os.lseek(fd, 0, 0)
1001
1002 out = os.read(temp_fds[2], 1024)
1003 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1004 self.assertEqual(out, b"got STDIN")
1005 self.assertEqual(err, b"err")
1006
1007 finally:
1008 for fd in temp_fds:
1009 os.close(fd)
1010
Victor Stinner13bb71c2010-04-23 21:41:56 +00001011 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001012 def prepare():
1013 raise ValueError("surrogate:\uDCff")
1014
1015 try:
1016 subprocess.call(
1017 [sys.executable, "-c", "pass"],
1018 preexec_fn=prepare)
1019 except ValueError as err:
1020 # Pure Python implementations keeps the message
1021 self.assertIsNone(subprocess._posixsubprocess)
1022 self.assertEqual(str(err), "surrogate:\uDCff")
1023 except RuntimeError as err:
1024 # _posixsubprocess uses a default message
1025 self.assertIsNotNone(subprocess._posixsubprocess)
1026 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1027 else:
1028 self.fail("Expected ValueError or RuntimeError")
1029
Victor Stinner13bb71c2010-04-23 21:41:56 +00001030 def test_undecodable_env(self):
1031 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001032 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001033 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001034 env = os.environ.copy()
1035 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001036 # Use C locale to get ascii for the locale encoding to force
1037 # surrogate-escaping of \xFF in the child process; otherwise it can
1038 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001039 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001040 stdout = subprocess.check_output(
1041 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001042 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001043 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001044 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001045
1046 # test bytes
1047 key = key.encode("ascii", "surrogateescape")
1048 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001049 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001050 env = os.environ.copy()
1051 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001052 stdout = subprocess.check_output(
1053 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001054 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001055 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001056 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001057
Victor Stinnerb745a742010-05-18 17:17:23 +00001058 def test_bytes_program(self):
1059 abs_program = os.fsencode(sys.executable)
1060 path, program = os.path.split(sys.executable)
1061 program = os.fsencode(program)
1062
1063 # absolute bytes path
1064 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001065 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001066
1067 # bytes program, unicode PATH
1068 env = os.environ.copy()
1069 env["PATH"] = path
1070 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001071 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001072
1073 # bytes program, bytes PATH
1074 envb = os.environb.copy()
1075 envb[b"PATH"] = os.fsencode(path)
1076 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001077 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001078
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001079 def test_pipe_cloexec(self):
1080 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1081 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1082
1083 p1 = subprocess.Popen([sys.executable, sleeper],
1084 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1085 stderr=subprocess.PIPE, close_fds=False)
1086
1087 self.addCleanup(p1.communicate, b'')
1088
1089 p2 = subprocess.Popen([sys.executable, fd_status],
1090 stdout=subprocess.PIPE, close_fds=False)
1091
1092 output, error = p2.communicate()
1093 result_fds = set(map(int, output.split(b',')))
1094 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1095 p1.stderr.fileno()])
1096
1097 self.assertFalse(result_fds & unwanted_fds,
1098 "Expected no fds from %r to be open in child, "
1099 "found %r" %
1100 (unwanted_fds, result_fds & unwanted_fds))
1101
1102 def test_pipe_cloexec_real_tools(self):
1103 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1104 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1105
1106 subdata = b'zxcvbn'
1107 data = subdata * 4 + b'\n'
1108
1109 p1 = subprocess.Popen([sys.executable, qcat],
1110 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1111 close_fds=False)
1112
1113 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1114 stdin=p1.stdout, stdout=subprocess.PIPE,
1115 close_fds=False)
1116
1117 self.addCleanup(p1.wait)
1118 self.addCleanup(p2.wait)
1119 self.addCleanup(p1.terminate)
1120 self.addCleanup(p2.terminate)
1121
1122 p1.stdin.write(data)
1123 p1.stdin.close()
1124
1125 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1126
1127 self.assertTrue(readfiles, "The child hung")
1128 self.assertEqual(p2.stdout.read(), data)
1129
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001130 p1.stdout.close()
1131 p2.stdout.close()
1132
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001133 def test_close_fds(self):
1134 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1135
1136 fds = os.pipe()
1137 self.addCleanup(os.close, fds[0])
1138 self.addCleanup(os.close, fds[1])
1139
1140 open_fds = set(fds)
1141
1142 p = subprocess.Popen([sys.executable, fd_status],
1143 stdout=subprocess.PIPE, close_fds=False)
1144 output, ignored = p.communicate()
1145 remaining_fds = set(map(int, output.split(b',')))
1146
1147 self.assertEqual(remaining_fds & open_fds, open_fds,
1148 "Some fds were closed")
1149
1150 p = subprocess.Popen([sys.executable, fd_status],
1151 stdout=subprocess.PIPE, close_fds=True)
1152 output, ignored = p.communicate()
1153 remaining_fds = set(map(int, output.split(b',')))
1154
1155 self.assertFalse(remaining_fds & open_fds,
1156 "Some fds were left open")
1157 self.assertIn(1, remaining_fds, "Subprocess failed")
1158
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001159 def test_pass_fds(self):
1160 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1161
1162 open_fds = set()
1163
1164 for x in range(5):
1165 fds = os.pipe()
1166 self.addCleanup(os.close, fds[0])
1167 self.addCleanup(os.close, fds[1])
1168 open_fds.update(fds)
1169
1170 for fd in open_fds:
1171 p = subprocess.Popen([sys.executable, fd_status],
1172 stdout=subprocess.PIPE, close_fds=True,
1173 pass_fds=(fd, ))
1174 output, ignored = p.communicate()
1175
1176 remaining_fds = set(map(int, output.split(b',')))
1177 to_be_closed = open_fds - {fd}
1178
1179 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1180 self.assertFalse(remaining_fds & to_be_closed,
1181 "fd to be closed passed")
1182
1183 # pass_fds overrides close_fds with a warning.
1184 with self.assertWarns(RuntimeWarning) as context:
1185 self.assertFalse(subprocess.call(
1186 [sys.executable, "-c", "import sys; sys.exit(0)"],
1187 close_fds=False, pass_fds=(fd, )))
1188 self.assertIn('overriding close_fds', str(context.warning))
1189
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001190 def test_stdout_stdin_are_single_inout_fd(self):
1191 with io.open(os.devnull, "r+") as inout:
1192 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1193 stdout=inout, stdin=inout)
1194 p.wait()
1195
1196 def test_stdout_stderr_are_single_inout_fd(self):
1197 with io.open(os.devnull, "r+") as inout:
1198 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1199 stdout=inout, stderr=inout)
1200 p.wait()
1201
1202 def test_stderr_stdin_are_single_inout_fd(self):
1203 with io.open(os.devnull, "r+") as inout:
1204 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1205 stderr=inout, stdin=inout)
1206 p.wait()
1207
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001208 def test_wait_when_sigchild_ignored(self):
1209 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1210 sigchild_ignore = support.findfile("sigchild_ignore.py",
1211 subdir="subprocessdata")
1212 p = subprocess.Popen([sys.executable, sigchild_ignore],
1213 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1214 stdout, stderr = p.communicate()
1215 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001216 " non-zero with this error:\n%s" %
1217 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001218
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001219
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001220@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001221class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001222
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001223 def test_startupinfo(self):
1224 # startupinfo argument
1225 # We uses hardcoded constants, because we do not want to
1226 # depend on win32all.
1227 STARTF_USESHOWWINDOW = 1
1228 SW_MAXIMIZE = 3
1229 startupinfo = subprocess.STARTUPINFO()
1230 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1231 startupinfo.wShowWindow = SW_MAXIMIZE
1232 # Since Python is a console process, it won't be affected
1233 # by wShowWindow, but the argument should be silently
1234 # ignored
1235 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001236 startupinfo=startupinfo)
1237
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001238 def test_creationflags(self):
1239 # creationflags argument
1240 CREATE_NEW_CONSOLE = 16
1241 sys.stderr.write(" a DOS box should flash briefly ...\n")
1242 subprocess.call(sys.executable +
1243 ' -c "import time; time.sleep(0.25)"',
1244 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001245
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001246 def test_invalid_args(self):
1247 # invalid arguments should raise ValueError
1248 self.assertRaises(ValueError, subprocess.call,
1249 [sys.executable, "-c",
1250 "import sys; sys.exit(47)"],
1251 preexec_fn=lambda: 1)
1252 self.assertRaises(ValueError, subprocess.call,
1253 [sys.executable, "-c",
1254 "import sys; sys.exit(47)"],
1255 stdout=subprocess.PIPE,
1256 close_fds=True)
1257
1258 def test_close_fds(self):
1259 # close file descriptors
1260 rc = subprocess.call([sys.executable, "-c",
1261 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001262 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001263 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001264
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001265 def test_shell_sequence(self):
1266 # Run command through the shell (sequence)
1267 newenv = os.environ.copy()
1268 newenv["FRUIT"] = "physalis"
1269 p = subprocess.Popen(["set"], shell=1,
1270 stdout=subprocess.PIPE,
1271 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001272 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001273 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001274
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001275 def test_shell_string(self):
1276 # Run command through the shell (string)
1277 newenv = os.environ.copy()
1278 newenv["FRUIT"] = "physalis"
1279 p = subprocess.Popen("set", shell=1,
1280 stdout=subprocess.PIPE,
1281 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001282 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001283 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001284
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001285 def test_call_string(self):
1286 # call() function with string argument on Windows
1287 rc = subprocess.call(sys.executable +
1288 ' -c "import sys; sys.exit(47)"')
1289 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001290
Florent Xicluna4886d242010-03-08 13:27:26 +00001291 def _kill_process(self, method, *args):
1292 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001293 p = subprocess.Popen([sys.executable, "-c", """if 1:
1294 import sys, time
1295 sys.stdout.write('x\\n')
1296 sys.stdout.flush()
1297 time.sleep(30)
1298 """],
1299 stdin=subprocess.PIPE,
1300 stdout=subprocess.PIPE,
1301 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001302 self.addCleanup(p.stdout.close)
1303 self.addCleanup(p.stderr.close)
1304 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001305 # Wait for the interpreter to be completely initialized before
1306 # sending any signal.
1307 p.stdout.read(1)
1308 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001309 _, stderr = p.communicate()
1310 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001311 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001312 self.assertNotEqual(returncode, 0)
1313
1314 def test_send_signal(self):
1315 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001316
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001317 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001318 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001319
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001320 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001321 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001322
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001323
Brett Cannona23810f2008-05-26 19:04:21 +00001324# The module says:
1325# "NB This only works (and is only relevant) for UNIX."
1326#
1327# Actually, getoutput should work on any platform with an os.popen, but
1328# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001329@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001330class CommandTests(unittest.TestCase):
1331 def test_getoutput(self):
1332 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1333 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1334 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001335
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001336 # we use mkdtemp in the next line to create an empty directory
1337 # under our exclusive control; from that, we can invent a pathname
1338 # that we _know_ won't exist. This is guaranteed to fail.
1339 dir = None
1340 try:
1341 dir = tempfile.mkdtemp()
1342 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001343
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001344 status, output = subprocess.getstatusoutput('cat ' + name)
1345 self.assertNotEqual(status, 0)
1346 finally:
1347 if dir is not None:
1348 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001349
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001350
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001351@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1352 "poll system call not supported")
1353class ProcessTestCaseNoPoll(ProcessTestCase):
1354 def setUp(self):
1355 subprocess._has_poll = False
1356 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001357
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001358 def tearDown(self):
1359 subprocess._has_poll = True
1360 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001361
1362
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001363@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1364 "_posixsubprocess extension module not found.")
1365class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
1366 def setUp(self):
1367 subprocess._posixsubprocess = None
1368 ProcessTestCase.setUp(self)
1369 POSIXProcessTestCase.setUp(self)
1370
1371 def tearDown(self):
1372 subprocess._posixsubprocess = sys.modules['_posixsubprocess']
1373 POSIXProcessTestCase.tearDown(self)
1374 ProcessTestCase.tearDown(self)
1375
1376
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001377class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001378 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001379 def test_eintr_retry_call(self):
1380 record_calls = []
1381 def fake_os_func(*args):
1382 record_calls.append(args)
1383 if len(record_calls) == 2:
1384 raise OSError(errno.EINTR, "fake interrupted system call")
1385 return tuple(reversed(args))
1386
1387 self.assertEqual((999, 256),
1388 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1389 self.assertEqual([(256, 999)], record_calls)
1390 # This time there will be an EINTR so it will loop once.
1391 self.assertEqual((666,),
1392 subprocess._eintr_retry_call(fake_os_func, 666))
1393 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1394
1395
Tim Golden126c2962010-08-11 14:20:40 +00001396@unittest.skipUnless(mswindows, "Windows-specific tests")
1397class CommandsWithSpaces (BaseTestCase):
1398
1399 def setUp(self):
1400 super().setUp()
1401 f, fname = mkstemp(".py", "te st")
1402 self.fname = fname.lower ()
1403 os.write(f, b"import sys;"
1404 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1405 )
1406 os.close(f)
1407
1408 def tearDown(self):
1409 os.remove(self.fname)
1410 super().tearDown()
1411
1412 def with_spaces(self, *args, **kwargs):
1413 kwargs['stdout'] = subprocess.PIPE
1414 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001415 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001416 self.assertEqual(
1417 p.stdout.read ().decode("mbcs"),
1418 "2 [%r, 'ab cd']" % self.fname
1419 )
1420
1421 def test_shell_string_with_spaces(self):
1422 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001423 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1424 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001425
1426 def test_shell_sequence_with_spaces(self):
1427 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001428 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001429
1430 def test_noshell_string_with_spaces(self):
1431 # call() function with string argument with spaces on Windows
1432 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1433 "ab cd"))
1434
1435 def test_noshell_sequence_with_spaces(self):
1436 # call() function with sequence argument with spaces on Windows
1437 self.with_spaces([sys.executable, self.fname, "ab cd"])
1438
Brian Curtin79cdb662010-12-03 02:46:02 +00001439
1440class ContextManagerTests(ProcessTestCase):
1441
1442 def test_pipe(self):
1443 with subprocess.Popen([sys.executable, "-c",
1444 "import sys;"
1445 "sys.stdout.write('stdout');"
1446 "sys.stderr.write('stderr');"],
1447 stdout=subprocess.PIPE,
1448 stderr=subprocess.PIPE) as proc:
1449 self.assertEqual(proc.stdout.read(), b"stdout")
1450 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1451
1452 self.assertTrue(proc.stdout.closed)
1453 self.assertTrue(proc.stderr.closed)
1454
1455 def test_returncode(self):
1456 with subprocess.Popen([sys.executable, "-c",
1457 "import sys; sys.exit(100)"]) as proc:
1458 proc.wait()
1459 self.assertEqual(proc.returncode, 100)
1460
1461 def test_communicate_stdin(self):
1462 with subprocess.Popen([sys.executable, "-c",
1463 "import sys;"
1464 "sys.exit(sys.stdin.read() == 'context')"],
1465 stdin=subprocess.PIPE) as proc:
1466 proc.communicate(b"context")
1467 self.assertEqual(proc.returncode, 1)
1468
1469 def test_invalid_args(self):
1470 with self.assertRaises(EnvironmentError) as c:
1471 with subprocess.Popen(['nonexisting_i_hope'],
1472 stdout=subprocess.PIPE,
1473 stderr=subprocess.PIPE) as proc:
1474 pass
1475
1476 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1477 raise c.exception
1478
1479
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001480if __name__ == "__main__":
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001481 unittest.main()
1482 support.reap_children()