blob: 73f44ad93af485e2646a397196dad023287cabd7 [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. Smith81ce6852011-03-15 02:04:11 -040014import shutil
Gregory P. Smith32ec9da2010-03-19 16:53:08 +000015try:
16 import gc
17except ImportError:
18 gc = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000019
20mswindows = (sys.platform == "win32")
21
22#
23# Depends on the following external programs: Python
24#
25
26if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000027 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
28 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000029else:
30 SETBINARY = ''
31
Florent Xiclunab1e94e82010-02-27 22:12:37 +000032
33try:
34 mkstemp = tempfile.mkstemp
35except AttributeError:
36 # tempfile.mkstemp is not available
37 def mkstemp():
38 """Replacement for mkstemp, calling mktemp."""
39 fname = tempfile.mktemp()
40 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
41
Tim Peters3761e8d2004-10-13 04:07:12 +000042
Florent Xiclunac049d872010-03-27 22:47:23 +000043class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000044 def setUp(self):
45 # Try to minimize the number of children we have so this test
46 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000047 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000048
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000049 def tearDown(self):
50 for inst in subprocess._active:
51 inst.wait()
52 subprocess._cleanup()
53 self.assertFalse(subprocess._active, "subprocess._active not empty")
54
Florent Xiclunab1e94e82010-02-27 22:12:37 +000055 def assertStderrEqual(self, stderr, expected, msg=None):
56 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
57 # shutdown time. That frustrates tests trying to check stderr produced
58 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000059 actual = support.strip_python_stderr(stderr)
Florent Xiclunab1e94e82010-02-27 22:12:37 +000060 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000061
Florent Xiclunac049d872010-03-27 22:47:23 +000062
63class ProcessTestCase(BaseTestCase):
64
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000065 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000066 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000067 rc = subprocess.call([sys.executable, "-c",
68 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000069 self.assertEqual(rc, 47)
70
Peter Astrand454f7672005-01-01 09:36:35 +000071 def test_check_call_zero(self):
72 # check_call() function with zero return code
73 rc = subprocess.check_call([sys.executable, "-c",
74 "import sys; sys.exit(0)"])
75 self.assertEqual(rc, 0)
76
77 def test_check_call_nonzero(self):
78 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000079 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000080 subprocess.check_call([sys.executable, "-c",
81 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000082 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000083
Georg Brandlf9734072008-12-07 15:30:06 +000084 def test_check_output(self):
85 # check_output() function with zero return code
86 output = subprocess.check_output(
87 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000088 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000089
90 def test_check_output_nonzero(self):
91 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000092 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +000093 subprocess.check_output(
94 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000095 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +000096
97 def test_check_output_stderr(self):
98 # check_output() function stderr redirected to stdout
99 output = subprocess.check_output(
100 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
101 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000102 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000103
104 def test_check_output_stdout_arg(self):
105 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000106 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000107 output = subprocess.check_output(
108 [sys.executable, "-c", "print('will not be run')"],
109 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000110 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000111 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000112
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000113 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000114 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000115 newenv = os.environ.copy()
116 newenv["FRUIT"] = "banana"
117 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000118 'import sys, os;'
119 'sys.exit(os.getenv("FRUIT")=="banana")'],
120 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000121 self.assertEqual(rc, 1)
122
123 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000124 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000125 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000126 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000127 self.addCleanup(p.stdout.close)
128 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000129 p.wait()
130 self.assertEqual(p.stdin, None)
131
132 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000133 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000134 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000135 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000136 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000137 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000138 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000139 self.addCleanup(p.stdin.close)
140 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000141 p.wait()
142 self.assertEqual(p.stdout, None)
143
144 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000145 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000146 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000147 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000148 self.addCleanup(p.stdout.close)
149 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000150 p.wait()
151 self.assertEqual(p.stderr, None)
152
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000153 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000154 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000155 p = subprocess.Popen(["somethingyoudonthave", "-c",
156 "import sys; sys.exit(47)"],
157 executable=sys.executable, cwd=python_dir)
158 p.wait()
159 self.assertEqual(p.returncode, 47)
160
161 @unittest.skipIf(sysconfig.is_python_build(),
162 "need an installed Python. See #7774")
163 def test_executable_without_cwd(self):
164 # For a normal installation, it should work without 'cwd'
165 # argument. For test runs in the build directory, see #7774.
166 p = subprocess.Popen(["somethingyoudonthave", "-c",
167 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000168 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000169 p.wait()
170 self.assertEqual(p.returncode, 47)
171
172 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000173 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000174 p = subprocess.Popen([sys.executable, "-c",
175 'import sys; sys.exit(sys.stdin.read() == "pear")'],
176 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000177 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000178 p.stdin.close()
179 p.wait()
180 self.assertEqual(p.returncode, 1)
181
182 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000183 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000184 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000185 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000186 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000187 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000188 os.lseek(d, 0, 0)
189 p = subprocess.Popen([sys.executable, "-c",
190 'import sys; sys.exit(sys.stdin.read() == "pear")'],
191 stdin=d)
192 p.wait()
193 self.assertEqual(p.returncode, 1)
194
195 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000196 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000197 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000198 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000199 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000200 tf.seek(0)
201 p = subprocess.Popen([sys.executable, "-c",
202 'import sys; sys.exit(sys.stdin.read() == "pear")'],
203 stdin=tf)
204 p.wait()
205 self.assertEqual(p.returncode, 1)
206
207 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000208 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000209 p = subprocess.Popen([sys.executable, "-c",
210 'import sys; sys.stdout.write("orange")'],
211 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000212 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000213 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000214
215 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000216 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000217 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000218 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000219 d = tf.fileno()
220 p = subprocess.Popen([sys.executable, "-c",
221 'import sys; sys.stdout.write("orange")'],
222 stdout=d)
223 p.wait()
224 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000225 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000226
227 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000228 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000229 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000230 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000231 p = subprocess.Popen([sys.executable, "-c",
232 'import sys; sys.stdout.write("orange")'],
233 stdout=tf)
234 p.wait()
235 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000236 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000237
238 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000239 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000240 p = subprocess.Popen([sys.executable, "-c",
241 'import sys; sys.stderr.write("strawberry")'],
242 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000243 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000244 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245
246 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000247 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000248 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000249 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000250 d = tf.fileno()
251 p = subprocess.Popen([sys.executable, "-c",
252 'import sys; sys.stderr.write("strawberry")'],
253 stderr=d)
254 p.wait()
255 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000256 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000257
258 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000259 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000260 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000261 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262 p = subprocess.Popen([sys.executable, "-c",
263 'import sys; sys.stderr.write("strawberry")'],
264 stderr=tf)
265 p.wait()
266 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000267 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268
269 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000270 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000272 'import sys;'
273 'sys.stdout.write("apple");'
274 'sys.stdout.flush();'
275 'sys.stderr.write("orange")'],
276 stdout=subprocess.PIPE,
277 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000278 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000279 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000280
281 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000282 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000283 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000284 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000286 'import sys;'
287 'sys.stdout.write("apple");'
288 'sys.stdout.flush();'
289 'sys.stderr.write("orange")'],
290 stdout=tf,
291 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000292 p.wait()
293 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000294 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000295
Thomas Wouters89f507f2006-12-13 04:49:30 +0000296 def test_stdout_filedes_of_stdout(self):
297 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000298 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000299 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000300 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000301
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000302 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000303 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000304 # We cannot use os.path.realpath to canonicalize the path,
305 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
306 cwd = os.getcwd()
307 os.chdir(tmpdir)
308 tmpdir = os.getcwd()
309 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000310 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000311 'import sys,os;'
312 'sys.stdout.write(os.getcwd())'],
313 stdout=subprocess.PIPE,
314 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000315 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000316 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000317 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
318 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000319
320 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000321 newenv = os.environ.copy()
322 newenv["FRUIT"] = "orange"
323 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000324 'import sys,os;'
325 'sys.stdout.write(os.getenv("FRUIT"))'],
326 stdout=subprocess.PIPE,
327 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000328 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000329 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000330
Peter Astrandcbac93c2005-03-03 20:24:28 +0000331 def test_communicate_stdin(self):
332 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000333 'import sys;'
334 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000335 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000336 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000337 self.assertEqual(p.returncode, 1)
338
339 def test_communicate_stdout(self):
340 p = subprocess.Popen([sys.executable, "-c",
341 'import sys; sys.stdout.write("pineapple")'],
342 stdout=subprocess.PIPE)
343 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000344 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000345 self.assertEqual(stderr, None)
346
347 def test_communicate_stderr(self):
348 p = subprocess.Popen([sys.executable, "-c",
349 'import sys; sys.stderr.write("pineapple")'],
350 stderr=subprocess.PIPE)
351 (stdout, stderr) = p.communicate()
352 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000353 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000354
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000355 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000356 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000357 'import sys,os;'
358 'sys.stderr.write("pineapple");'
359 'sys.stdout.write(sys.stdin.read())'],
360 stdin=subprocess.PIPE,
361 stdout=subprocess.PIPE,
362 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000363 self.addCleanup(p.stdout.close)
364 self.addCleanup(p.stderr.close)
365 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000366 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000367 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000368 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000369
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000370 # Test for the fd leak reported in http://bugs.python.org/issue2791.
371 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000372 for stdin_pipe in (False, True):
373 for stdout_pipe in (False, True):
374 for stderr_pipe in (False, True):
375 options = {}
376 if stdin_pipe:
377 options['stdin'] = subprocess.PIPE
378 if stdout_pipe:
379 options['stdout'] = subprocess.PIPE
380 if stderr_pipe:
381 options['stderr'] = subprocess.PIPE
382 if not options:
383 continue
384 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
385 p.communicate()
386 if p.stdin is not None:
387 self.assertTrue(p.stdin.closed)
388 if p.stdout is not None:
389 self.assertTrue(p.stdout.closed)
390 if p.stderr is not None:
391 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000392
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000393 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000394 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000395 p = subprocess.Popen([sys.executable, "-c",
396 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000397 (stdout, stderr) = p.communicate()
398 self.assertEqual(stdout, None)
399 self.assertEqual(stderr, None)
400
401 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000402 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000403 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000404 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000405 x, y = os.pipe()
406 if mswindows:
407 pipe_buf = 512
408 else:
409 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
410 os.close(x)
411 os.close(y)
412 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000413 'import sys,os;'
414 'sys.stdout.write(sys.stdin.read(47));'
415 'sys.stderr.write("xyz"*%d);'
416 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
417 stdin=subprocess.PIPE,
418 stdout=subprocess.PIPE,
419 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000420 self.addCleanup(p.stdout.close)
421 self.addCleanup(p.stderr.close)
422 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000423 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424 (stdout, stderr) = p.communicate(string_to_write)
425 self.assertEqual(stdout, string_to_write)
426
427 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000428 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000429 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000430 'import sys,os;'
431 'sys.stdout.write(sys.stdin.read())'],
432 stdin=subprocess.PIPE,
433 stdout=subprocess.PIPE,
434 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000435 self.addCleanup(p.stdout.close)
436 self.addCleanup(p.stderr.close)
437 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000438 p.stdin.write(b"banana")
439 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000440 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000441 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000442
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000443 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000445 'import sys,os;' + SETBINARY +
446 'sys.stdout.write("line1\\n");'
447 'sys.stdout.flush();'
448 'sys.stdout.write("line2\\n");'
449 'sys.stdout.flush();'
450 'sys.stdout.write("line3\\r\\n");'
451 'sys.stdout.flush();'
452 'sys.stdout.write("line4\\r");'
453 'sys.stdout.flush();'
454 'sys.stdout.write("\\nline5");'
455 'sys.stdout.flush();'
456 'sys.stdout.write("\\nline6");'],
457 stdout=subprocess.PIPE,
458 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000459 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000460 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000461 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000462
463 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000464 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000465 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000466 'import sys,os;' + SETBINARY +
467 'sys.stdout.write("line1\\n");'
468 'sys.stdout.flush();'
469 'sys.stdout.write("line2\\n");'
470 'sys.stdout.flush();'
471 'sys.stdout.write("line3\\r\\n");'
472 'sys.stdout.flush();'
473 'sys.stdout.write("line4\\r");'
474 'sys.stdout.flush();'
475 'sys.stdout.write("\\nline5");'
476 'sys.stdout.flush();'
477 'sys.stdout.write("\\nline6");'],
478 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
479 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000480 self.addCleanup(p.stdout.close)
481 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000483 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484
485 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000486 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000487 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000488 max_handles = 1026 # too much for most UNIX systems
489 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000490 max_handles = 2050 # too much for (at least some) Windows setups
491 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400492 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000493 try:
494 for i in range(max_handles):
495 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400496 tmpfile = os.path.join(tmpdir, support.TESTFN)
497 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000498 except OSError as e:
499 if e.errno != errno.EMFILE:
500 raise
501 break
502 else:
503 self.skipTest("failed to reach the file descriptor limit "
504 "(tried %d)" % max_handles)
505 # Close a couple of them (should be enough for a subprocess)
506 for i in range(10):
507 os.close(handles.pop())
508 # Loop creating some subprocesses. If one of them leaks some fds,
509 # the next loop iteration will fail by reaching the max fd limit.
510 for i in range(15):
511 p = subprocess.Popen([sys.executable, "-c",
512 "import sys;"
513 "sys.stdout.write(sys.stdin.read())"],
514 stdin=subprocess.PIPE,
515 stdout=subprocess.PIPE,
516 stderr=subprocess.PIPE)
517 data = p.communicate(b"lime")[0]
518 self.assertEqual(data, b"lime")
519 finally:
520 for h in handles:
521 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400522 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523
524 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
526 '"a b c" d e')
527 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
528 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000529 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
530 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
532 'a\\\\\\b "de fg" h')
533 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
534 'a\\\\\\"b c d')
535 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
536 '"a\\\\b c" d e')
537 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
538 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000539 self.assertEqual(subprocess.list2cmdline(['ab', '']),
540 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000541
542
543 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000544 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000545 "-c", "import time; time.sleep(1)"])
546 count = 0
547 while p.poll() is None:
548 time.sleep(0.1)
549 count += 1
550 # We expect that the poll loop probably went around about 10 times,
551 # but, based on system scheduling we can't control, it's possible
552 # poll() never returned None. It "should be" very rare that it
553 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000554 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000555 # Subsequent invocations should just return the returncode
556 self.assertEqual(p.poll(), 0)
557
558
559 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000560 p = subprocess.Popen([sys.executable,
561 "-c", "import time; time.sleep(2)"])
562 self.assertEqual(p.wait(), 0)
563 # Subsequent invocations should just return the returncode
564 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000565
Peter Astrand738131d2004-11-30 21:04:45 +0000566
567 def test_invalid_bufsize(self):
568 # an invalid type of the bufsize argument should raise
569 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000570 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000571 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000572
Guido van Rossum46a05a72007-06-07 21:56:45 +0000573 def test_bufsize_is_none(self):
574 # bufsize=None should be the same as bufsize=0.
575 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
576 self.assertEqual(p.wait(), 0)
577 # Again with keyword arg
578 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
579 self.assertEqual(p.wait(), 0)
580
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000581 def test_leaking_fds_on_error(self):
582 # see bug #5179: Popen leaks file descriptors to PIPEs if
583 # the child fails to execute; this will eventually exhaust
584 # the maximum number of open fds. 1024 seems a very common
585 # value for that limit, but Windows has 2048, so we loop
586 # 1024 times (each call leaked two fds).
587 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000588 # Windows raises IOError. Others raise OSError.
589 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000590 subprocess.Popen(['nonexisting_i_hope'],
591 stdout=subprocess.PIPE,
592 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400593 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400594 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000595 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000596
Victor Stinnerb3693582010-05-21 20:13:12 +0000597 def test_issue8780(self):
598 # Ensure that stdout is inherited from the parent
599 # if stdout=PIPE is not used
600 code = ';'.join((
601 'import subprocess, sys',
602 'retcode = subprocess.call('
603 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
604 'assert retcode == 0'))
605 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000606 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000607
Tim Goldenaf5ac392010-08-06 13:03:56 +0000608 def test_handles_closed_on_exception(self):
609 # If CreateProcess exits with an error, ensure the
610 # duplicate output handles are released
611 ifhandle, ifname = mkstemp()
612 ofhandle, ofname = mkstemp()
613 efhandle, efname = mkstemp()
614 try:
615 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
616 stderr=efhandle)
617 except OSError:
618 os.close(ifhandle)
619 os.remove(ifname)
620 os.close(ofhandle)
621 os.remove(ofname)
622 os.close(efhandle)
623 os.remove(efname)
624 self.assertFalse(os.path.exists(ifname))
625 self.assertFalse(os.path.exists(ofname))
626 self.assertFalse(os.path.exists(efname))
627
Tim Peterse718f612004-10-12 21:51:32 +0000628
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000629# context manager
630class _SuppressCoreFiles(object):
631 """Try to prevent core files from being created."""
632 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000633
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000634 def __enter__(self):
635 """Try to save previous ulimit, then set it to (0, 0)."""
636 try:
637 import resource
638 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
639 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
640 except (ImportError, ValueError, resource.error):
641 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000642
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000643 if sys.platform == 'darwin':
644 # Check if the 'Crash Reporter' on OSX was configured
645 # in 'Developer' mode and warn that it will get triggered
646 # when it is.
647 #
648 # This assumes that this context manager is used in tests
649 # that might trigger the next manager.
650 value = subprocess.Popen(['/usr/bin/defaults', 'read',
651 'com.apple.CrashReporter', 'DialogType'],
652 stdout=subprocess.PIPE).communicate()[0]
653 if value.strip() == b'developer':
654 print("this tests triggers the Crash Reporter, "
655 "that is intentional", end='')
656 sys.stdout.flush()
657
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000658 def __exit__(self, *args):
659 """Return core file behavior to default."""
660 if self.old_limit is None:
661 return
662 try:
663 import resource
664 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
665 except (ImportError, ValueError, resource.error):
666 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000667
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000668
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000669@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000670class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000671
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000672 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000673 nonexistent_dir = "/_this/pa.th/does/not/exist"
674 try:
675 os.chdir(nonexistent_dir)
676 except OSError as e:
677 # This avoids hard coding the errno value or the OS perror()
678 # string and instead capture the exception that we want to see
679 # below for comparison.
680 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000681 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000682 else:
683 self.fail("chdir to nonexistant directory %s succeeded." %
684 nonexistent_dir)
685
686 # Error in the child re-raised in the parent.
687 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000688 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000689 cwd=nonexistent_dir)
690 except OSError as e:
691 # Test that the child process chdir failure actually makes
692 # it up to the parent process as the correct exception.
693 self.assertEqual(desired_exception.errno, e.errno)
694 self.assertEqual(desired_exception.strerror, e.strerror)
695 else:
696 self.fail("Expected OSError: %s" % desired_exception)
697
698 def test_restore_signals(self):
699 # Code coverage for both values of restore_signals to make sure it
700 # at least does not blow up.
701 # A test for behavior would be complex. Contributions welcome.
702 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
703 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
704
705 def test_start_new_session(self):
706 # For code coverage of calling setsid(). We don't care if we get an
707 # EPERM error from it depending on the test execution environment, that
708 # still indicates that it was called.
709 try:
710 output = subprocess.check_output(
711 [sys.executable, "-c",
712 "import os; print(os.getpgid(os.getpid()))"],
713 start_new_session=True)
714 except OSError as e:
715 if e.errno != errno.EPERM:
716 raise
717 else:
718 parent_pgid = os.getpgid(os.getpid())
719 child_pgid = int(output)
720 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000721
722 def test_run_abort(self):
723 # returncode handles signal termination
724 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000725 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000726 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000727 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000728 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000729
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000730 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000731 # DISCLAIMER: Setting environment variables is *not* a good use
732 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000733 p = subprocess.Popen([sys.executable, "-c",
734 'import sys,os;'
735 'sys.stdout.write(os.getenv("FRUIT"))'],
736 stdout=subprocess.PIPE,
737 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000738 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000739 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000740
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000741 def test_preexec_exception(self):
742 def raise_it():
743 raise ValueError("What if two swallows carried a coconut?")
744 try:
745 p = subprocess.Popen([sys.executable, "-c", ""],
746 preexec_fn=raise_it)
747 except RuntimeError as e:
748 self.assertTrue(
749 subprocess._posixsubprocess,
750 "Expected a ValueError from the preexec_fn")
751 except ValueError as e:
752 self.assertIn("coconut", e.args[0])
753 else:
754 self.fail("Exception raised by preexec_fn did not make it "
755 "to the parent process.")
756
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000757 @unittest.skipUnless(gc, "Requires a gc module.")
758 def test_preexec_gc_module_failure(self):
759 # This tests the code that disables garbage collection if the child
760 # process will execute any Python.
761 def raise_runtime_error():
762 raise RuntimeError("this shouldn't escape")
763 enabled = gc.isenabled()
764 orig_gc_disable = gc.disable
765 orig_gc_isenabled = gc.isenabled
766 try:
767 gc.disable()
768 self.assertFalse(gc.isenabled())
769 subprocess.call([sys.executable, '-c', ''],
770 preexec_fn=lambda: None)
771 self.assertFalse(gc.isenabled(),
772 "Popen enabled gc when it shouldn't.")
773
774 gc.enable()
775 self.assertTrue(gc.isenabled())
776 subprocess.call([sys.executable, '-c', ''],
777 preexec_fn=lambda: None)
778 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
779
780 gc.disable = raise_runtime_error
781 self.assertRaises(RuntimeError, subprocess.Popen,
782 [sys.executable, '-c', ''],
783 preexec_fn=lambda: None)
784
785 del gc.isenabled # force an AttributeError
786 self.assertRaises(AttributeError, subprocess.Popen,
787 [sys.executable, '-c', ''],
788 preexec_fn=lambda: None)
789 finally:
790 gc.disable = orig_gc_disable
791 gc.isenabled = orig_gc_isenabled
792 if not enabled:
793 gc.disable()
794
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000795 def test_args_string(self):
796 # args is a string
797 fd, fname = mkstemp()
798 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000799 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000800 fobj.write("#!/bin/sh\n")
801 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
802 sys.executable)
803 os.chmod(fname, 0o700)
804 p = subprocess.Popen(fname)
805 p.wait()
806 os.remove(fname)
807 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000808
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000809 def test_invalid_args(self):
810 # invalid arguments should raise ValueError
811 self.assertRaises(ValueError, subprocess.call,
812 [sys.executable, "-c",
813 "import sys; sys.exit(47)"],
814 startupinfo=47)
815 self.assertRaises(ValueError, subprocess.call,
816 [sys.executable, "-c",
817 "import sys; sys.exit(47)"],
818 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000819
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000820 def test_shell_sequence(self):
821 # Run command through the shell (sequence)
822 newenv = os.environ.copy()
823 newenv["FRUIT"] = "apple"
824 p = subprocess.Popen(["echo $FRUIT"], shell=1,
825 stdout=subprocess.PIPE,
826 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000827 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000828 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000829
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000830 def test_shell_string(self):
831 # Run command through the shell (string)
832 newenv = os.environ.copy()
833 newenv["FRUIT"] = "apple"
834 p = subprocess.Popen("echo $FRUIT", shell=1,
835 stdout=subprocess.PIPE,
836 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000837 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000838 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000839
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000840 def test_call_string(self):
841 # call() function with string argument on UNIX
842 fd, fname = mkstemp()
843 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000844 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000845 fobj.write("#!/bin/sh\n")
846 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
847 sys.executable)
848 os.chmod(fname, 0o700)
849 rc = subprocess.call(fname)
850 os.remove(fname)
851 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000852
Stefan Krah9542cc62010-07-19 14:20:53 +0000853 def test_specific_shell(self):
854 # Issue #9265: Incorrect name passed as arg[0].
855 shells = []
856 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
857 for name in ['bash', 'ksh']:
858 sh = os.path.join(prefix, name)
859 if os.path.isfile(sh):
860 shells.append(sh)
861 if not shells: # Will probably work for any shell but csh.
862 self.skipTest("bash or ksh required for this test")
863 sh = '/bin/sh'
864 if os.path.isfile(sh) and not os.path.islink(sh):
865 # Test will fail if /bin/sh is a symlink to csh.
866 shells.append(sh)
867 for sh in shells:
868 p = subprocess.Popen("echo $0", executable=sh, shell=True,
869 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000870 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000871 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
872
Florent Xicluna4886d242010-03-08 13:27:26 +0000873 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000874 # Do not inherit file handles from the parent.
875 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000876 p = subprocess.Popen([sys.executable, "-c", """if 1:
877 import sys, time
878 sys.stdout.write('x\\n')
879 sys.stdout.flush()
880 time.sleep(30)
881 """],
882 close_fds=True,
883 stdin=subprocess.PIPE,
884 stdout=subprocess.PIPE,
885 stderr=subprocess.PIPE)
886 # Wait for the interpreter to be completely initialized before
887 # sending any signal.
888 p.stdout.read(1)
889 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000890 return p
891
892 def test_send_signal(self):
893 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000894 _, stderr = p.communicate()
895 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000896 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000897
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000898 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000899 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000900 _, stderr = p.communicate()
901 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000902 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000903
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000904 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000905 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000906 _, stderr = p.communicate()
907 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000908 self.assertEqual(p.wait(), -signal.SIGTERM)
909
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000910 def check_close_std_fds(self, fds):
911 # Issue #9905: test that subprocess pipes still work properly with
912 # some standard fds closed
913 stdin = 0
914 newfds = []
915 for a in fds:
916 b = os.dup(a)
917 newfds.append(b)
918 if a == 0:
919 stdin = b
920 try:
921 for fd in fds:
922 os.close(fd)
923 out, err = subprocess.Popen([sys.executable, "-c",
924 'import sys;'
925 'sys.stdout.write("apple");'
926 'sys.stdout.flush();'
927 'sys.stderr.write("orange")'],
928 stdin=stdin,
929 stdout=subprocess.PIPE,
930 stderr=subprocess.PIPE).communicate()
931 err = support.strip_python_stderr(err)
932 self.assertEqual((out, err), (b'apple', b'orange'))
933 finally:
934 for b, a in zip(newfds, fds):
935 os.dup2(b, a)
936 for b in newfds:
937 os.close(b)
938
939 def test_close_fd_0(self):
940 self.check_close_std_fds([0])
941
942 def test_close_fd_1(self):
943 self.check_close_std_fds([1])
944
945 def test_close_fd_2(self):
946 self.check_close_std_fds([2])
947
948 def test_close_fds_0_1(self):
949 self.check_close_std_fds([0, 1])
950
951 def test_close_fds_0_2(self):
952 self.check_close_std_fds([0, 2])
953
954 def test_close_fds_1_2(self):
955 self.check_close_std_fds([1, 2])
956
957 def test_close_fds_0_1_2(self):
958 # Issue #10806: test that subprocess pipes still work properly with
959 # all standard fds closed.
960 self.check_close_std_fds([0, 1, 2])
961
Antoine Pitrou95aaeee2011-01-03 21:15:48 +0000962 def test_remapping_std_fds(self):
963 # open up some temporary files
964 temps = [mkstemp() for i in range(3)]
965 try:
966 temp_fds = [fd for fd, fname in temps]
967
968 # unlink the files -- we won't need to reopen them
969 for fd, fname in temps:
970 os.unlink(fname)
971
972 # write some data to what will become stdin, and rewind
973 os.write(temp_fds[1], b"STDIN")
974 os.lseek(temp_fds[1], 0, 0)
975
976 # move the standard file descriptors out of the way
977 saved_fds = [os.dup(fd) for fd in range(3)]
978 try:
979 # duplicate the file objects over the standard fd's
980 for fd, temp_fd in enumerate(temp_fds):
981 os.dup2(temp_fd, fd)
982
983 # now use those files in the "wrong" order, so that subprocess
984 # has to rearrange them in the child
985 p = subprocess.Popen([sys.executable, "-c",
986 'import sys; got = sys.stdin.read();'
987 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
988 stdin=temp_fds[1],
989 stdout=temp_fds[2],
990 stderr=temp_fds[0])
991 p.wait()
992 finally:
993 # restore the original fd's underneath sys.stdin, etc.
994 for std, saved in enumerate(saved_fds):
995 os.dup2(saved, std)
996 os.close(saved)
997
998 for fd in temp_fds:
999 os.lseek(fd, 0, 0)
1000
1001 out = os.read(temp_fds[2], 1024)
1002 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1003 self.assertEqual(out, b"got STDIN")
1004 self.assertEqual(err, b"err")
1005
1006 finally:
1007 for fd in temp_fds:
1008 os.close(fd)
1009
Victor Stinner13bb71c2010-04-23 21:41:56 +00001010 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001011 def prepare():
1012 raise ValueError("surrogate:\uDCff")
1013
1014 try:
1015 subprocess.call(
1016 [sys.executable, "-c", "pass"],
1017 preexec_fn=prepare)
1018 except ValueError as err:
1019 # Pure Python implementations keeps the message
1020 self.assertIsNone(subprocess._posixsubprocess)
1021 self.assertEqual(str(err), "surrogate:\uDCff")
1022 except RuntimeError as err:
1023 # _posixsubprocess uses a default message
1024 self.assertIsNotNone(subprocess._posixsubprocess)
1025 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1026 else:
1027 self.fail("Expected ValueError or RuntimeError")
1028
Victor Stinner13bb71c2010-04-23 21:41:56 +00001029 def test_undecodable_env(self):
1030 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001031 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001032 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001033 env = os.environ.copy()
1034 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001035 # Use C locale to get ascii for the locale encoding to force
1036 # surrogate-escaping of \xFF in the child process; otherwise it can
1037 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001038 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001039 stdout = subprocess.check_output(
1040 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001041 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001042 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001043 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001044
1045 # test bytes
1046 key = key.encode("ascii", "surrogateescape")
1047 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001048 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001049 env = os.environ.copy()
1050 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001051 stdout = subprocess.check_output(
1052 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001053 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001054 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001055 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001056
Victor Stinnerb745a742010-05-18 17:17:23 +00001057 def test_bytes_program(self):
1058 abs_program = os.fsencode(sys.executable)
1059 path, program = os.path.split(sys.executable)
1060 program = os.fsencode(program)
1061
1062 # absolute bytes path
1063 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001064 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001065
1066 # bytes program, unicode PATH
1067 env = os.environ.copy()
1068 env["PATH"] = path
1069 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001070 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001071
1072 # bytes program, bytes PATH
1073 envb = os.environb.copy()
1074 envb[b"PATH"] = os.fsencode(path)
1075 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001076 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001077
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001078 def test_pipe_cloexec(self):
1079 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1080 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1081
1082 p1 = subprocess.Popen([sys.executable, sleeper],
1083 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1084 stderr=subprocess.PIPE, close_fds=False)
1085
1086 self.addCleanup(p1.communicate, b'')
1087
1088 p2 = subprocess.Popen([sys.executable, fd_status],
1089 stdout=subprocess.PIPE, close_fds=False)
1090
1091 output, error = p2.communicate()
1092 result_fds = set(map(int, output.split(b',')))
1093 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1094 p1.stderr.fileno()])
1095
1096 self.assertFalse(result_fds & unwanted_fds,
1097 "Expected no fds from %r to be open in child, "
1098 "found %r" %
1099 (unwanted_fds, result_fds & unwanted_fds))
1100
1101 def test_pipe_cloexec_real_tools(self):
1102 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1103 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1104
1105 subdata = b'zxcvbn'
1106 data = subdata * 4 + b'\n'
1107
1108 p1 = subprocess.Popen([sys.executable, qcat],
1109 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1110 close_fds=False)
1111
1112 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1113 stdin=p1.stdout, stdout=subprocess.PIPE,
1114 close_fds=False)
1115
1116 self.addCleanup(p1.wait)
1117 self.addCleanup(p2.wait)
1118 self.addCleanup(p1.terminate)
1119 self.addCleanup(p2.terminate)
1120
1121 p1.stdin.write(data)
1122 p1.stdin.close()
1123
1124 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1125
1126 self.assertTrue(readfiles, "The child hung")
1127 self.assertEqual(p2.stdout.read(), data)
1128
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001129 p1.stdout.close()
1130 p2.stdout.close()
1131
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001132 def test_close_fds(self):
1133 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1134
1135 fds = os.pipe()
1136 self.addCleanup(os.close, fds[0])
1137 self.addCleanup(os.close, fds[1])
1138
1139 open_fds = set(fds)
1140
1141 p = subprocess.Popen([sys.executable, fd_status],
1142 stdout=subprocess.PIPE, close_fds=False)
1143 output, ignored = p.communicate()
1144 remaining_fds = set(map(int, output.split(b',')))
1145
1146 self.assertEqual(remaining_fds & open_fds, open_fds,
1147 "Some fds were closed")
1148
1149 p = subprocess.Popen([sys.executable, fd_status],
1150 stdout=subprocess.PIPE, close_fds=True)
1151 output, ignored = p.communicate()
1152 remaining_fds = set(map(int, output.split(b',')))
1153
1154 self.assertFalse(remaining_fds & open_fds,
1155 "Some fds were left open")
1156 self.assertIn(1, remaining_fds, "Subprocess failed")
1157
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001158 def test_pass_fds(self):
1159 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1160
1161 open_fds = set()
1162
1163 for x in range(5):
1164 fds = os.pipe()
1165 self.addCleanup(os.close, fds[0])
1166 self.addCleanup(os.close, fds[1])
1167 open_fds.update(fds)
1168
1169 for fd in open_fds:
1170 p = subprocess.Popen([sys.executable, fd_status],
1171 stdout=subprocess.PIPE, close_fds=True,
1172 pass_fds=(fd, ))
1173 output, ignored = p.communicate()
1174
1175 remaining_fds = set(map(int, output.split(b',')))
1176 to_be_closed = open_fds - {fd}
1177
1178 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1179 self.assertFalse(remaining_fds & to_be_closed,
1180 "fd to be closed passed")
1181
1182 # pass_fds overrides close_fds with a warning.
1183 with self.assertWarns(RuntimeWarning) as context:
1184 self.assertFalse(subprocess.call(
1185 [sys.executable, "-c", "import sys; sys.exit(0)"],
1186 close_fds=False, pass_fds=(fd, )))
1187 self.assertIn('overriding close_fds', str(context.warning))
1188
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001189 def test_wait_when_sigchild_ignored(self):
1190 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1191 sigchild_ignore = support.findfile("sigchild_ignore.py",
1192 subdir="subprocessdata")
1193 p = subprocess.Popen([sys.executable, sigchild_ignore],
1194 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1195 stdout, stderr = p.communicate()
1196 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001197 " non-zero with this error:\n%s" %
1198 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001199
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001200
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001201@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001202class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001203
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001204 def test_startupinfo(self):
1205 # startupinfo argument
1206 # We uses hardcoded constants, because we do not want to
1207 # depend on win32all.
1208 STARTF_USESHOWWINDOW = 1
1209 SW_MAXIMIZE = 3
1210 startupinfo = subprocess.STARTUPINFO()
1211 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1212 startupinfo.wShowWindow = SW_MAXIMIZE
1213 # Since Python is a console process, it won't be affected
1214 # by wShowWindow, but the argument should be silently
1215 # ignored
1216 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001217 startupinfo=startupinfo)
1218
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001219 def test_creationflags(self):
1220 # creationflags argument
1221 CREATE_NEW_CONSOLE = 16
1222 sys.stderr.write(" a DOS box should flash briefly ...\n")
1223 subprocess.call(sys.executable +
1224 ' -c "import time; time.sleep(0.25)"',
1225 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001226
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001227 def test_invalid_args(self):
1228 # invalid arguments should raise ValueError
1229 self.assertRaises(ValueError, subprocess.call,
1230 [sys.executable, "-c",
1231 "import sys; sys.exit(47)"],
1232 preexec_fn=lambda: 1)
1233 self.assertRaises(ValueError, subprocess.call,
1234 [sys.executable, "-c",
1235 "import sys; sys.exit(47)"],
1236 stdout=subprocess.PIPE,
1237 close_fds=True)
1238
1239 def test_close_fds(self):
1240 # close file descriptors
1241 rc = subprocess.call([sys.executable, "-c",
1242 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001243 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001244 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001245
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001246 def test_shell_sequence(self):
1247 # Run command through the shell (sequence)
1248 newenv = os.environ.copy()
1249 newenv["FRUIT"] = "physalis"
1250 p = subprocess.Popen(["set"], shell=1,
1251 stdout=subprocess.PIPE,
1252 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001253 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001254 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001255
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001256 def test_shell_string(self):
1257 # Run command through the shell (string)
1258 newenv = os.environ.copy()
1259 newenv["FRUIT"] = "physalis"
1260 p = subprocess.Popen("set", shell=1,
1261 stdout=subprocess.PIPE,
1262 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001263 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001264 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001265
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001266 def test_call_string(self):
1267 # call() function with string argument on Windows
1268 rc = subprocess.call(sys.executable +
1269 ' -c "import sys; sys.exit(47)"')
1270 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001271
Florent Xicluna4886d242010-03-08 13:27:26 +00001272 def _kill_process(self, method, *args):
1273 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001274 p = subprocess.Popen([sys.executable, "-c", """if 1:
1275 import sys, time
1276 sys.stdout.write('x\\n')
1277 sys.stdout.flush()
1278 time.sleep(30)
1279 """],
1280 stdin=subprocess.PIPE,
1281 stdout=subprocess.PIPE,
1282 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001283 self.addCleanup(p.stdout.close)
1284 self.addCleanup(p.stderr.close)
1285 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001286 # Wait for the interpreter to be completely initialized before
1287 # sending any signal.
1288 p.stdout.read(1)
1289 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001290 _, stderr = p.communicate()
1291 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001292 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001293 self.assertNotEqual(returncode, 0)
1294
1295 def test_send_signal(self):
1296 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001297
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001298 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001299 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001300
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001301 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001302 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001303
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001304
Brett Cannona23810f2008-05-26 19:04:21 +00001305# The module says:
1306# "NB This only works (and is only relevant) for UNIX."
1307#
1308# Actually, getoutput should work on any platform with an os.popen, but
1309# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001310@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001311class CommandTests(unittest.TestCase):
1312 def test_getoutput(self):
1313 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1314 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1315 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001316
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001317 # we use mkdtemp in the next line to create an empty directory
1318 # under our exclusive control; from that, we can invent a pathname
1319 # that we _know_ won't exist. This is guaranteed to fail.
1320 dir = None
1321 try:
1322 dir = tempfile.mkdtemp()
1323 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001324
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001325 status, output = subprocess.getstatusoutput('cat ' + name)
1326 self.assertNotEqual(status, 0)
1327 finally:
1328 if dir is not None:
1329 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001330
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001331
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001332@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1333 "poll system call not supported")
1334class ProcessTestCaseNoPoll(ProcessTestCase):
1335 def setUp(self):
1336 subprocess._has_poll = False
1337 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001338
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001339 def tearDown(self):
1340 subprocess._has_poll = True
1341 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001342
1343
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001344@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1345 "_posixsubprocess extension module not found.")
1346class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
1347 def setUp(self):
1348 subprocess._posixsubprocess = None
1349 ProcessTestCase.setUp(self)
1350 POSIXProcessTestCase.setUp(self)
1351
1352 def tearDown(self):
1353 subprocess._posixsubprocess = sys.modules['_posixsubprocess']
1354 POSIXProcessTestCase.tearDown(self)
1355 ProcessTestCase.tearDown(self)
1356
1357
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001358class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001359 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001360 def test_eintr_retry_call(self):
1361 record_calls = []
1362 def fake_os_func(*args):
1363 record_calls.append(args)
1364 if len(record_calls) == 2:
1365 raise OSError(errno.EINTR, "fake interrupted system call")
1366 return tuple(reversed(args))
1367
1368 self.assertEqual((999, 256),
1369 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1370 self.assertEqual([(256, 999)], record_calls)
1371 # This time there will be an EINTR so it will loop once.
1372 self.assertEqual((666,),
1373 subprocess._eintr_retry_call(fake_os_func, 666))
1374 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1375
1376
Tim Golden126c2962010-08-11 14:20:40 +00001377@unittest.skipUnless(mswindows, "Windows-specific tests")
1378class CommandsWithSpaces (BaseTestCase):
1379
1380 def setUp(self):
1381 super().setUp()
1382 f, fname = mkstemp(".py", "te st")
1383 self.fname = fname.lower ()
1384 os.write(f, b"import sys;"
1385 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1386 )
1387 os.close(f)
1388
1389 def tearDown(self):
1390 os.remove(self.fname)
1391 super().tearDown()
1392
1393 def with_spaces(self, *args, **kwargs):
1394 kwargs['stdout'] = subprocess.PIPE
1395 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001396 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001397 self.assertEqual(
1398 p.stdout.read ().decode("mbcs"),
1399 "2 [%r, 'ab cd']" % self.fname
1400 )
1401
1402 def test_shell_string_with_spaces(self):
1403 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001404 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1405 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001406
1407 def test_shell_sequence_with_spaces(self):
1408 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001409 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001410
1411 def test_noshell_string_with_spaces(self):
1412 # call() function with string argument with spaces on Windows
1413 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1414 "ab cd"))
1415
1416 def test_noshell_sequence_with_spaces(self):
1417 # call() function with sequence argument with spaces on Windows
1418 self.with_spaces([sys.executable, self.fname, "ab cd"])
1419
Brian Curtin79cdb662010-12-03 02:46:02 +00001420
1421class ContextManagerTests(ProcessTestCase):
1422
1423 def test_pipe(self):
1424 with subprocess.Popen([sys.executable, "-c",
1425 "import sys;"
1426 "sys.stdout.write('stdout');"
1427 "sys.stderr.write('stderr');"],
1428 stdout=subprocess.PIPE,
1429 stderr=subprocess.PIPE) as proc:
1430 self.assertEqual(proc.stdout.read(), b"stdout")
1431 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1432
1433 self.assertTrue(proc.stdout.closed)
1434 self.assertTrue(proc.stderr.closed)
1435
1436 def test_returncode(self):
1437 with subprocess.Popen([sys.executable, "-c",
1438 "import sys; sys.exit(100)"]) as proc:
1439 proc.wait()
1440 self.assertEqual(proc.returncode, 100)
1441
1442 def test_communicate_stdin(self):
1443 with subprocess.Popen([sys.executable, "-c",
1444 "import sys;"
1445 "sys.exit(sys.stdin.read() == 'context')"],
1446 stdin=subprocess.PIPE) as proc:
1447 proc.communicate(b"context")
1448 self.assertEqual(proc.returncode, 1)
1449
1450 def test_invalid_args(self):
1451 with self.assertRaises(EnvironmentError) as c:
1452 with subprocess.Popen(['nonexisting_i_hope'],
1453 stdout=subprocess.PIPE,
1454 stderr=subprocess.PIPE) as proc:
1455 pass
1456
1457 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1458 raise c.exception
1459
1460
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001461def test_main():
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001462 unit_tests = (ProcessTestCase,
1463 POSIXProcessTestCase,
1464 Win32ProcessTestCase,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001465 ProcessTestCasePOSIXPurePython,
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001466 CommandTests,
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001467 ProcessTestCaseNoPoll,
Tim Golden126c2962010-08-11 14:20:40 +00001468 HelperFunctionTests,
Brian Curtin79cdb662010-12-03 02:46:02 +00001469 CommandsWithSpaces,
Gregory P. Smithf5604852010-12-13 06:45:02 +00001470 ContextManagerTests)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001471
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001472 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +00001473 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001474
1475if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +00001476 test_main()