blob: 5a325ce130954cd30f126cd5845f5aaf58ee0e3d [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
7import tempfile
8import time
Tim Peters3761e8d2004-10-13 04:07:12 +00009import re
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000010
11mswindows = (sys.platform == "win32")
12
13#
14# Depends on the following external programs: Python
15#
16
17if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000018 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
19 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000020else:
21 SETBINARY = ''
22
Tim Peters3761e8d2004-10-13 04:07:12 +000023# In a debug build, stuff like "[6580 refs]" is printed to stderr at
24# shutdown time. That frustrates tests trying to check stderr produced
25# from a spawned Python process.
26def remove_stderr_debug_decorations(stderr):
Guido van Rossum98297ee2007-11-06 21:34:58 +000027 return re.sub("\[\d+ refs\]\r?\n?$", "", stderr.decode()).encode()
28 #return re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr)
Tim Peters3761e8d2004-10-13 04:07:12 +000029
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000030class ProcessTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000031 def setUp(self):
32 # Try to minimize the number of children we have so this test
33 # doesn't crash on some buildbots (Alphas in particular).
Benjamin Petersonee8712c2008-05-20 21:35:26 +000034 if hasattr(support, "reap_children"):
35 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000036
37 def tearDown(self):
38 # Try to minimize the number of children we have so this test
39 # doesn't crash on some buildbots (Alphas in particular).
Benjamin Petersonee8712c2008-05-20 21:35:26 +000040 if hasattr(support, "reap_children"):
41 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000042
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000043 def mkstemp(self):
44 """wrapper for mkstemp, calling mktemp if mkstemp is not available"""
45 if hasattr(tempfile, "mkstemp"):
46 return tempfile.mkstemp()
47 else:
48 fname = tempfile.mktemp()
49 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
Tim Peterse718f612004-10-12 21:51:32 +000050
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000051 #
52 # Generic tests
53 #
54 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000055 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000056 rc = subprocess.call([sys.executable, "-c",
57 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000058 self.assertEqual(rc, 47)
59
Peter Astrand454f7672005-01-01 09:36:35 +000060 def test_check_call_zero(self):
61 # check_call() function with zero return code
62 rc = subprocess.check_call([sys.executable, "-c",
63 "import sys; sys.exit(0)"])
64 self.assertEqual(rc, 0)
65
66 def test_check_call_nonzero(self):
67 # check_call() function with non-zero return code
68 try:
69 subprocess.check_call([sys.executable, "-c",
70 "import sys; sys.exit(47)"])
Guido van Rossumb940e112007-01-10 16:19:56 +000071 except subprocess.CalledProcessError as e:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072 self.assertEqual(e.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000073 else:
74 self.fail("Expected CalledProcessError")
75
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000076 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +000077 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000078 newenv = os.environ.copy()
79 newenv["FRUIT"] = "banana"
80 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +000081 'import sys, os;'
82 'sys.exit(os.getenv("FRUIT")=="banana")'],
83 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000084 self.assertEqual(rc, 1)
85
86 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +000087 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +000088 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000089 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
90 p.wait()
91 self.assertEqual(p.stdin, None)
92
93 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +000094 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +000095 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +000096 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +000097 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +000098 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +000099 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000100 p.wait()
101 self.assertEqual(p.stdout, None)
102
103 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000104 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000105 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000106 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
107 p.wait()
108 self.assertEqual(p.stderr, None)
109
110 def test_executable(self):
Tim Peters3b01a702004-10-12 22:19:32 +0000111 p = subprocess.Popen(["somethingyoudonthave",
112 "-c", "import sys; sys.exit(47)"],
113 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 p.wait()
115 self.assertEqual(p.returncode, 47)
116
117 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000118 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000119 p = subprocess.Popen([sys.executable, "-c",
120 'import sys; sys.exit(sys.stdin.read() == "pear")'],
121 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000122 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000123 p.stdin.close()
124 p.wait()
125 self.assertEqual(p.returncode, 1)
126
127 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000128 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000129 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000130 d = tf.fileno()
131 os.write(d, "pear")
132 os.lseek(d, 0, 0)
133 p = subprocess.Popen([sys.executable, "-c",
134 'import sys; sys.exit(sys.stdin.read() == "pear")'],
135 stdin=d)
136 p.wait()
137 self.assertEqual(p.returncode, 1)
138
139 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000140 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000141 tf = tempfile.TemporaryFile()
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000142 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000143 tf.seek(0)
144 p = subprocess.Popen([sys.executable, "-c",
145 'import sys; sys.exit(sys.stdin.read() == "pear")'],
146 stdin=tf)
147 p.wait()
148 self.assertEqual(p.returncode, 1)
149
150 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000151 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000152 p = subprocess.Popen([sys.executable, "-c",
153 'import sys; sys.stdout.write("orange")'],
154 stdout=subprocess.PIPE)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000155 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000156
157 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000158 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000159 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000160 d = tf.fileno()
161 p = subprocess.Popen([sys.executable, "-c",
162 'import sys; sys.stdout.write("orange")'],
163 stdout=d)
164 p.wait()
165 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000166 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000167
168 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000169 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000170 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000171 p = subprocess.Popen([sys.executable, "-c",
172 'import sys; sys.stdout.write("orange")'],
173 stdout=tf)
174 p.wait()
175 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000176 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000177
178 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000179 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000180 p = subprocess.Popen([sys.executable, "-c",
181 'import sys; sys.stderr.write("strawberry")'],
182 stderr=subprocess.PIPE)
Tim Peters3761e8d2004-10-13 04:07:12 +0000183 self.assertEqual(remove_stderr_debug_decorations(p.stderr.read()),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000184 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000185
186 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000187 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000188 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 d = tf.fileno()
190 p = subprocess.Popen([sys.executable, "-c",
191 'import sys; sys.stderr.write("strawberry")'],
192 stderr=d)
193 p.wait()
194 os.lseek(d, 0, 0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000195 self.assertEqual(remove_stderr_debug_decorations(os.read(d, 1024)),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000196 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000197
198 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000199 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000200 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000201 p = subprocess.Popen([sys.executable, "-c",
202 'import sys; sys.stderr.write("strawberry")'],
203 stderr=tf)
204 p.wait()
205 tf.seek(0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000206 self.assertEqual(remove_stderr_debug_decorations(tf.read()),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000207 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000208
209 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000210 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000211 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000212 'import sys;'
213 'sys.stdout.write("apple");'
214 'sys.stdout.flush();'
215 'sys.stderr.write("orange")'],
216 stdout=subprocess.PIPE,
217 stderr=subprocess.STDOUT)
Tim Peters3761e8d2004-10-13 04:07:12 +0000218 output = p.stdout.read()
219 stripped = remove_stderr_debug_decorations(output)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000220 self.assertEqual(stripped, b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000221
222 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000223 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000224 tf = tempfile.TemporaryFile()
225 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000226 'import sys;'
227 'sys.stdout.write("apple");'
228 'sys.stdout.flush();'
229 'sys.stderr.write("orange")'],
230 stdout=tf,
231 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000232 p.wait()
233 tf.seek(0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000234 output = tf.read()
235 stripped = remove_stderr_debug_decorations(output)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000236 self.assertEqual(stripped, b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000237
Thomas Wouters89f507f2006-12-13 04:49:30 +0000238 def test_stdout_filedes_of_stdout(self):
239 # stdout is set to 1 (#1531862).
240 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), '.\n'))"
241 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
242 self.assertEquals(rc, 2)
243
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000245 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000246 # We cannot use os.path.realpath to canonicalize the path,
247 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
248 cwd = os.getcwd()
249 os.chdir(tmpdir)
250 tmpdir = os.getcwd()
251 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000252 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000253 'import sys,os;'
254 'sys.stdout.write(os.getcwd())'],
255 stdout=subprocess.PIPE,
256 cwd=tmpdir)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000257 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000258 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
259 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000260
261 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262 newenv = os.environ.copy()
263 newenv["FRUIT"] = "orange"
264 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000265 'import sys,os;'
266 'sys.stdout.write(os.getenv("FRUIT"))'],
267 stdout=subprocess.PIPE,
268 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000269 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270
Peter Astrandcbac93c2005-03-03 20:24:28 +0000271 def test_communicate_stdin(self):
272 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000273 'import sys;'
274 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000275 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000276 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000277 self.assertEqual(p.returncode, 1)
278
279 def test_communicate_stdout(self):
280 p = subprocess.Popen([sys.executable, "-c",
281 'import sys; sys.stdout.write("pineapple")'],
282 stdout=subprocess.PIPE)
283 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000284 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000285 self.assertEqual(stderr, None)
286
287 def test_communicate_stderr(self):
288 p = subprocess.Popen([sys.executable, "-c",
289 'import sys; sys.stderr.write("pineapple")'],
290 stderr=subprocess.PIPE)
291 (stdout, stderr) = p.communicate()
292 self.assertEqual(stdout, None)
Brett Cannon653a5ad2005-03-05 06:40:52 +0000293 # When running with a pydebug build, the # of references is outputted
294 # to stderr, so just check if stderr at least started with "pinapple"
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000295 self.assert_(stderr.startswith(b"pineapple"))
Peter Astrandcbac93c2005-03-03 20:24:28 +0000296
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000297 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000299 'import sys,os;'
300 'sys.stderr.write("pineapple");'
301 'sys.stdout.write(sys.stdin.read())'],
302 stdin=subprocess.PIPE,
303 stdout=subprocess.PIPE,
304 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000305 (stdout, stderr) = p.communicate("banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000306 self.assertEqual(stdout, b"banana")
Tim Peters3761e8d2004-10-13 04:07:12 +0000307 self.assertEqual(remove_stderr_debug_decorations(stderr),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000308 b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309
310 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000311 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000312 p = subprocess.Popen([sys.executable, "-c",
313 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000314 (stdout, stderr) = p.communicate()
315 self.assertEqual(stdout, None)
316 self.assertEqual(stderr, None)
317
318 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000319 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000320 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000321 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000322 x, y = os.pipe()
323 if mswindows:
324 pipe_buf = 512
325 else:
326 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
327 os.close(x)
328 os.close(y)
329 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000330 'import sys,os;'
331 'sys.stdout.write(sys.stdin.read(47));'
332 'sys.stderr.write("xyz"*%d);'
333 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
334 stdin=subprocess.PIPE,
335 stdout=subprocess.PIPE,
336 stderr=subprocess.PIPE)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000337 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000338 (stdout, stderr) = p.communicate(string_to_write)
339 self.assertEqual(stdout, string_to_write)
340
341 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000342 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000343 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000344 'import sys,os;'
345 'sys.stdout.write(sys.stdin.read())'],
346 stdin=subprocess.PIPE,
347 stdout=subprocess.PIPE,
348 stderr=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000349 p.stdin.write(b"banana")
350 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000351 self.assertEqual(stdout, b"bananasplit")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000352 self.assertEqual(remove_stderr_debug_decorations(stderr), b"")
Tim Peterse718f612004-10-12 21:51:32 +0000353
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000355 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000356 'import sys,os;' + SETBINARY +
357 'sys.stdout.write("line1\\n");'
358 'sys.stdout.flush();'
359 'sys.stdout.write("line2\\n");'
360 'sys.stdout.flush();'
361 'sys.stdout.write("line3\\r\\n");'
362 'sys.stdout.flush();'
363 'sys.stdout.write("line4\\r");'
364 'sys.stdout.flush();'
365 'sys.stdout.write("\\nline5");'
366 'sys.stdout.flush();'
367 'sys.stdout.write("\\nline6");'],
368 stdout=subprocess.PIPE,
369 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000371 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000372
373 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000374 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000375 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000376 'import sys,os;' + SETBINARY +
377 'sys.stdout.write("line1\\n");'
378 'sys.stdout.flush();'
379 'sys.stdout.write("line2\\n");'
380 'sys.stdout.flush();'
381 'sys.stdout.write("line3\\r\\n");'
382 'sys.stdout.flush();'
383 'sys.stdout.write("line4\\r");'
384 'sys.stdout.flush();'
385 'sys.stdout.write("\\nline5");'
386 'sys.stdout.flush();'
387 'sys.stdout.write("\\nline6");'],
388 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
389 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000391 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000392
393 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000394 # Make sure we leak no resources
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000395 if (not hasattr(support, "is_resource_enabled") or
396 support.is_resource_enabled("subprocess") and not mswindows):
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000397 max_handles = 1026 # too much for most UNIX systems
398 else:
Tim Peterseba28be2005-03-28 01:08:02 +0000399 max_handles = 65
Fredrik Lundh9e29fc52004-10-13 07:54:54 +0000400 for i in range(max_handles):
Tim Peters3b01a702004-10-12 22:19:32 +0000401 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000402 "import sys;"
403 "sys.stdout.write(sys.stdin.read())"],
404 stdin=subprocess.PIPE,
405 stdout=subprocess.PIPE,
406 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000407 data = p.communicate("lime")[0]
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000408 self.assertEqual(data, b"lime")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000409
410
411 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000412 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
413 '"a b c" d e')
414 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
415 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000416 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
417 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000418 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
419 'a\\\\\\b "de fg" h')
420 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
421 'a\\\\\\"b c d')
422 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
423 '"a\\\\b c" d e')
424 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
425 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000426 self.assertEqual(subprocess.list2cmdline(['ab', '']),
427 'ab ""')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000428 self.assertEqual(subprocess.list2cmdline(['echo', 'foo|bar']),
429 'echo "foo|bar"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000430
431
432 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000434 "-c", "import time; time.sleep(1)"])
435 count = 0
436 while p.poll() is None:
437 time.sleep(0.1)
438 count += 1
439 # We expect that the poll loop probably went around about 10 times,
440 # but, based on system scheduling we can't control, it's possible
441 # poll() never returned None. It "should be" very rare that it
442 # didn't go around at least twice.
443 self.assert_(count >= 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 # Subsequent invocations should just return the returncode
445 self.assertEqual(p.poll(), 0)
446
447
448 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449 p = subprocess.Popen([sys.executable,
450 "-c", "import time; time.sleep(2)"])
451 self.assertEqual(p.wait(), 0)
452 # Subsequent invocations should just return the returncode
453 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000454
Peter Astrand738131d2004-11-30 21:04:45 +0000455
456 def test_invalid_bufsize(self):
457 # an invalid type of the bufsize argument should raise
458 # TypeError.
459 try:
460 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
461 except TypeError:
462 pass
463 else:
464 self.fail("Expected TypeError")
465
Guido van Rossum46a05a72007-06-07 21:56:45 +0000466 def test_bufsize_is_none(self):
467 # bufsize=None should be the same as bufsize=0.
468 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
469 self.assertEqual(p.wait(), 0)
470 # Again with keyword arg
471 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
472 self.assertEqual(p.wait(), 0)
473
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474 #
475 # POSIX tests
476 #
477 if not mswindows:
478 def test_exceptions(self):
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000479 # caught & re-raised exceptions
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000480 try:
481 p = subprocess.Popen([sys.executable, "-c", ""],
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000482 cwd="/this/path/does/not/exist")
Guido van Rossumb940e112007-01-10 16:19:56 +0000483 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484 # The attribute child_traceback should contain "os.chdir"
485 # somewhere.
486 self.assertNotEqual(e.child_traceback.find("os.chdir"), -1)
487 else:
488 self.fail("Expected OSError")
Tim Peterse718f612004-10-12 21:51:32 +0000489
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000490 def _suppress_core_files(self):
491 """Try to prevent core files from being created.
492 Returns previous ulimit if successful, else None.
493 """
494 try:
495 import resource
496 old_limit = resource.getrlimit(resource.RLIMIT_CORE)
497 resource.setrlimit(resource.RLIMIT_CORE, (0,0))
498 return old_limit
499 except (ImportError, ValueError, resource.error):
500 return None
501
502 def _unsuppress_core_files(self, old_limit):
503 """Return core file behavior to default."""
504 if old_limit is None:
505 return
506 try:
507 import resource
508 resource.setrlimit(resource.RLIMIT_CORE, old_limit)
509 except (ImportError, ValueError, resource.error):
510 return
511
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 def test_run_abort(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000513 # returncode handles signal termination
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000514 old_limit = self._suppress_core_files()
515 try:
516 p = subprocess.Popen([sys.executable,
517 "-c", "import os; os.abort()"])
518 finally:
519 self._unsuppress_core_files(old_limit)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520 p.wait()
521 self.assertEqual(-p.returncode, signal.SIGABRT)
522
523 def test_preexec(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000524 # preexec function
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000526 'import sys,os;'
527 'sys.stdout.write(os.getenv("FRUIT"))'],
528 stdout=subprocess.PIPE,
529 preexec_fn=lambda: os.putenv("FRUIT",
530 "apple"))
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000531 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000533 def test_args_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000534 # args is a string
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000535 f, fname = self.mkstemp()
536 os.write(f, "#!/bin/sh\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000537 os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" %
538 sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000539 os.close(f)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000540 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000541 p = subprocess.Popen(fname)
542 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 os.remove(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000544 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545
546 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000547 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000549 [sys.executable,
550 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551 startupinfo=47)
552 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000553 [sys.executable,
554 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000555 creationflags=47)
556
557 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000558 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 newenv = os.environ.copy()
560 newenv["FRUIT"] = "apple"
561 p = subprocess.Popen(["echo $FRUIT"], shell=1,
562 stdout=subprocess.PIPE,
563 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000564 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565
566 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000567 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568 newenv = os.environ.copy()
569 newenv["FRUIT"] = "apple"
570 p = subprocess.Popen("echo $FRUIT", shell=1,
571 stdout=subprocess.PIPE,
572 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000573 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000574
575 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000576 # call() function with string argument on UNIX
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000577 f, fname = self.mkstemp()
578 os.write(f, "#!/bin/sh\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000579 os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" %
580 sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000581 os.close(f)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000582 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000583 rc = subprocess.call(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000584 os.remove(fname)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000585 self.assertEqual(rc, 47)
586
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000587 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000588 p = subprocess.Popen([sys.executable,
589 "-c", "input()"])
590
591 self.assert_(p.poll() is None, p.poll())
592 p.send_signal(signal.SIGINT)
593 self.assertNotEqual(p.wait(), 0)
594
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000595 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000596 p = subprocess.Popen([sys.executable,
597 "-c", "input()"])
598
599 self.assert_(p.poll() is None, p.poll())
600 p.kill()
601 self.assertEqual(p.wait(), -signal.SIGKILL)
602
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000603 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000604 p = subprocess.Popen([sys.executable,
605 "-c", "input()"])
606
607 self.assert_(p.poll() is None, p.poll())
608 p.terminate()
609 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000610
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000611 #
612 # Windows tests
613 #
614 if mswindows:
615 def test_startupinfo(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000616 # startupinfo argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000617 # We uses hardcoded constants, because we do not want to
Tim Peterse718f612004-10-12 21:51:32 +0000618 # depend on win32all.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619 STARTF_USESHOWWINDOW = 1
620 SW_MAXIMIZE = 3
621 startupinfo = subprocess.STARTUPINFO()
622 startupinfo.dwFlags = STARTF_USESHOWWINDOW
623 startupinfo.wShowWindow = SW_MAXIMIZE
624 # Since Python is a console process, it won't be affected
625 # by wShowWindow, but the argument should be silently
626 # ignored
627 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
628 startupinfo=startupinfo)
629
630 def test_creationflags(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000631 # creationflags argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000632 CREATE_NEW_CONSOLE = 16
Tim Peters876c4322004-10-13 03:21:35 +0000633 sys.stderr.write(" a DOS box should flash briefly ...\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000634 subprocess.call(sys.executable +
Tim Peters876c4322004-10-13 03:21:35 +0000635 ' -c "import time; time.sleep(0.25)"',
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000636 creationflags=CREATE_NEW_CONSOLE)
637
638 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000639 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000640 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000641 [sys.executable,
642 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643 preexec_fn=lambda: 1)
644 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000645 [sys.executable,
646 "-c", "import sys; sys.exit(47)"],
Guido van Rossume7ba4952007-06-06 23:52:48 +0000647 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000648 close_fds=True)
649
Guido van Rossume7ba4952007-06-06 23:52:48 +0000650 def test_close_fds(self):
651 # close file descriptors
652 rc = subprocess.call([sys.executable, "-c",
653 "import sys; sys.exit(47)"],
654 close_fds=True)
655 self.assertEqual(rc, 47)
656
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000657 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000658 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659 newenv = os.environ.copy()
660 newenv["FRUIT"] = "physalis"
661 p = subprocess.Popen(["set"], shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000662 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000664 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000665
666 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000667 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000668 newenv = os.environ.copy()
669 newenv["FRUIT"] = "physalis"
670 p = subprocess.Popen("set", shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000671 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000672 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000673 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000674
675 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000676 # call() function with string argument on Windows
Tim Peters3b01a702004-10-12 22:19:32 +0000677 rc = subprocess.call(sys.executable +
678 ' -c "import sys; sys.exit(47)"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000679 self.assertEqual(rc, 47)
680
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000681 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000682 p = subprocess.Popen([sys.executable,
683 "-c", "input()"])
684
685 self.assert_(p.poll() is None, p.poll())
686 p.send_signal(signal.SIGTERM)
687 self.assertNotEqual(p.wait(), 0)
688
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000689 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000690 p = subprocess.Popen([sys.executable,
691 "-c", "input()"])
692
693 self.assert_(p.poll() is None, p.poll())
694 p.kill()
695 self.assertNotEqual(p.wait(), 0)
696
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000697 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000698 p = subprocess.Popen([sys.executable,
699 "-c", "input()"])
700
701 self.assert_(p.poll() is None, p.poll())
702 p.terminate()
703 self.assertNotEqual(p.wait(), 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000704
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000705def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000706 support.run_unittest(ProcessTestCase)
707 if hasattr(support, "reap_children"):
708 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000709
710if __name__ == "__main__":
Guido van Rossum98297ee2007-11-06 21:34:58 +0000711 unittest.main() # XXX test_main()