blob: 5100a207af2ee2eeac7a1d986386a1021d37e026 [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
6import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00007import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008import tempfile
9import time
Tim Peters3761e8d2004-10-13 04:07:12 +000010import re
Ezio Melotti184bdfb2010-02-18 09:37:05 +000011import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000012import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000013import select
Gregory P. Smith32ec9da2010-03-19 16:53:08 +000014try:
15 import gc
16except ImportError:
17 gc = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000018
19mswindows = (sys.platform == "win32")
20
21#
22# Depends on the following external programs: Python
23#
24
25if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000026 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
27 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000028else:
29 SETBINARY = ''
30
Florent Xiclunab1e94e82010-02-27 22:12:37 +000031
32try:
33 mkstemp = tempfile.mkstemp
34except AttributeError:
35 # tempfile.mkstemp is not available
36 def mkstemp():
37 """Replacement for mkstemp, calling mktemp."""
38 fname = tempfile.mktemp()
39 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
40
Tim Peters3761e8d2004-10-13 04:07:12 +000041
Florent Xiclunac049d872010-03-27 22:47:23 +000042class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000043 def setUp(self):
44 # Try to minimize the number of children we have so this test
45 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000046 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000047
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000048 def tearDown(self):
49 for inst in subprocess._active:
50 inst.wait()
51 subprocess._cleanup()
52 self.assertFalse(subprocess._active, "subprocess._active not empty")
53
Florent Xiclunab1e94e82010-02-27 22:12:37 +000054 def assertStderrEqual(self, stderr, expected, msg=None):
55 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
56 # shutdown time. That frustrates tests trying to check stderr produced
57 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000058 actual = support.strip_python_stderr(stderr)
Florent Xiclunab1e94e82010-02-27 22:12:37 +000059 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000060
Florent Xiclunac049d872010-03-27 22:47:23 +000061
62class ProcessTestCase(BaseTestCase):
63
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000064 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000065 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000066 rc = subprocess.call([sys.executable, "-c",
67 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000068 self.assertEqual(rc, 47)
69
Peter Astrand454f7672005-01-01 09:36:35 +000070 def test_check_call_zero(self):
71 # check_call() function with zero return code
72 rc = subprocess.check_call([sys.executable, "-c",
73 "import sys; sys.exit(0)"])
74 self.assertEqual(rc, 0)
75
76 def test_check_call_nonzero(self):
77 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000078 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000079 subprocess.check_call([sys.executable, "-c",
80 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000081 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000082
Georg Brandlf9734072008-12-07 15:30:06 +000083 def test_check_output(self):
84 # check_output() function with zero return code
85 output = subprocess.check_output(
86 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000087 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000088
89 def test_check_output_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:
Georg Brandlf9734072008-12-07 15:30:06 +000092 subprocess.check_output(
93 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000094 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +000095
96 def test_check_output_stderr(self):
97 # check_output() function stderr redirected to stdout
98 output = subprocess.check_output(
99 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
100 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000101 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000102
103 def test_check_output_stdout_arg(self):
104 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000105 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000106 output = subprocess.check_output(
107 [sys.executable, "-c", "print('will not be run')"],
108 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000109 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000110 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000111
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000112 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000113 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 newenv = os.environ.copy()
115 newenv["FRUIT"] = "banana"
116 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000117 'import sys, os;'
118 'sys.exit(os.getenv("FRUIT")=="banana")'],
119 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000120 self.assertEqual(rc, 1)
121
122 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000123 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000124 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000125 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000126 self.addCleanup(p.stdout.close)
127 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000128 p.wait()
129 self.assertEqual(p.stdin, None)
130
131 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000132 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000133 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000134 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000135 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000136 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000137 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000138 self.addCleanup(p.stdin.close)
139 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140 p.wait()
141 self.assertEqual(p.stdout, None)
142
143 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000144 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000145 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000146 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000147 self.addCleanup(p.stdout.close)
148 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000149 p.wait()
150 self.assertEqual(p.stderr, None)
151
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000152 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000153 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000154 p = subprocess.Popen(["somethingyoudonthave", "-c",
155 "import sys; sys.exit(47)"],
156 executable=sys.executable, cwd=python_dir)
157 p.wait()
158 self.assertEqual(p.returncode, 47)
159
160 @unittest.skipIf(sysconfig.is_python_build(),
161 "need an installed Python. See #7774")
162 def test_executable_without_cwd(self):
163 # For a normal installation, it should work without 'cwd'
164 # argument. For test runs in the build directory, see #7774.
165 p = subprocess.Popen(["somethingyoudonthave", "-c",
166 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000167 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000168 p.wait()
169 self.assertEqual(p.returncode, 47)
170
171 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000172 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000173 p = subprocess.Popen([sys.executable, "-c",
174 'import sys; sys.exit(sys.stdin.read() == "pear")'],
175 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000176 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000177 p.stdin.close()
178 p.wait()
179 self.assertEqual(p.returncode, 1)
180
181 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000182 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000183 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000184 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000185 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000186 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000187 os.lseek(d, 0, 0)
188 p = subprocess.Popen([sys.executable, "-c",
189 'import sys; sys.exit(sys.stdin.read() == "pear")'],
190 stdin=d)
191 p.wait()
192 self.assertEqual(p.returncode, 1)
193
194 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000195 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000196 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000197 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000198 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000199 tf.seek(0)
200 p = subprocess.Popen([sys.executable, "-c",
201 'import sys; sys.exit(sys.stdin.read() == "pear")'],
202 stdin=tf)
203 p.wait()
204 self.assertEqual(p.returncode, 1)
205
206 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000207 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000208 p = subprocess.Popen([sys.executable, "-c",
209 'import sys; sys.stdout.write("orange")'],
210 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000211 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000212 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000213
214 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000215 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000216 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000217 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000218 d = tf.fileno()
219 p = subprocess.Popen([sys.executable, "-c",
220 'import sys; sys.stdout.write("orange")'],
221 stdout=d)
222 p.wait()
223 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000224 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000225
226 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000227 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000228 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000229 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000230 p = subprocess.Popen([sys.executable, "-c",
231 'import sys; sys.stdout.write("orange")'],
232 stdout=tf)
233 p.wait()
234 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000235 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236
237 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000238 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239 p = subprocess.Popen([sys.executable, "-c",
240 'import sys; sys.stderr.write("strawberry")'],
241 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000242 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000243 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244
245 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000246 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000247 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000248 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000249 d = tf.fileno()
250 p = subprocess.Popen([sys.executable, "-c",
251 'import sys; sys.stderr.write("strawberry")'],
252 stderr=d)
253 p.wait()
254 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000255 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000256
257 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000258 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000259 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000260 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000261 p = subprocess.Popen([sys.executable, "-c",
262 'import sys; sys.stderr.write("strawberry")'],
263 stderr=tf)
264 p.wait()
265 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000266 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000267
268 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000269 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000271 'import sys;'
272 'sys.stdout.write("apple");'
273 'sys.stdout.flush();'
274 'sys.stderr.write("orange")'],
275 stdout=subprocess.PIPE,
276 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000277 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000278 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000279
280 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000281 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000283 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000284 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000285 'import sys;'
286 'sys.stdout.write("apple");'
287 'sys.stdout.flush();'
288 'sys.stderr.write("orange")'],
289 stdout=tf,
290 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291 p.wait()
292 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000293 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294
Thomas Wouters89f507f2006-12-13 04:49:30 +0000295 def test_stdout_filedes_of_stdout(self):
296 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000297 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000298 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000299 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000300
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000301 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000302 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000303 # We cannot use os.path.realpath to canonicalize the path,
304 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
305 cwd = os.getcwd()
306 os.chdir(tmpdir)
307 tmpdir = os.getcwd()
308 os.chdir(cwd)
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,os;'
311 'sys.stdout.write(os.getcwd())'],
312 stdout=subprocess.PIPE,
313 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000314 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000315 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000316 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
317 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318
319 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000320 newenv = os.environ.copy()
321 newenv["FRUIT"] = "orange"
322 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000323 'import sys,os;'
324 'sys.stdout.write(os.getenv("FRUIT"))'],
325 stdout=subprocess.PIPE,
326 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000327 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000328 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000329
Peter Astrandcbac93c2005-03-03 20:24:28 +0000330 def test_communicate_stdin(self):
331 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000332 'import sys;'
333 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000334 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000335 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000336 self.assertEqual(p.returncode, 1)
337
338 def test_communicate_stdout(self):
339 p = subprocess.Popen([sys.executable, "-c",
340 'import sys; sys.stdout.write("pineapple")'],
341 stdout=subprocess.PIPE)
342 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000343 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000344 self.assertEqual(stderr, None)
345
346 def test_communicate_stderr(self):
347 p = subprocess.Popen([sys.executable, "-c",
348 'import sys; sys.stderr.write("pineapple")'],
349 stderr=subprocess.PIPE)
350 (stdout, stderr) = p.communicate()
351 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000352 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000353
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000355 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000356 'import sys,os;'
357 'sys.stderr.write("pineapple");'
358 'sys.stdout.write(sys.stdin.read())'],
359 stdin=subprocess.PIPE,
360 stdout=subprocess.PIPE,
361 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000362 self.addCleanup(p.stdout.close)
363 self.addCleanup(p.stderr.close)
364 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000365 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000366 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000367 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000368
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000369 # Test for the fd leak reported in http://bugs.python.org/issue2791.
370 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000371 for stdin_pipe in (False, True):
372 for stdout_pipe in (False, True):
373 for stderr_pipe in (False, True):
374 options = {}
375 if stdin_pipe:
376 options['stdin'] = subprocess.PIPE
377 if stdout_pipe:
378 options['stdout'] = subprocess.PIPE
379 if stderr_pipe:
380 options['stderr'] = subprocess.PIPE
381 if not options:
382 continue
383 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
384 p.communicate()
385 if p.stdin is not None:
386 self.assertTrue(p.stdin.closed)
387 if p.stdout is not None:
388 self.assertTrue(p.stdout.closed)
389 if p.stderr is not None:
390 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000391
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000392 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000393 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000394 p = subprocess.Popen([sys.executable, "-c",
395 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000396 (stdout, stderr) = p.communicate()
397 self.assertEqual(stdout, None)
398 self.assertEqual(stderr, None)
399
400 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000401 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000402 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000403 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000404 x, y = os.pipe()
405 if mswindows:
406 pipe_buf = 512
407 else:
408 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
409 os.close(x)
410 os.close(y)
411 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000412 'import sys,os;'
413 'sys.stdout.write(sys.stdin.read(47));'
414 'sys.stderr.write("xyz"*%d);'
415 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
416 stdin=subprocess.PIPE,
417 stdout=subprocess.PIPE,
418 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000419 self.addCleanup(p.stdout.close)
420 self.addCleanup(p.stderr.close)
421 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000422 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 (stdout, stderr) = p.communicate(string_to_write)
424 self.assertEqual(stdout, string_to_write)
425
426 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000427 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000428 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000429 'import sys,os;'
430 'sys.stdout.write(sys.stdin.read())'],
431 stdin=subprocess.PIPE,
432 stdout=subprocess.PIPE,
433 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000434 self.addCleanup(p.stdout.close)
435 self.addCleanup(p.stderr.close)
436 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000437 p.stdin.write(b"banana")
438 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000439 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000440 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000441
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000442 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000443 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000444 'import sys,os;' + SETBINARY +
445 'sys.stdout.write("line1\\n");'
446 'sys.stdout.flush();'
447 'sys.stdout.write("line2\\n");'
448 'sys.stdout.flush();'
449 'sys.stdout.write("line3\\r\\n");'
450 'sys.stdout.flush();'
451 'sys.stdout.write("line4\\r");'
452 'sys.stdout.flush();'
453 'sys.stdout.write("\\nline5");'
454 'sys.stdout.flush();'
455 'sys.stdout.write("\\nline6");'],
456 stdout=subprocess.PIPE,
457 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000458 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000460 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000461
462 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000463 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000465 'import sys,os;' + SETBINARY +
466 'sys.stdout.write("line1\\n");'
467 'sys.stdout.flush();'
468 'sys.stdout.write("line2\\n");'
469 'sys.stdout.flush();'
470 'sys.stdout.write("line3\\r\\n");'
471 'sys.stdout.flush();'
472 'sys.stdout.write("line4\\r");'
473 'sys.stdout.flush();'
474 'sys.stdout.write("\\nline5");'
475 'sys.stdout.flush();'
476 'sys.stdout.write("\\nline6");'],
477 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
478 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000479 self.addCleanup(p.stdout.close)
480 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000482 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483
484 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000485 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000486 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000487 max_handles = 1026 # too much for most UNIX systems
488 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000489 max_handles = 2050 # too much for (at least some) Windows setups
490 handles = []
491 try:
492 for i in range(max_handles):
493 try:
494 handles.append(os.open(support.TESTFN,
495 os.O_WRONLY | os.O_CREAT))
496 except OSError as e:
497 if e.errno != errno.EMFILE:
498 raise
499 break
500 else:
501 self.skipTest("failed to reach the file descriptor limit "
502 "(tried %d)" % max_handles)
503 # Close a couple of them (should be enough for a subprocess)
504 for i in range(10):
505 os.close(handles.pop())
506 # Loop creating some subprocesses. If one of them leaks some fds,
507 # the next loop iteration will fail by reaching the max fd limit.
508 for i in range(15):
509 p = subprocess.Popen([sys.executable, "-c",
510 "import sys;"
511 "sys.stdout.write(sys.stdin.read())"],
512 stdin=subprocess.PIPE,
513 stdout=subprocess.PIPE,
514 stderr=subprocess.PIPE)
515 data = p.communicate(b"lime")[0]
516 self.assertEqual(data, b"lime")
517 finally:
518 for h in handles:
519 os.close(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520
521 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
523 '"a b c" d e')
524 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
525 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000526 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
527 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
529 'a\\\\\\b "de fg" h')
530 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
531 'a\\\\\\"b c d')
532 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
533 '"a\\\\b c" d e')
534 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
535 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000536 self.assertEqual(subprocess.list2cmdline(['ab', '']),
537 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000538
539
540 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000541 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000542 "-c", "import time; time.sleep(1)"])
543 count = 0
544 while p.poll() is None:
545 time.sleep(0.1)
546 count += 1
547 # We expect that the poll loop probably went around about 10 times,
548 # but, based on system scheduling we can't control, it's possible
549 # poll() never returned None. It "should be" very rare that it
550 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000551 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000552 # Subsequent invocations should just return the returncode
553 self.assertEqual(p.poll(), 0)
554
555
556 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000557 p = subprocess.Popen([sys.executable,
558 "-c", "import time; time.sleep(2)"])
559 self.assertEqual(p.wait(), 0)
560 # Subsequent invocations should just return the returncode
561 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000562
Peter Astrand738131d2004-11-30 21:04:45 +0000563
564 def test_invalid_bufsize(self):
565 # an invalid type of the bufsize argument should raise
566 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000567 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000568 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000569
Guido van Rossum46a05a72007-06-07 21:56:45 +0000570 def test_bufsize_is_none(self):
571 # bufsize=None should be the same as bufsize=0.
572 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
573 self.assertEqual(p.wait(), 0)
574 # Again with keyword arg
575 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
576 self.assertEqual(p.wait(), 0)
577
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000578 def test_leaking_fds_on_error(self):
579 # see bug #5179: Popen leaks file descriptors to PIPEs if
580 # the child fails to execute; this will eventually exhaust
581 # the maximum number of open fds. 1024 seems a very common
582 # value for that limit, but Windows has 2048, so we loop
583 # 1024 times (each call leaked two fds).
584 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000585 # Windows raises IOError. Others raise OSError.
586 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000587 subprocess.Popen(['nonexisting_i_hope'],
588 stdout=subprocess.PIPE,
589 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400590 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400591 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000592 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000593
Victor Stinnerb3693582010-05-21 20:13:12 +0000594 def test_issue8780(self):
595 # Ensure that stdout is inherited from the parent
596 # if stdout=PIPE is not used
597 code = ';'.join((
598 'import subprocess, sys',
599 'retcode = subprocess.call('
600 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
601 'assert retcode == 0'))
602 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000603 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000604
Tim Goldenaf5ac392010-08-06 13:03:56 +0000605 def test_handles_closed_on_exception(self):
606 # If CreateProcess exits with an error, ensure the
607 # duplicate output handles are released
608 ifhandle, ifname = mkstemp()
609 ofhandle, ofname = mkstemp()
610 efhandle, efname = mkstemp()
611 try:
612 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
613 stderr=efhandle)
614 except OSError:
615 os.close(ifhandle)
616 os.remove(ifname)
617 os.close(ofhandle)
618 os.remove(ofname)
619 os.close(efhandle)
620 os.remove(efname)
621 self.assertFalse(os.path.exists(ifname))
622 self.assertFalse(os.path.exists(ofname))
623 self.assertFalse(os.path.exists(efname))
624
Tim Peterse718f612004-10-12 21:51:32 +0000625
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000626# context manager
627class _SuppressCoreFiles(object):
628 """Try to prevent core files from being created."""
629 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000630
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000631 def __enter__(self):
632 """Try to save previous ulimit, then set it to (0, 0)."""
633 try:
634 import resource
635 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
636 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
637 except (ImportError, ValueError, resource.error):
638 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000639
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000640 if sys.platform == 'darwin':
641 # Check if the 'Crash Reporter' on OSX was configured
642 # in 'Developer' mode and warn that it will get triggered
643 # when it is.
644 #
645 # This assumes that this context manager is used in tests
646 # that might trigger the next manager.
647 value = subprocess.Popen(['/usr/bin/defaults', 'read',
648 'com.apple.CrashReporter', 'DialogType'],
649 stdout=subprocess.PIPE).communicate()[0]
650 if value.strip() == b'developer':
651 print("this tests triggers the Crash Reporter, "
652 "that is intentional", end='')
653 sys.stdout.flush()
654
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000655 def __exit__(self, *args):
656 """Return core file behavior to default."""
657 if self.old_limit is None:
658 return
659 try:
660 import resource
661 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
662 except (ImportError, ValueError, resource.error):
663 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000664
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000665
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000666@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000667class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000668
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000669 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000670 nonexistent_dir = "/_this/pa.th/does/not/exist"
671 try:
672 os.chdir(nonexistent_dir)
673 except OSError as e:
674 # This avoids hard coding the errno value or the OS perror()
675 # string and instead capture the exception that we want to see
676 # below for comparison.
677 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000678 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000679 else:
680 self.fail("chdir to nonexistant directory %s succeeded." %
681 nonexistent_dir)
682
683 # Error in the child re-raised in the parent.
684 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000685 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000686 cwd=nonexistent_dir)
687 except OSError as e:
688 # Test that the child process chdir failure actually makes
689 # it up to the parent process as the correct exception.
690 self.assertEqual(desired_exception.errno, e.errno)
691 self.assertEqual(desired_exception.strerror, e.strerror)
692 else:
693 self.fail("Expected OSError: %s" % desired_exception)
694
695 def test_restore_signals(self):
696 # Code coverage for both values of restore_signals to make sure it
697 # at least does not blow up.
698 # A test for behavior would be complex. Contributions welcome.
699 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
700 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
701
702 def test_start_new_session(self):
703 # For code coverage of calling setsid(). We don't care if we get an
704 # EPERM error from it depending on the test execution environment, that
705 # still indicates that it was called.
706 try:
707 output = subprocess.check_output(
708 [sys.executable, "-c",
709 "import os; print(os.getpgid(os.getpid()))"],
710 start_new_session=True)
711 except OSError as e:
712 if e.errno != errno.EPERM:
713 raise
714 else:
715 parent_pgid = os.getpgid(os.getpid())
716 child_pgid = int(output)
717 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000718
719 def test_run_abort(self):
720 # returncode handles signal termination
721 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000722 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000723 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000724 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000725 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000726
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000727 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000728 # DISCLAIMER: Setting environment variables is *not* a good use
729 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000730 p = subprocess.Popen([sys.executable, "-c",
731 'import sys,os;'
732 'sys.stdout.write(os.getenv("FRUIT"))'],
733 stdout=subprocess.PIPE,
734 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000735 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000736 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000737
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000738 def test_preexec_exception(self):
739 def raise_it():
740 raise ValueError("What if two swallows carried a coconut?")
741 try:
742 p = subprocess.Popen([sys.executable, "-c", ""],
743 preexec_fn=raise_it)
744 except RuntimeError as e:
745 self.assertTrue(
746 subprocess._posixsubprocess,
747 "Expected a ValueError from the preexec_fn")
748 except ValueError as e:
749 self.assertIn("coconut", e.args[0])
750 else:
751 self.fail("Exception raised by preexec_fn did not make it "
752 "to the parent process.")
753
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000754 @unittest.skipUnless(gc, "Requires a gc module.")
755 def test_preexec_gc_module_failure(self):
756 # This tests the code that disables garbage collection if the child
757 # process will execute any Python.
758 def raise_runtime_error():
759 raise RuntimeError("this shouldn't escape")
760 enabled = gc.isenabled()
761 orig_gc_disable = gc.disable
762 orig_gc_isenabled = gc.isenabled
763 try:
764 gc.disable()
765 self.assertFalse(gc.isenabled())
766 subprocess.call([sys.executable, '-c', ''],
767 preexec_fn=lambda: None)
768 self.assertFalse(gc.isenabled(),
769 "Popen enabled gc when it shouldn't.")
770
771 gc.enable()
772 self.assertTrue(gc.isenabled())
773 subprocess.call([sys.executable, '-c', ''],
774 preexec_fn=lambda: None)
775 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
776
777 gc.disable = raise_runtime_error
778 self.assertRaises(RuntimeError, subprocess.Popen,
779 [sys.executable, '-c', ''],
780 preexec_fn=lambda: None)
781
782 del gc.isenabled # force an AttributeError
783 self.assertRaises(AttributeError, subprocess.Popen,
784 [sys.executable, '-c', ''],
785 preexec_fn=lambda: None)
786 finally:
787 gc.disable = orig_gc_disable
788 gc.isenabled = orig_gc_isenabled
789 if not enabled:
790 gc.disable()
791
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000792 def test_args_string(self):
793 # args is a string
794 fd, fname = mkstemp()
795 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000796 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000797 fobj.write("#!/bin/sh\n")
798 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
799 sys.executable)
800 os.chmod(fname, 0o700)
801 p = subprocess.Popen(fname)
802 p.wait()
803 os.remove(fname)
804 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000805
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000806 def test_invalid_args(self):
807 # invalid arguments should raise ValueError
808 self.assertRaises(ValueError, subprocess.call,
809 [sys.executable, "-c",
810 "import sys; sys.exit(47)"],
811 startupinfo=47)
812 self.assertRaises(ValueError, subprocess.call,
813 [sys.executable, "-c",
814 "import sys; sys.exit(47)"],
815 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000816
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000817 def test_shell_sequence(self):
818 # Run command through the shell (sequence)
819 newenv = os.environ.copy()
820 newenv["FRUIT"] = "apple"
821 p = subprocess.Popen(["echo $FRUIT"], shell=1,
822 stdout=subprocess.PIPE,
823 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000824 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000825 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000826
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000827 def test_shell_string(self):
828 # Run command through the shell (string)
829 newenv = os.environ.copy()
830 newenv["FRUIT"] = "apple"
831 p = subprocess.Popen("echo $FRUIT", shell=1,
832 stdout=subprocess.PIPE,
833 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000834 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000835 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000836
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000837 def test_call_string(self):
838 # call() function with string argument on UNIX
839 fd, fname = mkstemp()
840 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000841 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000842 fobj.write("#!/bin/sh\n")
843 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
844 sys.executable)
845 os.chmod(fname, 0o700)
846 rc = subprocess.call(fname)
847 os.remove(fname)
848 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000849
Stefan Krah9542cc62010-07-19 14:20:53 +0000850 def test_specific_shell(self):
851 # Issue #9265: Incorrect name passed as arg[0].
852 shells = []
853 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
854 for name in ['bash', 'ksh']:
855 sh = os.path.join(prefix, name)
856 if os.path.isfile(sh):
857 shells.append(sh)
858 if not shells: # Will probably work for any shell but csh.
859 self.skipTest("bash or ksh required for this test")
860 sh = '/bin/sh'
861 if os.path.isfile(sh) and not os.path.islink(sh):
862 # Test will fail if /bin/sh is a symlink to csh.
863 shells.append(sh)
864 for sh in shells:
865 p = subprocess.Popen("echo $0", executable=sh, shell=True,
866 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000867 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000868 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
869
Florent Xicluna4886d242010-03-08 13:27:26 +0000870 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000871 # Do not inherit file handles from the parent.
872 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000873 p = subprocess.Popen([sys.executable, "-c", """if 1:
874 import sys, time
875 sys.stdout.write('x\\n')
876 sys.stdout.flush()
877 time.sleep(30)
878 """],
879 close_fds=True,
880 stdin=subprocess.PIPE,
881 stdout=subprocess.PIPE,
882 stderr=subprocess.PIPE)
883 # Wait for the interpreter to be completely initialized before
884 # sending any signal.
885 p.stdout.read(1)
886 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000887 return p
888
889 def test_send_signal(self):
890 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000891 _, stderr = p.communicate()
892 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000893 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000894
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000895 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000896 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000897 _, stderr = p.communicate()
898 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000899 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000900
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000901 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000902 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000903 _, stderr = p.communicate()
904 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000905 self.assertEqual(p.wait(), -signal.SIGTERM)
906
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000907 def check_close_std_fds(self, fds):
908 # Issue #9905: test that subprocess pipes still work properly with
909 # some standard fds closed
910 stdin = 0
911 newfds = []
912 for a in fds:
913 b = os.dup(a)
914 newfds.append(b)
915 if a == 0:
916 stdin = b
917 try:
918 for fd in fds:
919 os.close(fd)
920 out, err = subprocess.Popen([sys.executable, "-c",
921 'import sys;'
922 'sys.stdout.write("apple");'
923 'sys.stdout.flush();'
924 'sys.stderr.write("orange")'],
925 stdin=stdin,
926 stdout=subprocess.PIPE,
927 stderr=subprocess.PIPE).communicate()
928 err = support.strip_python_stderr(err)
929 self.assertEqual((out, err), (b'apple', b'orange'))
930 finally:
931 for b, a in zip(newfds, fds):
932 os.dup2(b, a)
933 for b in newfds:
934 os.close(b)
935
936 def test_close_fd_0(self):
937 self.check_close_std_fds([0])
938
939 def test_close_fd_1(self):
940 self.check_close_std_fds([1])
941
942 def test_close_fd_2(self):
943 self.check_close_std_fds([2])
944
945 def test_close_fds_0_1(self):
946 self.check_close_std_fds([0, 1])
947
948 def test_close_fds_0_2(self):
949 self.check_close_std_fds([0, 2])
950
951 def test_close_fds_1_2(self):
952 self.check_close_std_fds([1, 2])
953
954 def test_close_fds_0_1_2(self):
955 # Issue #10806: test that subprocess pipes still work properly with
956 # all standard fds closed.
957 self.check_close_std_fds([0, 1, 2])
958
Antoine Pitrou95aaeee2011-01-03 21:15:48 +0000959 def test_remapping_std_fds(self):
960 # open up some temporary files
961 temps = [mkstemp() for i in range(3)]
962 try:
963 temp_fds = [fd for fd, fname in temps]
964
965 # unlink the files -- we won't need to reopen them
966 for fd, fname in temps:
967 os.unlink(fname)
968
969 # write some data to what will become stdin, and rewind
970 os.write(temp_fds[1], b"STDIN")
971 os.lseek(temp_fds[1], 0, 0)
972
973 # move the standard file descriptors out of the way
974 saved_fds = [os.dup(fd) for fd in range(3)]
975 try:
976 # duplicate the file objects over the standard fd's
977 for fd, temp_fd in enumerate(temp_fds):
978 os.dup2(temp_fd, fd)
979
980 # now use those files in the "wrong" order, so that subprocess
981 # has to rearrange them in the child
982 p = subprocess.Popen([sys.executable, "-c",
983 'import sys; got = sys.stdin.read();'
984 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
985 stdin=temp_fds[1],
986 stdout=temp_fds[2],
987 stderr=temp_fds[0])
988 p.wait()
989 finally:
990 # restore the original fd's underneath sys.stdin, etc.
991 for std, saved in enumerate(saved_fds):
992 os.dup2(saved, std)
993 os.close(saved)
994
995 for fd in temp_fds:
996 os.lseek(fd, 0, 0)
997
998 out = os.read(temp_fds[2], 1024)
999 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1000 self.assertEqual(out, b"got STDIN")
1001 self.assertEqual(err, b"err")
1002
1003 finally:
1004 for fd in temp_fds:
1005 os.close(fd)
1006
Victor Stinner13bb71c2010-04-23 21:41:56 +00001007 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001008 def prepare():
1009 raise ValueError("surrogate:\uDCff")
1010
1011 try:
1012 subprocess.call(
1013 [sys.executable, "-c", "pass"],
1014 preexec_fn=prepare)
1015 except ValueError as err:
1016 # Pure Python implementations keeps the message
1017 self.assertIsNone(subprocess._posixsubprocess)
1018 self.assertEqual(str(err), "surrogate:\uDCff")
1019 except RuntimeError as err:
1020 # _posixsubprocess uses a default message
1021 self.assertIsNotNone(subprocess._posixsubprocess)
1022 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1023 else:
1024 self.fail("Expected ValueError or RuntimeError")
1025
Victor Stinner13bb71c2010-04-23 21:41:56 +00001026 def test_undecodable_env(self):
1027 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001028 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001029 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001030 env = os.environ.copy()
1031 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001032 # Use C locale to get ascii for the locale encoding to force
1033 # surrogate-escaping of \xFF in the child process; otherwise it can
1034 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001035 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001036 stdout = subprocess.check_output(
1037 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001038 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001039 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001040 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001041
1042 # test bytes
1043 key = key.encode("ascii", "surrogateescape")
1044 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001045 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001046 env = os.environ.copy()
1047 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001048 stdout = subprocess.check_output(
1049 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001050 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001051 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001052 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001053
Victor Stinnerb745a742010-05-18 17:17:23 +00001054 def test_bytes_program(self):
1055 abs_program = os.fsencode(sys.executable)
1056 path, program = os.path.split(sys.executable)
1057 program = os.fsencode(program)
1058
1059 # absolute bytes path
1060 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001061 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001062
1063 # bytes program, unicode PATH
1064 env = os.environ.copy()
1065 env["PATH"] = path
1066 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001067 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001068
1069 # bytes program, bytes PATH
1070 envb = os.environb.copy()
1071 envb[b"PATH"] = os.fsencode(path)
1072 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001073 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001074
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001075 def test_pipe_cloexec(self):
1076 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1077 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1078
1079 p1 = subprocess.Popen([sys.executable, sleeper],
1080 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1081 stderr=subprocess.PIPE, close_fds=False)
1082
1083 self.addCleanup(p1.communicate, b'')
1084
1085 p2 = subprocess.Popen([sys.executable, fd_status],
1086 stdout=subprocess.PIPE, close_fds=False)
1087
1088 output, error = p2.communicate()
1089 result_fds = set(map(int, output.split(b',')))
1090 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1091 p1.stderr.fileno()])
1092
1093 self.assertFalse(result_fds & unwanted_fds,
1094 "Expected no fds from %r to be open in child, "
1095 "found %r" %
1096 (unwanted_fds, result_fds & unwanted_fds))
1097
1098 def test_pipe_cloexec_real_tools(self):
1099 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1100 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1101
1102 subdata = b'zxcvbn'
1103 data = subdata * 4 + b'\n'
1104
1105 p1 = subprocess.Popen([sys.executable, qcat],
1106 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1107 close_fds=False)
1108
1109 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1110 stdin=p1.stdout, stdout=subprocess.PIPE,
1111 close_fds=False)
1112
1113 self.addCleanup(p1.wait)
1114 self.addCleanup(p2.wait)
1115 self.addCleanup(p1.terminate)
1116 self.addCleanup(p2.terminate)
1117
1118 p1.stdin.write(data)
1119 p1.stdin.close()
1120
1121 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1122
1123 self.assertTrue(readfiles, "The child hung")
1124 self.assertEqual(p2.stdout.read(), data)
1125
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001126 p1.stdout.close()
1127 p2.stdout.close()
1128
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001129 def test_close_fds(self):
1130 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1131
1132 fds = os.pipe()
1133 self.addCleanup(os.close, fds[0])
1134 self.addCleanup(os.close, fds[1])
1135
1136 open_fds = set(fds)
1137
1138 p = subprocess.Popen([sys.executable, fd_status],
1139 stdout=subprocess.PIPE, close_fds=False)
1140 output, ignored = p.communicate()
1141 remaining_fds = set(map(int, output.split(b',')))
1142
1143 self.assertEqual(remaining_fds & open_fds, open_fds,
1144 "Some fds were closed")
1145
1146 p = subprocess.Popen([sys.executable, fd_status],
1147 stdout=subprocess.PIPE, close_fds=True)
1148 output, ignored = p.communicate()
1149 remaining_fds = set(map(int, output.split(b',')))
1150
1151 self.assertFalse(remaining_fds & open_fds,
1152 "Some fds were left open")
1153 self.assertIn(1, remaining_fds, "Subprocess failed")
1154
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001155 def test_pass_fds(self):
1156 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1157
1158 open_fds = set()
1159
1160 for x in range(5):
1161 fds = os.pipe()
1162 self.addCleanup(os.close, fds[0])
1163 self.addCleanup(os.close, fds[1])
1164 open_fds.update(fds)
1165
1166 for fd in open_fds:
1167 p = subprocess.Popen([sys.executable, fd_status],
1168 stdout=subprocess.PIPE, close_fds=True,
1169 pass_fds=(fd, ))
1170 output, ignored = p.communicate()
1171
1172 remaining_fds = set(map(int, output.split(b',')))
1173 to_be_closed = open_fds - {fd}
1174
1175 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1176 self.assertFalse(remaining_fds & to_be_closed,
1177 "fd to be closed passed")
1178
1179 # pass_fds overrides close_fds with a warning.
1180 with self.assertWarns(RuntimeWarning) as context:
1181 self.assertFalse(subprocess.call(
1182 [sys.executable, "-c", "import sys; sys.exit(0)"],
1183 close_fds=False, pass_fds=(fd, )))
1184 self.assertIn('overriding close_fds', str(context.warning))
1185
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001186 def test_wait_when_sigchild_ignored(self):
1187 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1188 sigchild_ignore = support.findfile("sigchild_ignore.py",
1189 subdir="subprocessdata")
1190 p = subprocess.Popen([sys.executable, sigchild_ignore],
1191 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1192 stdout, stderr = p.communicate()
1193 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001194 " non-zero with this error:\n%s" %
1195 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001196
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001197
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001198@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001199class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001200
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001201 def test_startupinfo(self):
1202 # startupinfo argument
1203 # We uses hardcoded constants, because we do not want to
1204 # depend on win32all.
1205 STARTF_USESHOWWINDOW = 1
1206 SW_MAXIMIZE = 3
1207 startupinfo = subprocess.STARTUPINFO()
1208 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1209 startupinfo.wShowWindow = SW_MAXIMIZE
1210 # Since Python is a console process, it won't be affected
1211 # by wShowWindow, but the argument should be silently
1212 # ignored
1213 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001214 startupinfo=startupinfo)
1215
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001216 def test_creationflags(self):
1217 # creationflags argument
1218 CREATE_NEW_CONSOLE = 16
1219 sys.stderr.write(" a DOS box should flash briefly ...\n")
1220 subprocess.call(sys.executable +
1221 ' -c "import time; time.sleep(0.25)"',
1222 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001223
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001224 def test_invalid_args(self):
1225 # invalid arguments should raise ValueError
1226 self.assertRaises(ValueError, subprocess.call,
1227 [sys.executable, "-c",
1228 "import sys; sys.exit(47)"],
1229 preexec_fn=lambda: 1)
1230 self.assertRaises(ValueError, subprocess.call,
1231 [sys.executable, "-c",
1232 "import sys; sys.exit(47)"],
1233 stdout=subprocess.PIPE,
1234 close_fds=True)
1235
1236 def test_close_fds(self):
1237 # close file descriptors
1238 rc = subprocess.call([sys.executable, "-c",
1239 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001240 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001241 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001242
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001243 def test_shell_sequence(self):
1244 # Run command through the shell (sequence)
1245 newenv = os.environ.copy()
1246 newenv["FRUIT"] = "physalis"
1247 p = subprocess.Popen(["set"], shell=1,
1248 stdout=subprocess.PIPE,
1249 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001250 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001251 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001252
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001253 def test_shell_string(self):
1254 # Run command through the shell (string)
1255 newenv = os.environ.copy()
1256 newenv["FRUIT"] = "physalis"
1257 p = subprocess.Popen("set", shell=1,
1258 stdout=subprocess.PIPE,
1259 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001260 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001261 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001262
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001263 def test_call_string(self):
1264 # call() function with string argument on Windows
1265 rc = subprocess.call(sys.executable +
1266 ' -c "import sys; sys.exit(47)"')
1267 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001268
Florent Xicluna4886d242010-03-08 13:27:26 +00001269 def _kill_process(self, method, *args):
1270 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001271 p = subprocess.Popen([sys.executable, "-c", """if 1:
1272 import sys, time
1273 sys.stdout.write('x\\n')
1274 sys.stdout.flush()
1275 time.sleep(30)
1276 """],
1277 stdin=subprocess.PIPE,
1278 stdout=subprocess.PIPE,
1279 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001280 self.addCleanup(p.stdout.close)
1281 self.addCleanup(p.stderr.close)
1282 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001283 # Wait for the interpreter to be completely initialized before
1284 # sending any signal.
1285 p.stdout.read(1)
1286 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001287 _, stderr = p.communicate()
1288 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001289 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001290 self.assertNotEqual(returncode, 0)
1291
1292 def test_send_signal(self):
1293 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001294
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001295 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001296 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001297
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001298 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001299 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001300
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001301
Brett Cannona23810f2008-05-26 19:04:21 +00001302# The module says:
1303# "NB This only works (and is only relevant) for UNIX."
1304#
1305# Actually, getoutput should work on any platform with an os.popen, but
1306# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001307@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001308class CommandTests(unittest.TestCase):
1309 def test_getoutput(self):
1310 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1311 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1312 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001313
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001314 # we use mkdtemp in the next line to create an empty directory
1315 # under our exclusive control; from that, we can invent a pathname
1316 # that we _know_ won't exist. This is guaranteed to fail.
1317 dir = None
1318 try:
1319 dir = tempfile.mkdtemp()
1320 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001321
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001322 status, output = subprocess.getstatusoutput('cat ' + name)
1323 self.assertNotEqual(status, 0)
1324 finally:
1325 if dir is not None:
1326 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001327
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001328
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001329@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1330 "poll system call not supported")
1331class ProcessTestCaseNoPoll(ProcessTestCase):
1332 def setUp(self):
1333 subprocess._has_poll = False
1334 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001335
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001336 def tearDown(self):
1337 subprocess._has_poll = True
1338 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001339
1340
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001341@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1342 "_posixsubprocess extension module not found.")
1343class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
1344 def setUp(self):
1345 subprocess._posixsubprocess = None
1346 ProcessTestCase.setUp(self)
1347 POSIXProcessTestCase.setUp(self)
1348
1349 def tearDown(self):
1350 subprocess._posixsubprocess = sys.modules['_posixsubprocess']
1351 POSIXProcessTestCase.tearDown(self)
1352 ProcessTestCase.tearDown(self)
1353
1354
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001355class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001356 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001357 def test_eintr_retry_call(self):
1358 record_calls = []
1359 def fake_os_func(*args):
1360 record_calls.append(args)
1361 if len(record_calls) == 2:
1362 raise OSError(errno.EINTR, "fake interrupted system call")
1363 return tuple(reversed(args))
1364
1365 self.assertEqual((999, 256),
1366 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1367 self.assertEqual([(256, 999)], record_calls)
1368 # This time there will be an EINTR so it will loop once.
1369 self.assertEqual((666,),
1370 subprocess._eintr_retry_call(fake_os_func, 666))
1371 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1372
1373
Tim Golden126c2962010-08-11 14:20:40 +00001374@unittest.skipUnless(mswindows, "Windows-specific tests")
1375class CommandsWithSpaces (BaseTestCase):
1376
1377 def setUp(self):
1378 super().setUp()
1379 f, fname = mkstemp(".py", "te st")
1380 self.fname = fname.lower ()
1381 os.write(f, b"import sys;"
1382 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1383 )
1384 os.close(f)
1385
1386 def tearDown(self):
1387 os.remove(self.fname)
1388 super().tearDown()
1389
1390 def with_spaces(self, *args, **kwargs):
1391 kwargs['stdout'] = subprocess.PIPE
1392 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001393 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001394 self.assertEqual(
1395 p.stdout.read ().decode("mbcs"),
1396 "2 [%r, 'ab cd']" % self.fname
1397 )
1398
1399 def test_shell_string_with_spaces(self):
1400 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001401 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1402 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001403
1404 def test_shell_sequence_with_spaces(self):
1405 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001406 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001407
1408 def test_noshell_string_with_spaces(self):
1409 # call() function with string argument with spaces on Windows
1410 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1411 "ab cd"))
1412
1413 def test_noshell_sequence_with_spaces(self):
1414 # call() function with sequence argument with spaces on Windows
1415 self.with_spaces([sys.executable, self.fname, "ab cd"])
1416
Brian Curtin79cdb662010-12-03 02:46:02 +00001417
1418class ContextManagerTests(ProcessTestCase):
1419
1420 def test_pipe(self):
1421 with subprocess.Popen([sys.executable, "-c",
1422 "import sys;"
1423 "sys.stdout.write('stdout');"
1424 "sys.stderr.write('stderr');"],
1425 stdout=subprocess.PIPE,
1426 stderr=subprocess.PIPE) as proc:
1427 self.assertEqual(proc.stdout.read(), b"stdout")
1428 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1429
1430 self.assertTrue(proc.stdout.closed)
1431 self.assertTrue(proc.stderr.closed)
1432
1433 def test_returncode(self):
1434 with subprocess.Popen([sys.executable, "-c",
1435 "import sys; sys.exit(100)"]) as proc:
1436 proc.wait()
1437 self.assertEqual(proc.returncode, 100)
1438
1439 def test_communicate_stdin(self):
1440 with subprocess.Popen([sys.executable, "-c",
1441 "import sys;"
1442 "sys.exit(sys.stdin.read() == 'context')"],
1443 stdin=subprocess.PIPE) as proc:
1444 proc.communicate(b"context")
1445 self.assertEqual(proc.returncode, 1)
1446
1447 def test_invalid_args(self):
1448 with self.assertRaises(EnvironmentError) as c:
1449 with subprocess.Popen(['nonexisting_i_hope'],
1450 stdout=subprocess.PIPE,
1451 stderr=subprocess.PIPE) as proc:
1452 pass
1453
1454 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1455 raise c.exception
1456
1457
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001458def test_main():
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001459 unit_tests = (ProcessTestCase,
1460 POSIXProcessTestCase,
1461 Win32ProcessTestCase,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001462 ProcessTestCasePOSIXPurePython,
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001463 CommandTests,
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001464 ProcessTestCaseNoPoll,
Tim Golden126c2962010-08-11 14:20:40 +00001465 HelperFunctionTests,
Brian Curtin79cdb662010-12-03 02:46:02 +00001466 CommandsWithSpaces,
Gregory P. Smithf5604852010-12-13 06:45:02 +00001467 ContextManagerTests)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001468
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001469 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +00001470 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001471
1472if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +00001473 test_main()