blob: eaa26d2ba67ac7af5ccc71245bd2ed023294786d [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. Smith32ec9da2010-03-19 16:53:08 +000013try:
14 import gc
15except ImportError:
16 gc = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000017
18mswindows = (sys.platform == "win32")
19
20#
21# Depends on the following external programs: Python
22#
23
24if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000025 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
26 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000027else:
28 SETBINARY = ''
29
Florent Xiclunab1e94e82010-02-27 22:12:37 +000030
31try:
32 mkstemp = tempfile.mkstemp
33except AttributeError:
34 # tempfile.mkstemp is not available
35 def mkstemp():
36 """Replacement for mkstemp, calling mktemp."""
37 fname = tempfile.mktemp()
38 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
39
Tim Peters3761e8d2004-10-13 04:07:12 +000040
Florent Xiclunac049d872010-03-27 22:47:23 +000041class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000042 def setUp(self):
43 # Try to minimize the number of children we have so this test
44 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000045 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000046
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000047 def tearDown(self):
48 for inst in subprocess._active:
49 inst.wait()
50 subprocess._cleanup()
51 self.assertFalse(subprocess._active, "subprocess._active not empty")
52
Florent Xiclunab1e94e82010-02-27 22:12:37 +000053 def assertStderrEqual(self, stderr, expected, msg=None):
54 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
55 # shutdown time. That frustrates tests trying to check stderr produced
56 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000057 actual = support.strip_python_stderr(stderr)
Florent Xiclunab1e94e82010-02-27 22:12:37 +000058 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059
Florent Xiclunac049d872010-03-27 22:47:23 +000060
61class ProcessTestCase(BaseTestCase):
62
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000063 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000064 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000065 rc = subprocess.call([sys.executable, "-c",
66 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000067 self.assertEqual(rc, 47)
68
Peter Astrand454f7672005-01-01 09:36:35 +000069 def test_check_call_zero(self):
70 # check_call() function with zero return code
71 rc = subprocess.check_call([sys.executable, "-c",
72 "import sys; sys.exit(0)"])
73 self.assertEqual(rc, 0)
74
75 def test_check_call_nonzero(self):
76 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000077 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000078 subprocess.check_call([sys.executable, "-c",
79 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000080 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000081
Georg Brandlf9734072008-12-07 15:30:06 +000082 def test_check_output(self):
83 # check_output() function with zero return code
84 output = subprocess.check_output(
85 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000086 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000087
88 def test_check_output_nonzero(self):
89 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000090 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +000091 subprocess.check_output(
92 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000093 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +000094
95 def test_check_output_stderr(self):
96 # check_output() function stderr redirected to stdout
97 output = subprocess.check_output(
98 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
99 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000100 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000101
102 def test_check_output_stdout_arg(self):
103 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000104 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000105 output = subprocess.check_output(
106 [sys.executable, "-c", "print('will not be run')"],
107 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000108 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000109 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000110
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000111 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000112 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000113 newenv = os.environ.copy()
114 newenv["FRUIT"] = "banana"
115 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000116 'import sys, os;'
117 'sys.exit(os.getenv("FRUIT")=="banana")'],
118 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000119 self.assertEqual(rc, 1)
120
121 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000122 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000123 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000124 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000125 self.addCleanup(p.stdout.close)
126 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000127 p.wait()
128 self.assertEqual(p.stdin, None)
129
130 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000131 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000132 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000133 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000134 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000135 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000136 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000137 self.addCleanup(p.stdin.close)
138 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000139 p.wait()
140 self.assertEqual(p.stdout, None)
141
142 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000143 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000144 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000146 self.addCleanup(p.stdout.close)
147 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000148 p.wait()
149 self.assertEqual(p.stderr, None)
150
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000151 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000152 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000153 p = subprocess.Popen(["somethingyoudonthave", "-c",
154 "import sys; sys.exit(47)"],
155 executable=sys.executable, cwd=python_dir)
156 p.wait()
157 self.assertEqual(p.returncode, 47)
158
159 @unittest.skipIf(sysconfig.is_python_build(),
160 "need an installed Python. See #7774")
161 def test_executable_without_cwd(self):
162 # For a normal installation, it should work without 'cwd'
163 # argument. For test runs in the build directory, see #7774.
164 p = subprocess.Popen(["somethingyoudonthave", "-c",
165 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000166 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000167 p.wait()
168 self.assertEqual(p.returncode, 47)
169
170 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000171 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000172 p = subprocess.Popen([sys.executable, "-c",
173 'import sys; sys.exit(sys.stdin.read() == "pear")'],
174 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000175 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000176 p.stdin.close()
177 p.wait()
178 self.assertEqual(p.returncode, 1)
179
180 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000181 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000182 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000183 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000184 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000185 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000186 os.lseek(d, 0, 0)
187 p = subprocess.Popen([sys.executable, "-c",
188 'import sys; sys.exit(sys.stdin.read() == "pear")'],
189 stdin=d)
190 p.wait()
191 self.assertEqual(p.returncode, 1)
192
193 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000194 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000195 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000196 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000197 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000198 tf.seek(0)
199 p = subprocess.Popen([sys.executable, "-c",
200 'import sys; sys.exit(sys.stdin.read() == "pear")'],
201 stdin=tf)
202 p.wait()
203 self.assertEqual(p.returncode, 1)
204
205 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000206 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000207 p = subprocess.Popen([sys.executable, "-c",
208 'import sys; sys.stdout.write("orange")'],
209 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000210 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000211 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000212
213 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000214 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000215 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000216 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000217 d = tf.fileno()
218 p = subprocess.Popen([sys.executable, "-c",
219 'import sys; sys.stdout.write("orange")'],
220 stdout=d)
221 p.wait()
222 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000223 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000224
225 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000226 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000227 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000228 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000229 p = subprocess.Popen([sys.executable, "-c",
230 'import sys; sys.stdout.write("orange")'],
231 stdout=tf)
232 p.wait()
233 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000234 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000235
236 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000237 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238 p = subprocess.Popen([sys.executable, "-c",
239 'import sys; sys.stderr.write("strawberry")'],
240 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000241 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000242 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000243
244 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000245 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000246 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000247 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000248 d = tf.fileno()
249 p = subprocess.Popen([sys.executable, "-c",
250 'import sys; sys.stderr.write("strawberry")'],
251 stderr=d)
252 p.wait()
253 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000254 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000255
256 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000257 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000258 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000259 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000260 p = subprocess.Popen([sys.executable, "-c",
261 'import sys; sys.stderr.write("strawberry")'],
262 stderr=tf)
263 p.wait()
264 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000265 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000266
267 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000268 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000270 'import sys;'
271 'sys.stdout.write("apple");'
272 'sys.stdout.flush();'
273 'sys.stderr.write("orange")'],
274 stdout=subprocess.PIPE,
275 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000276 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000277 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000278
279 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000280 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000282 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000283 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000284 'import sys;'
285 'sys.stdout.write("apple");'
286 'sys.stdout.flush();'
287 'sys.stderr.write("orange")'],
288 stdout=tf,
289 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000290 p.wait()
291 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000292 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293
Thomas Wouters89f507f2006-12-13 04:49:30 +0000294 def test_stdout_filedes_of_stdout(self):
295 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000296 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000297 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000298 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000299
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000300 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000301 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000302 # We cannot use os.path.realpath to canonicalize the path,
303 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
304 cwd = os.getcwd()
305 os.chdir(tmpdir)
306 tmpdir = os.getcwd()
307 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000309 'import sys,os;'
310 'sys.stdout.write(os.getcwd())'],
311 stdout=subprocess.PIPE,
312 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000313 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000314 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000315 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
316 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000317
318 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000319 newenv = os.environ.copy()
320 newenv["FRUIT"] = "orange"
321 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000322 'import sys,os;'
323 'sys.stdout.write(os.getenv("FRUIT"))'],
324 stdout=subprocess.PIPE,
325 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000326 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000327 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000328
Peter Astrandcbac93c2005-03-03 20:24:28 +0000329 def test_communicate_stdin(self):
330 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000331 'import sys;'
332 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000333 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000334 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000335 self.assertEqual(p.returncode, 1)
336
337 def test_communicate_stdout(self):
338 p = subprocess.Popen([sys.executable, "-c",
339 'import sys; sys.stdout.write("pineapple")'],
340 stdout=subprocess.PIPE)
341 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000342 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000343 self.assertEqual(stderr, None)
344
345 def test_communicate_stderr(self):
346 p = subprocess.Popen([sys.executable, "-c",
347 'import sys; sys.stderr.write("pineapple")'],
348 stderr=subprocess.PIPE)
349 (stdout, stderr) = p.communicate()
350 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000351 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000352
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000353 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000355 'import sys,os;'
356 'sys.stderr.write("pineapple");'
357 'sys.stdout.write(sys.stdin.read())'],
358 stdin=subprocess.PIPE,
359 stdout=subprocess.PIPE,
360 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000361 self.addCleanup(p.stdout.close)
362 self.addCleanup(p.stderr.close)
363 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000364 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000365 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000366 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000367
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000368 # This test is Linux specific for simplicity to at least have
369 # some coverage. It is not a platform specific bug.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000370 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
371 "Linux specific")
372 # Test for the fd leak reported in http://bugs.python.org/issue2791.
373 def test_communicate_pipe_fd_leak(self):
374 fd_directory = '/proc/%d/fd' % os.getpid()
375 num_fds_before_popen = len(os.listdir(fd_directory))
376 p = subprocess.Popen([sys.executable, "-c", "print()"],
377 stdout=subprocess.PIPE)
378 p.communicate()
379 num_fds_after_communicate = len(os.listdir(fd_directory))
380 del p
381 num_fds_after_destruction = len(os.listdir(fd_directory))
382 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
383 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000384
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000385 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000386 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000387 p = subprocess.Popen([sys.executable, "-c",
388 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000389 (stdout, stderr) = p.communicate()
390 self.assertEqual(stdout, None)
391 self.assertEqual(stderr, None)
392
393 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000394 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000395 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000396 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000397 x, y = os.pipe()
398 if mswindows:
399 pipe_buf = 512
400 else:
401 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
402 os.close(x)
403 os.close(y)
404 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000405 'import sys,os;'
406 'sys.stdout.write(sys.stdin.read(47));'
407 'sys.stderr.write("xyz"*%d);'
408 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
409 stdin=subprocess.PIPE,
410 stdout=subprocess.PIPE,
411 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000412 self.addCleanup(p.stdout.close)
413 self.addCleanup(p.stderr.close)
414 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000415 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416 (stdout, stderr) = p.communicate(string_to_write)
417 self.assertEqual(stdout, string_to_write)
418
419 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000420 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000421 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000422 'import sys,os;'
423 'sys.stdout.write(sys.stdin.read())'],
424 stdin=subprocess.PIPE,
425 stdout=subprocess.PIPE,
426 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000427 self.addCleanup(p.stdout.close)
428 self.addCleanup(p.stderr.close)
429 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000430 p.stdin.write(b"banana")
431 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000432 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000433 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000434
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000436 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000437 'import sys,os;' + SETBINARY +
438 'sys.stdout.write("line1\\n");'
439 'sys.stdout.flush();'
440 'sys.stdout.write("line2\\n");'
441 'sys.stdout.flush();'
442 'sys.stdout.write("line3\\r\\n");'
443 'sys.stdout.flush();'
444 'sys.stdout.write("line4\\r");'
445 'sys.stdout.flush();'
446 'sys.stdout.write("\\nline5");'
447 'sys.stdout.flush();'
448 'sys.stdout.write("\\nline6");'],
449 stdout=subprocess.PIPE,
450 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000451 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000453 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454
455 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000456 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000457 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000458 'import sys,os;' + SETBINARY +
459 'sys.stdout.write("line1\\n");'
460 'sys.stdout.flush();'
461 'sys.stdout.write("line2\\n");'
462 'sys.stdout.flush();'
463 'sys.stdout.write("line3\\r\\n");'
464 'sys.stdout.flush();'
465 'sys.stdout.write("line4\\r");'
466 'sys.stdout.flush();'
467 'sys.stdout.write("\\nline5");'
468 'sys.stdout.flush();'
469 'sys.stdout.write("\\nline6");'],
470 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
471 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000472 self.addCleanup(p.stdout.close)
473 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000475 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476
477 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000478 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000479 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000480 max_handles = 1026 # too much for most UNIX systems
481 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000482 max_handles = 2050 # too much for (at least some) Windows setups
483 handles = []
484 try:
485 for i in range(max_handles):
486 try:
487 handles.append(os.open(support.TESTFN,
488 os.O_WRONLY | os.O_CREAT))
489 except OSError as e:
490 if e.errno != errno.EMFILE:
491 raise
492 break
493 else:
494 self.skipTest("failed to reach the file descriptor limit "
495 "(tried %d)" % max_handles)
496 # Close a couple of them (should be enough for a subprocess)
497 for i in range(10):
498 os.close(handles.pop())
499 # Loop creating some subprocesses. If one of them leaks some fds,
500 # the next loop iteration will fail by reaching the max fd limit.
501 for i in range(15):
502 p = subprocess.Popen([sys.executable, "-c",
503 "import sys;"
504 "sys.stdout.write(sys.stdin.read())"],
505 stdin=subprocess.PIPE,
506 stdout=subprocess.PIPE,
507 stderr=subprocess.PIPE)
508 data = p.communicate(b"lime")[0]
509 self.assertEqual(data, b"lime")
510 finally:
511 for h in handles:
512 os.close(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000513
514 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000515 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
516 '"a b c" d e')
517 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
518 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000519 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
520 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000521 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
522 'a\\\\\\b "de fg" h')
523 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
524 'a\\\\\\"b c d')
525 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
526 '"a\\\\b c" d e')
527 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
528 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000529 self.assertEqual(subprocess.list2cmdline(['ab', '']),
530 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531
532
533 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000535 "-c", "import time; time.sleep(1)"])
536 count = 0
537 while p.poll() is None:
538 time.sleep(0.1)
539 count += 1
540 # We expect that the poll loop probably went around about 10 times,
541 # but, based on system scheduling we can't control, it's possible
542 # poll() never returned None. It "should be" very rare that it
543 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000544 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 # Subsequent invocations should just return the returncode
546 self.assertEqual(p.poll(), 0)
547
548
549 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000550 p = subprocess.Popen([sys.executable,
551 "-c", "import time; time.sleep(2)"])
552 self.assertEqual(p.wait(), 0)
553 # Subsequent invocations should just return the returncode
554 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000555
Peter Astrand738131d2004-11-30 21:04:45 +0000556
557 def test_invalid_bufsize(self):
558 # an invalid type of the bufsize argument should raise
559 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000560 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000561 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000562
Guido van Rossum46a05a72007-06-07 21:56:45 +0000563 def test_bufsize_is_none(self):
564 # bufsize=None should be the same as bufsize=0.
565 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
566 self.assertEqual(p.wait(), 0)
567 # Again with keyword arg
568 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
569 self.assertEqual(p.wait(), 0)
570
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000571 def test_leaking_fds_on_error(self):
572 # see bug #5179: Popen leaks file descriptors to PIPEs if
573 # the child fails to execute; this will eventually exhaust
574 # the maximum number of open fds. 1024 seems a very common
575 # value for that limit, but Windows has 2048, so we loop
576 # 1024 times (each call leaked two fds).
577 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000578 # Windows raises IOError. Others raise OSError.
579 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000580 subprocess.Popen(['nonexisting_i_hope'],
581 stdout=subprocess.PIPE,
582 stderr=subprocess.PIPE)
Antoine Pitrou679e0f22010-09-18 17:56:02 +0000583 if c.exception.errno != errno.ENOENT: # ignore "no such file"
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000584 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000585
Victor Stinnerb3693582010-05-21 20:13:12 +0000586 def test_issue8780(self):
587 # Ensure that stdout is inherited from the parent
588 # if stdout=PIPE is not used
589 code = ';'.join((
590 'import subprocess, sys',
591 'retcode = subprocess.call('
592 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
593 'assert retcode == 0'))
594 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000595 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000596
Tim Goldenaf5ac392010-08-06 13:03:56 +0000597 def test_handles_closed_on_exception(self):
598 # If CreateProcess exits with an error, ensure the
599 # duplicate output handles are released
600 ifhandle, ifname = mkstemp()
601 ofhandle, ofname = mkstemp()
602 efhandle, efname = mkstemp()
603 try:
604 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
605 stderr=efhandle)
606 except OSError:
607 os.close(ifhandle)
608 os.remove(ifname)
609 os.close(ofhandle)
610 os.remove(ofname)
611 os.close(efhandle)
612 os.remove(efname)
613 self.assertFalse(os.path.exists(ifname))
614 self.assertFalse(os.path.exists(ofname))
615 self.assertFalse(os.path.exists(efname))
616
Tim Peterse718f612004-10-12 21:51:32 +0000617
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000618# context manager
619class _SuppressCoreFiles(object):
620 """Try to prevent core files from being created."""
621 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000622
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000623 def __enter__(self):
624 """Try to save previous ulimit, then set it to (0, 0)."""
625 try:
626 import resource
627 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
628 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
629 except (ImportError, ValueError, resource.error):
630 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000631
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000632 if sys.platform == 'darwin':
633 # Check if the 'Crash Reporter' on OSX was configured
634 # in 'Developer' mode and warn that it will get triggered
635 # when it is.
636 #
637 # This assumes that this context manager is used in tests
638 # that might trigger the next manager.
639 value = subprocess.Popen(['/usr/bin/defaults', 'read',
640 'com.apple.CrashReporter', 'DialogType'],
641 stdout=subprocess.PIPE).communicate()[0]
642 if value.strip() == b'developer':
643 print("this tests triggers the Crash Reporter, "
644 "that is intentional", end='')
645 sys.stdout.flush()
646
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000647 def __exit__(self, *args):
648 """Return core file behavior to default."""
649 if self.old_limit is None:
650 return
651 try:
652 import resource
653 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
654 except (ImportError, ValueError, resource.error):
655 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000656
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000657
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000658@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000659class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000660
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000661 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000662 nonexistent_dir = "/_this/pa.th/does/not/exist"
663 try:
664 os.chdir(nonexistent_dir)
665 except OSError as e:
666 # This avoids hard coding the errno value or the OS perror()
667 # string and instead capture the exception that we want to see
668 # below for comparison.
669 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000670 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000671 else:
672 self.fail("chdir to nonexistant directory %s succeeded." %
673 nonexistent_dir)
674
675 # Error in the child re-raised in the parent.
676 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000677 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000678 cwd=nonexistent_dir)
679 except OSError as e:
680 # Test that the child process chdir failure actually makes
681 # it up to the parent process as the correct exception.
682 self.assertEqual(desired_exception.errno, e.errno)
683 self.assertEqual(desired_exception.strerror, e.strerror)
684 else:
685 self.fail("Expected OSError: %s" % desired_exception)
686
687 def test_restore_signals(self):
688 # Code coverage for both values of restore_signals to make sure it
689 # at least does not blow up.
690 # A test for behavior would be complex. Contributions welcome.
691 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
692 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
693
694 def test_start_new_session(self):
695 # For code coverage of calling setsid(). We don't care if we get an
696 # EPERM error from it depending on the test execution environment, that
697 # still indicates that it was called.
698 try:
699 output = subprocess.check_output(
700 [sys.executable, "-c",
701 "import os; print(os.getpgid(os.getpid()))"],
702 start_new_session=True)
703 except OSError as e:
704 if e.errno != errno.EPERM:
705 raise
706 else:
707 parent_pgid = os.getpgid(os.getpid())
708 child_pgid = int(output)
709 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000710
711 def test_run_abort(self):
712 # returncode handles signal termination
713 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000714 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000715 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000716 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000717 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000718
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000719 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000720 # DISCLAIMER: Setting environment variables is *not* a good use
721 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000722 p = subprocess.Popen([sys.executable, "-c",
723 'import sys,os;'
724 'sys.stdout.write(os.getenv("FRUIT"))'],
725 stdout=subprocess.PIPE,
726 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000727 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000728 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000729
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000730 def test_preexec_exception(self):
731 def raise_it():
732 raise ValueError("What if two swallows carried a coconut?")
733 try:
734 p = subprocess.Popen([sys.executable, "-c", ""],
735 preexec_fn=raise_it)
736 except RuntimeError as e:
737 self.assertTrue(
738 subprocess._posixsubprocess,
739 "Expected a ValueError from the preexec_fn")
740 except ValueError as e:
741 self.assertIn("coconut", e.args[0])
742 else:
743 self.fail("Exception raised by preexec_fn did not make it "
744 "to the parent process.")
745
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000746 @unittest.skipUnless(gc, "Requires a gc module.")
747 def test_preexec_gc_module_failure(self):
748 # This tests the code that disables garbage collection if the child
749 # process will execute any Python.
750 def raise_runtime_error():
751 raise RuntimeError("this shouldn't escape")
752 enabled = gc.isenabled()
753 orig_gc_disable = gc.disable
754 orig_gc_isenabled = gc.isenabled
755 try:
756 gc.disable()
757 self.assertFalse(gc.isenabled())
758 subprocess.call([sys.executable, '-c', ''],
759 preexec_fn=lambda: None)
760 self.assertFalse(gc.isenabled(),
761 "Popen enabled gc when it shouldn't.")
762
763 gc.enable()
764 self.assertTrue(gc.isenabled())
765 subprocess.call([sys.executable, '-c', ''],
766 preexec_fn=lambda: None)
767 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
768
769 gc.disable = raise_runtime_error
770 self.assertRaises(RuntimeError, subprocess.Popen,
771 [sys.executable, '-c', ''],
772 preexec_fn=lambda: None)
773
774 del gc.isenabled # force an AttributeError
775 self.assertRaises(AttributeError, subprocess.Popen,
776 [sys.executable, '-c', ''],
777 preexec_fn=lambda: None)
778 finally:
779 gc.disable = orig_gc_disable
780 gc.isenabled = orig_gc_isenabled
781 if not enabled:
782 gc.disable()
783
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000784 def test_args_string(self):
785 # args is a string
786 fd, fname = mkstemp()
787 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000788 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000789 fobj.write("#!/bin/sh\n")
790 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
791 sys.executable)
792 os.chmod(fname, 0o700)
793 p = subprocess.Popen(fname)
794 p.wait()
795 os.remove(fname)
796 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000797
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000798 def test_invalid_args(self):
799 # invalid arguments should raise ValueError
800 self.assertRaises(ValueError, subprocess.call,
801 [sys.executable, "-c",
802 "import sys; sys.exit(47)"],
803 startupinfo=47)
804 self.assertRaises(ValueError, subprocess.call,
805 [sys.executable, "-c",
806 "import sys; sys.exit(47)"],
807 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000808
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000809 def test_shell_sequence(self):
810 # Run command through the shell (sequence)
811 newenv = os.environ.copy()
812 newenv["FRUIT"] = "apple"
813 p = subprocess.Popen(["echo $FRUIT"], shell=1,
814 stdout=subprocess.PIPE,
815 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000816 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000817 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000818
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000819 def test_shell_string(self):
820 # Run command through the shell (string)
821 newenv = os.environ.copy()
822 newenv["FRUIT"] = "apple"
823 p = subprocess.Popen("echo $FRUIT", shell=1,
824 stdout=subprocess.PIPE,
825 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000826 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000827 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000828
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000829 def test_call_string(self):
830 # call() function with string argument on UNIX
831 fd, fname = mkstemp()
832 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000833 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000834 fobj.write("#!/bin/sh\n")
835 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
836 sys.executable)
837 os.chmod(fname, 0o700)
838 rc = subprocess.call(fname)
839 os.remove(fname)
840 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000841
Stefan Krah9542cc62010-07-19 14:20:53 +0000842 def test_specific_shell(self):
843 # Issue #9265: Incorrect name passed as arg[0].
844 shells = []
845 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
846 for name in ['bash', 'ksh']:
847 sh = os.path.join(prefix, name)
848 if os.path.isfile(sh):
849 shells.append(sh)
850 if not shells: # Will probably work for any shell but csh.
851 self.skipTest("bash or ksh required for this test")
852 sh = '/bin/sh'
853 if os.path.isfile(sh) and not os.path.islink(sh):
854 # Test will fail if /bin/sh is a symlink to csh.
855 shells.append(sh)
856 for sh in shells:
857 p = subprocess.Popen("echo $0", executable=sh, shell=True,
858 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000859 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000860 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
861
Florent Xicluna4886d242010-03-08 13:27:26 +0000862 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000863 # Do not inherit file handles from the parent.
864 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000865 p = subprocess.Popen([sys.executable, "-c", """if 1:
866 import sys, time
867 sys.stdout.write('x\\n')
868 sys.stdout.flush()
869 time.sleep(30)
870 """],
871 close_fds=True,
872 stdin=subprocess.PIPE,
873 stdout=subprocess.PIPE,
874 stderr=subprocess.PIPE)
875 # Wait for the interpreter to be completely initialized before
876 # sending any signal.
877 p.stdout.read(1)
878 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000879 return p
880
881 def test_send_signal(self):
882 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000883 _, stderr = p.communicate()
884 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000885 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000886
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000887 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000888 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000889 _, stderr = p.communicate()
890 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000891 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000892
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000893 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000894 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000895 _, stderr = p.communicate()
896 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000897 self.assertEqual(p.wait(), -signal.SIGTERM)
898
Victor Stinner13bb71c2010-04-23 21:41:56 +0000899 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +0000900 def prepare():
901 raise ValueError("surrogate:\uDCff")
902
903 try:
904 subprocess.call(
905 [sys.executable, "-c", "pass"],
906 preexec_fn=prepare)
907 except ValueError as err:
908 # Pure Python implementations keeps the message
909 self.assertIsNone(subprocess._posixsubprocess)
910 self.assertEqual(str(err), "surrogate:\uDCff")
911 except RuntimeError as err:
912 # _posixsubprocess uses a default message
913 self.assertIsNotNone(subprocess._posixsubprocess)
914 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
915 else:
916 self.fail("Expected ValueError or RuntimeError")
917
Victor Stinner13bb71c2010-04-23 21:41:56 +0000918 def test_undecodable_env(self):
919 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +0000920 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +0000921 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000922 env = os.environ.copy()
923 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +0000924 # Use C locale to get ascii for the locale encoding to force
925 # surrogate-escaping of \xFF in the child process; otherwise it can
926 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +0000927 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +0000928 stdout = subprocess.check_output(
929 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000930 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +0000931 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000932 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +0000933
934 # test bytes
935 key = key.encode("ascii", "surrogateescape")
936 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +0000937 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000938 env = os.environ.copy()
939 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +0000940 stdout = subprocess.check_output(
941 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000942 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +0000943 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000944 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +0000945
Victor Stinnerb745a742010-05-18 17:17:23 +0000946 def test_bytes_program(self):
947 abs_program = os.fsencode(sys.executable)
948 path, program = os.path.split(sys.executable)
949 program = os.fsencode(program)
950
951 # absolute bytes path
952 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000953 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +0000954
955 # bytes program, unicode PATH
956 env = os.environ.copy()
957 env["PATH"] = path
958 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000959 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +0000960
961 # bytes program, bytes PATH
962 envb = os.environb.copy()
963 envb[b"PATH"] = os.fsencode(path)
964 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000965 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +0000966
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000967
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000968@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000969class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000970
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000971 def test_startupinfo(self):
972 # startupinfo argument
973 # We uses hardcoded constants, because we do not want to
974 # depend on win32all.
975 STARTF_USESHOWWINDOW = 1
976 SW_MAXIMIZE = 3
977 startupinfo = subprocess.STARTUPINFO()
978 startupinfo.dwFlags = STARTF_USESHOWWINDOW
979 startupinfo.wShowWindow = SW_MAXIMIZE
980 # Since Python is a console process, it won't be affected
981 # by wShowWindow, but the argument should be silently
982 # ignored
983 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000984 startupinfo=startupinfo)
985
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000986 def test_creationflags(self):
987 # creationflags argument
988 CREATE_NEW_CONSOLE = 16
989 sys.stderr.write(" a DOS box should flash briefly ...\n")
990 subprocess.call(sys.executable +
991 ' -c "import time; time.sleep(0.25)"',
992 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000993
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000994 def test_invalid_args(self):
995 # invalid arguments should raise ValueError
996 self.assertRaises(ValueError, subprocess.call,
997 [sys.executable, "-c",
998 "import sys; sys.exit(47)"],
999 preexec_fn=lambda: 1)
1000 self.assertRaises(ValueError, subprocess.call,
1001 [sys.executable, "-c",
1002 "import sys; sys.exit(47)"],
1003 stdout=subprocess.PIPE,
1004 close_fds=True)
1005
1006 def test_close_fds(self):
1007 # close file descriptors
1008 rc = subprocess.call([sys.executable, "-c",
1009 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001010 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001011 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001012
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001013 def test_shell_sequence(self):
1014 # Run command through the shell (sequence)
1015 newenv = os.environ.copy()
1016 newenv["FRUIT"] = "physalis"
1017 p = subprocess.Popen(["set"], shell=1,
1018 stdout=subprocess.PIPE,
1019 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001020 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001021 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001022
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001023 def test_shell_string(self):
1024 # Run command through the shell (string)
1025 newenv = os.environ.copy()
1026 newenv["FRUIT"] = "physalis"
1027 p = subprocess.Popen("set", shell=1,
1028 stdout=subprocess.PIPE,
1029 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001030 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001031 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001032
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001033 def test_call_string(self):
1034 # call() function with string argument on Windows
1035 rc = subprocess.call(sys.executable +
1036 ' -c "import sys; sys.exit(47)"')
1037 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001038
Florent Xicluna4886d242010-03-08 13:27:26 +00001039 def _kill_process(self, method, *args):
1040 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001041 p = subprocess.Popen([sys.executable, "-c", """if 1:
1042 import sys, time
1043 sys.stdout.write('x\\n')
1044 sys.stdout.flush()
1045 time.sleep(30)
1046 """],
1047 stdin=subprocess.PIPE,
1048 stdout=subprocess.PIPE,
1049 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001050 self.addCleanup(p.stdout.close)
1051 self.addCleanup(p.stderr.close)
1052 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001053 # Wait for the interpreter to be completely initialized before
1054 # sending any signal.
1055 p.stdout.read(1)
1056 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001057 _, stderr = p.communicate()
1058 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001059 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001060 self.assertNotEqual(returncode, 0)
1061
1062 def test_send_signal(self):
1063 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001064
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001065 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001066 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001067
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001068 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001069 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001070
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001071
Brett Cannona23810f2008-05-26 19:04:21 +00001072# The module says:
1073# "NB This only works (and is only relevant) for UNIX."
1074#
1075# Actually, getoutput should work on any platform with an os.popen, but
1076# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001077@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001078class CommandTests(unittest.TestCase):
1079 def test_getoutput(self):
1080 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1081 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1082 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001083
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001084 # we use mkdtemp in the next line to create an empty directory
1085 # under our exclusive control; from that, we can invent a pathname
1086 # that we _know_ won't exist. This is guaranteed to fail.
1087 dir = None
1088 try:
1089 dir = tempfile.mkdtemp()
1090 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001091
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001092 status, output = subprocess.getstatusoutput('cat ' + name)
1093 self.assertNotEqual(status, 0)
1094 finally:
1095 if dir is not None:
1096 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001097
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001098
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001099@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1100 "poll system call not supported")
1101class ProcessTestCaseNoPoll(ProcessTestCase):
1102 def setUp(self):
1103 subprocess._has_poll = False
1104 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001105
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001106 def tearDown(self):
1107 subprocess._has_poll = True
1108 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001109
1110
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001111@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1112 "_posixsubprocess extension module not found.")
1113class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
1114 def setUp(self):
1115 subprocess._posixsubprocess = None
1116 ProcessTestCase.setUp(self)
1117 POSIXProcessTestCase.setUp(self)
1118
1119 def tearDown(self):
1120 subprocess._posixsubprocess = sys.modules['_posixsubprocess']
1121 POSIXProcessTestCase.tearDown(self)
1122 ProcessTestCase.tearDown(self)
1123
1124
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001125class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001126 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001127 def test_eintr_retry_call(self):
1128 record_calls = []
1129 def fake_os_func(*args):
1130 record_calls.append(args)
1131 if len(record_calls) == 2:
1132 raise OSError(errno.EINTR, "fake interrupted system call")
1133 return tuple(reversed(args))
1134
1135 self.assertEqual((999, 256),
1136 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1137 self.assertEqual([(256, 999)], record_calls)
1138 # This time there will be an EINTR so it will loop once.
1139 self.assertEqual((666,),
1140 subprocess._eintr_retry_call(fake_os_func, 666))
1141 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1142
1143
Tim Golden126c2962010-08-11 14:20:40 +00001144@unittest.skipUnless(mswindows, "Windows-specific tests")
1145class CommandsWithSpaces (BaseTestCase):
1146
1147 def setUp(self):
1148 super().setUp()
1149 f, fname = mkstemp(".py", "te st")
1150 self.fname = fname.lower ()
1151 os.write(f, b"import sys;"
1152 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1153 )
1154 os.close(f)
1155
1156 def tearDown(self):
1157 os.remove(self.fname)
1158 super().tearDown()
1159
1160 def with_spaces(self, *args, **kwargs):
1161 kwargs['stdout'] = subprocess.PIPE
1162 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001163 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001164 self.assertEqual(
1165 p.stdout.read ().decode("mbcs"),
1166 "2 [%r, 'ab cd']" % self.fname
1167 )
1168
1169 def test_shell_string_with_spaces(self):
1170 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001171 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1172 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001173
1174 def test_shell_sequence_with_spaces(self):
1175 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001176 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001177
1178 def test_noshell_string_with_spaces(self):
1179 # call() function with string argument with spaces on Windows
1180 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1181 "ab cd"))
1182
1183 def test_noshell_sequence_with_spaces(self):
1184 # call() function with sequence argument with spaces on Windows
1185 self.with_spaces([sys.executable, self.fname, "ab cd"])
1186
Brian Curtin79cdb662010-12-03 02:46:02 +00001187
1188class ContextManagerTests(ProcessTestCase):
1189
1190 def test_pipe(self):
1191 with subprocess.Popen([sys.executable, "-c",
1192 "import sys;"
1193 "sys.stdout.write('stdout');"
1194 "sys.stderr.write('stderr');"],
1195 stdout=subprocess.PIPE,
1196 stderr=subprocess.PIPE) as proc:
1197 self.assertEqual(proc.stdout.read(), b"stdout")
1198 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1199
1200 self.assertTrue(proc.stdout.closed)
1201 self.assertTrue(proc.stderr.closed)
1202
1203 def test_returncode(self):
1204 with subprocess.Popen([sys.executable, "-c",
1205 "import sys; sys.exit(100)"]) as proc:
1206 proc.wait()
1207 self.assertEqual(proc.returncode, 100)
1208
1209 def test_communicate_stdin(self):
1210 with subprocess.Popen([sys.executable, "-c",
1211 "import sys;"
1212 "sys.exit(sys.stdin.read() == 'context')"],
1213 stdin=subprocess.PIPE) as proc:
1214 proc.communicate(b"context")
1215 self.assertEqual(proc.returncode, 1)
1216
1217 def test_invalid_args(self):
1218 with self.assertRaises(EnvironmentError) as c:
1219 with subprocess.Popen(['nonexisting_i_hope'],
1220 stdout=subprocess.PIPE,
1221 stderr=subprocess.PIPE) as proc:
1222 pass
1223
1224 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1225 raise c.exception
1226
1227
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001228def test_main():
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001229 unit_tests = (ProcessTestCase,
1230 POSIXProcessTestCase,
1231 Win32ProcessTestCase,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001232 ProcessTestCasePOSIXPurePython,
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001233 CommandTests,
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001234 ProcessTestCaseNoPoll,
Tim Golden126c2962010-08-11 14:20:40 +00001235 HelperFunctionTests,
Brian Curtin79cdb662010-12-03 02:46:02 +00001236 CommandsWithSpaces,
Gregory P. Smithf5604852010-12-13 06:45:02 +00001237 ContextManagerTests)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001238
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001239 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +00001240 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001241
1242if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +00001243 test_main()