blob: 8c8ac405f8c0f71067b702f5bb9b79f3e33cbae2 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
2from test import test_support
3import 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):
Tim Peters1dbf2432004-10-14 04:16:54 +000027 return re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr)
Tim Peters3761e8d2004-10-13 04:07:12 +000028
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000029class ProcessTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000030 def setUp(self):
31 # Try to minimize the number of children we have so this test
32 # doesn't crash on some buildbots (Alphas in particular).
33 if hasattr(test_support, "reap_children"):
34 test_support.reap_children()
35
36 def tearDown(self):
37 # Try to minimize the number of children we have so this test
38 # doesn't crash on some buildbots (Alphas in particular).
39 if hasattr(test_support, "reap_children"):
40 test_support.reap_children()
41
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000042 def mkstemp(self):
43 """wrapper for mkstemp, calling mktemp if mkstemp is not available"""
44 if hasattr(tempfile, "mkstemp"):
45 return tempfile.mkstemp()
46 else:
47 fname = tempfile.mktemp()
48 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
Tim Peterse718f612004-10-12 21:51:32 +000049
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000050 #
51 # Generic tests
52 #
53 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000054 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000055 rc = subprocess.call([sys.executable, "-c",
56 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000057 self.assertEqual(rc, 47)
58
Peter Astrand454f7672005-01-01 09:36:35 +000059 def test_check_call_zero(self):
60 # check_call() function with zero return code
61 rc = subprocess.check_call([sys.executable, "-c",
62 "import sys; sys.exit(0)"])
63 self.assertEqual(rc, 0)
64
65 def test_check_call_nonzero(self):
66 # check_call() function with non-zero return code
67 try:
68 subprocess.check_call([sys.executable, "-c",
69 "import sys; sys.exit(47)"])
70 except subprocess.CalledProcessError, e:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000071 self.assertEqual(e.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000072 else:
73 self.fail("Expected CalledProcessError")
74
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000075 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +000076 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000077 newenv = os.environ.copy()
78 newenv["FRUIT"] = "banana"
79 rc = subprocess.call([sys.executable, "-c",
80 'import sys, os;' \
81 'sys.exit(os.getenv("FRUIT")=="banana")'],
82 env=newenv)
83 self.assertEqual(rc, 1)
84
85 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +000086 # .stdin is None when not redirected
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000087 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
88 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
89 p.wait()
90 self.assertEqual(p.stdin, None)
91
92 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +000093 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +000094 p = subprocess.Popen([sys.executable, "-c",
Tim Peters4052fe52004-10-13 03:29:54 +000095 'print " this bit of output is from a '
96 'test of stdout in a different '
97 'process ..."'],
98 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000099 p.wait()
100 self.assertEqual(p.stdout, None)
101
102 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000103 # .stderr is None when not redirected
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000104 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
105 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
106 p.wait()
107 self.assertEqual(p.stderr, None)
108
109 def test_executable(self):
Tim Peters3b01a702004-10-12 22:19:32 +0000110 p = subprocess.Popen(["somethingyoudonthave",
111 "-c", "import sys; sys.exit(47)"],
112 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000113 p.wait()
114 self.assertEqual(p.returncode, 47)
115
116 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000117 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000118 p = subprocess.Popen([sys.executable, "-c",
119 'import sys; sys.exit(sys.stdin.read() == "pear")'],
120 stdin=subprocess.PIPE)
121 p.stdin.write("pear")
122 p.stdin.close()
123 p.wait()
124 self.assertEqual(p.returncode, 1)
125
126 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000127 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000128 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000129 d = tf.fileno()
130 os.write(d, "pear")
131 os.lseek(d, 0, 0)
132 p = subprocess.Popen([sys.executable, "-c",
133 'import sys; sys.exit(sys.stdin.read() == "pear")'],
134 stdin=d)
135 p.wait()
136 self.assertEqual(p.returncode, 1)
137
138 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000139 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140 tf = tempfile.TemporaryFile()
141 tf.write("pear")
142 tf.seek(0)
143 p = subprocess.Popen([sys.executable, "-c",
144 'import sys; sys.exit(sys.stdin.read() == "pear")'],
145 stdin=tf)
146 p.wait()
147 self.assertEqual(p.returncode, 1)
148
149 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000150 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000151 p = subprocess.Popen([sys.executable, "-c",
152 'import sys; sys.stdout.write("orange")'],
153 stdout=subprocess.PIPE)
154 self.assertEqual(p.stdout.read(), "orange")
155
156 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000157 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000158 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000159 d = tf.fileno()
160 p = subprocess.Popen([sys.executable, "-c",
161 'import sys; sys.stdout.write("orange")'],
162 stdout=d)
163 p.wait()
164 os.lseek(d, 0, 0)
165 self.assertEqual(os.read(d, 1024), "orange")
166
167 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000168 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000169 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000170 p = subprocess.Popen([sys.executable, "-c",
171 'import sys; sys.stdout.write("orange")'],
172 stdout=tf)
173 p.wait()
174 tf.seek(0)
175 self.assertEqual(tf.read(), "orange")
176
177 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000178 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000179 p = subprocess.Popen([sys.executable, "-c",
180 'import sys; sys.stderr.write("strawberry")'],
181 stderr=subprocess.PIPE)
Tim Peters3761e8d2004-10-13 04:07:12 +0000182 self.assertEqual(remove_stderr_debug_decorations(p.stderr.read()),
183 "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000184
185 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000186 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000187 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000188 d = tf.fileno()
189 p = subprocess.Popen([sys.executable, "-c",
190 'import sys; sys.stderr.write("strawberry")'],
191 stderr=d)
192 p.wait()
193 os.lseek(d, 0, 0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000194 self.assertEqual(remove_stderr_debug_decorations(os.read(d, 1024)),
195 "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000196
197 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000198 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000199 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000200 p = subprocess.Popen([sys.executable, "-c",
201 'import sys; sys.stderr.write("strawberry")'],
202 stderr=tf)
203 p.wait()
204 tf.seek(0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000205 self.assertEqual(remove_stderr_debug_decorations(tf.read()),
206 "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000207
208 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000209 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210 p = subprocess.Popen([sys.executable, "-c",
211 'import sys;' \
212 'sys.stdout.write("apple");' \
213 'sys.stdout.flush();' \
214 'sys.stderr.write("orange")'],
215 stdout=subprocess.PIPE,
216 stderr=subprocess.STDOUT)
Tim Peters3761e8d2004-10-13 04:07:12 +0000217 output = p.stdout.read()
218 stripped = remove_stderr_debug_decorations(output)
219 self.assertEqual(stripped, "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000220
221 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000222 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223 tf = tempfile.TemporaryFile()
224 p = subprocess.Popen([sys.executable, "-c",
225 'import sys;' \
226 'sys.stdout.write("apple");' \
227 'sys.stdout.flush();' \
228 'sys.stderr.write("orange")'],
229 stdout=tf,
230 stderr=tf)
231 p.wait()
232 tf.seek(0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000233 output = tf.read()
234 stripped = remove_stderr_debug_decorations(output)
235 self.assertEqual(stripped, "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236
237 def test_cwd(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238 tmpdir = os.getenv("TEMP", "/tmp")
Peter Astrand195404f2004-11-12 15:51:48 +0000239 # We cannot use os.path.realpath to canonicalize the path,
240 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
241 cwd = os.getcwd()
242 os.chdir(tmpdir)
243 tmpdir = os.getcwd()
244 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 p = subprocess.Popen([sys.executable, "-c",
246 'import sys,os;' \
247 'sys.stdout.write(os.getcwd())'],
248 stdout=subprocess.PIPE,
249 cwd=tmpdir)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000250 normcase = os.path.normcase
251 self.assertEqual(normcase(p.stdout.read()), normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000252
253 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000254 newenv = os.environ.copy()
255 newenv["FRUIT"] = "orange"
256 p = subprocess.Popen([sys.executable, "-c",
257 'import sys,os;' \
258 'sys.stdout.write(os.getenv("FRUIT"))'],
259 stdout=subprocess.PIPE,
260 env=newenv)
261 self.assertEqual(p.stdout.read(), "orange")
262
Peter Astrandcbac93c2005-03-03 20:24:28 +0000263 def test_communicate_stdin(self):
264 p = subprocess.Popen([sys.executable, "-c",
265 'import sys; sys.exit(sys.stdin.read() == "pear")'],
266 stdin=subprocess.PIPE)
267 p.communicate("pear")
268 self.assertEqual(p.returncode, 1)
269
270 def test_communicate_stdout(self):
271 p = subprocess.Popen([sys.executable, "-c",
272 'import sys; sys.stdout.write("pineapple")'],
273 stdout=subprocess.PIPE)
274 (stdout, stderr) = p.communicate()
275 self.assertEqual(stdout, "pineapple")
276 self.assertEqual(stderr, None)
277
278 def test_communicate_stderr(self):
279 p = subprocess.Popen([sys.executable, "-c",
280 'import sys; sys.stderr.write("pineapple")'],
281 stderr=subprocess.PIPE)
282 (stdout, stderr) = p.communicate()
283 self.assertEqual(stdout, None)
Brett Cannon653a5ad2005-03-05 06:40:52 +0000284 # When running with a pydebug build, the # of references is outputted
285 # to stderr, so just check if stderr at least started with "pinapple"
286 self.assert_(stderr.startswith("pineapple"))
Peter Astrandcbac93c2005-03-03 20:24:28 +0000287
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000288 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000289 p = subprocess.Popen([sys.executable, "-c",
290 'import sys,os;' \
291 'sys.stderr.write("pineapple");' \
292 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000293 stdin=subprocess.PIPE,
294 stdout=subprocess.PIPE,
295 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296 (stdout, stderr) = p.communicate("banana")
297 self.assertEqual(stdout, "banana")
Tim Peters3761e8d2004-10-13 04:07:12 +0000298 self.assertEqual(remove_stderr_debug_decorations(stderr),
299 "pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000300
301 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000302 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000303 p = subprocess.Popen([sys.executable, "-c",
304 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000305 (stdout, stderr) = p.communicate()
306 self.assertEqual(stdout, None)
307 self.assertEqual(stderr, None)
308
309 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000310 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000311 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000312 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000313 x, y = os.pipe()
314 if mswindows:
315 pipe_buf = 512
316 else:
317 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
318 os.close(x)
319 os.close(y)
320 p = subprocess.Popen([sys.executable, "-c",
Tim Peterse718f612004-10-12 21:51:32 +0000321 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000322 'sys.stdout.write(sys.stdin.read(47));' \
323 'sys.stderr.write("xyz"*%d);' \
324 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
Tim Peters3b01a702004-10-12 22:19:32 +0000325 stdin=subprocess.PIPE,
326 stdout=subprocess.PIPE,
327 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000328 string_to_write = "abc"*pipe_buf
329 (stdout, stderr) = p.communicate(string_to_write)
330 self.assertEqual(stdout, string_to_write)
331
332 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000333 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334 p = subprocess.Popen([sys.executable, "-c",
335 'import sys,os;' \
336 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000337 stdin=subprocess.PIPE,
338 stdout=subprocess.PIPE,
339 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000340 p.stdin.write("banana")
341 (stdout, stderr) = p.communicate("split")
342 self.assertEqual(stdout, "bananasplit")
Tim Peters3761e8d2004-10-13 04:07:12 +0000343 self.assertEqual(remove_stderr_debug_decorations(stderr), "")
Tim Peterse718f612004-10-12 21:51:32 +0000344
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000345 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000346 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000347 'import sys,os;' + SETBINARY +
348 'sys.stdout.write("line1\\n");'
349 'sys.stdout.flush();'
350 'sys.stdout.write("line2\\r");'
351 'sys.stdout.flush();'
352 'sys.stdout.write("line3\\r\\n");'
353 'sys.stdout.flush();'
354 'sys.stdout.write("line4\\r");'
355 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000356 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000357 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000358 'sys.stdout.write("\\nline6");'],
359 stdout=subprocess.PIPE,
360 universal_newlines=1)
361 stdout = p.stdout.read()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000362 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000363 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000364 self.assertEqual(stdout,
365 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000366 else:
367 # Interpreter without universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000368 self.assertEqual(stdout,
369 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370
371 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000372 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000373 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000374 'import sys,os;' + SETBINARY +
375 'sys.stdout.write("line1\\n");'
376 'sys.stdout.flush();'
377 'sys.stdout.write("line2\\r");'
378 'sys.stdout.flush();'
379 'sys.stdout.write("line3\\r\\n");'
380 'sys.stdout.flush();'
381 'sys.stdout.write("line4\\r");'
382 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000383 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000384 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000385 'sys.stdout.write("\\nline6");'],
386 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
387 universal_newlines=1)
388 (stdout, stderr) = p.communicate()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000389 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000391 self.assertEqual(stdout,
392 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000393 else:
394 # Interpreter without universal newline support
395 self.assertEqual(stdout, "line1\nline2\rline3\r\nline4\r\nline5\nline6")
396
397 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000398 # Make sure we leak no resources
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000399 if not hasattr(test_support, "is_resource_enabled") \
400 or test_support.is_resource_enabled("subprocess") and not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000401 max_handles = 1026 # too much for most UNIX systems
402 else:
Tim Peterseba28be2005-03-28 01:08:02 +0000403 max_handles = 65
Fredrik Lundh9e29fc52004-10-13 07:54:54 +0000404 for i in range(max_handles):
Tim Peters3b01a702004-10-12 22:19:32 +0000405 p = subprocess.Popen([sys.executable, "-c",
406 "import sys;sys.stdout.write(sys.stdin.read())"],
407 stdin=subprocess.PIPE,
408 stdout=subprocess.PIPE,
409 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000410 data = p.communicate("lime")[0]
411 self.assertEqual(data, "lime")
412
413
414 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000415 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
416 '"a b c" d e')
417 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
418 'ab\\"c \\ d')
419 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
420 'a\\\\\\b "de fg" h')
421 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
422 'a\\\\\\"b c d')
423 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
424 '"a\\\\b c" d e')
425 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
426 '"a\\\\b\\ c" d e')
427
428
429 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000430 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000431 "-c", "import time; time.sleep(1)"])
432 count = 0
433 while p.poll() is None:
434 time.sleep(0.1)
435 count += 1
436 # We expect that the poll loop probably went around about 10 times,
437 # but, based on system scheduling we can't control, it's possible
438 # poll() never returned None. It "should be" very rare that it
439 # didn't go around at least twice.
440 self.assert_(count >= 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000441 # Subsequent invocations should just return the returncode
442 self.assertEqual(p.poll(), 0)
443
444
445 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000446 p = subprocess.Popen([sys.executable,
447 "-c", "import time; time.sleep(2)"])
448 self.assertEqual(p.wait(), 0)
449 # Subsequent invocations should just return the returncode
450 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000451
Peter Astrand738131d2004-11-30 21:04:45 +0000452
453 def test_invalid_bufsize(self):
454 # an invalid type of the bufsize argument should raise
455 # TypeError.
456 try:
457 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
458 except TypeError:
459 pass
460 else:
461 self.fail("Expected TypeError")
462
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463 #
464 # POSIX tests
465 #
466 if not mswindows:
467 def test_exceptions(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000468 # catched & re-raised exceptions
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000469 try:
470 p = subprocess.Popen([sys.executable, "-c", ""],
471 cwd="/this/path/does/not/exist")
472 except OSError, e:
473 # The attribute child_traceback should contain "os.chdir"
474 # somewhere.
475 self.assertNotEqual(e.child_traceback.find("os.chdir"), -1)
476 else:
477 self.fail("Expected OSError")
Tim Peterse718f612004-10-12 21:51:32 +0000478
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000479 def _suppress_core_files(self):
480 """Try to prevent core files from being created.
481 Returns previous ulimit if successful, else None.
482 """
483 try:
484 import resource
485 old_limit = resource.getrlimit(resource.RLIMIT_CORE)
486 resource.setrlimit(resource.RLIMIT_CORE, (0,0))
487 return old_limit
488 except (ImportError, ValueError, resource.error):
489 return None
490
491 def _unsuppress_core_files(self, old_limit):
492 """Return core file behavior to default."""
493 if old_limit is None:
494 return
495 try:
496 import resource
497 resource.setrlimit(resource.RLIMIT_CORE, old_limit)
498 except (ImportError, ValueError, resource.error):
499 return
500
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501 def test_run_abort(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000502 # returncode handles signal termination
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000503 old_limit = self._suppress_core_files()
504 try:
505 p = subprocess.Popen([sys.executable,
506 "-c", "import os; os.abort()"])
507 finally:
508 self._unsuppress_core_files(old_limit)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000509 p.wait()
510 self.assertEqual(-p.returncode, signal.SIGABRT)
511
512 def test_preexec(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000513 # preexec function
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514 p = subprocess.Popen([sys.executable, "-c",
515 'import sys,os;' \
516 'sys.stdout.write(os.getenv("FRUIT"))'],
517 stdout=subprocess.PIPE,
518 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
519 self.assertEqual(p.stdout.read(), "apple")
520
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000521 def test_args_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000522 # args is a string
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523 f, fname = self.mkstemp()
524 os.write(f, "#!/bin/sh\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000525 os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" %
526 sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527 os.close(f)
528 os.chmod(fname, 0700)
529 p = subprocess.Popen(fname)
530 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 os.remove(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000532 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000533
534 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000535 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000536 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000537 [sys.executable,
538 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000539 startupinfo=47)
540 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000541 [sys.executable,
542 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 creationflags=47)
544
545 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000546 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 newenv = os.environ.copy()
548 newenv["FRUIT"] = "apple"
549 p = subprocess.Popen(["echo $FRUIT"], shell=1,
550 stdout=subprocess.PIPE,
551 env=newenv)
552 self.assertEqual(p.stdout.read().strip(), "apple")
553
554 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000555 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556 newenv = os.environ.copy()
557 newenv["FRUIT"] = "apple"
558 p = subprocess.Popen("echo $FRUIT", shell=1,
559 stdout=subprocess.PIPE,
560 env=newenv)
561 self.assertEqual(p.stdout.read().strip(), "apple")
562
563 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000564 # call() function with string argument on UNIX
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565 f, fname = self.mkstemp()
566 os.write(f, "#!/bin/sh\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000567 os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" %
568 sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000569 os.close(f)
570 os.chmod(fname, 0700)
571 rc = subprocess.call(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000572 os.remove(fname)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000573 self.assertEqual(rc, 47)
574
Tim Peterse718f612004-10-12 21:51:32 +0000575
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000576 #
577 # Windows tests
578 #
579 if mswindows:
580 def test_startupinfo(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000581 # startupinfo argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000582 # We uses hardcoded constants, because we do not want to
Tim Peterse718f612004-10-12 21:51:32 +0000583 # depend on win32all.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000584 STARTF_USESHOWWINDOW = 1
585 SW_MAXIMIZE = 3
586 startupinfo = subprocess.STARTUPINFO()
587 startupinfo.dwFlags = STARTF_USESHOWWINDOW
588 startupinfo.wShowWindow = SW_MAXIMIZE
589 # Since Python is a console process, it won't be affected
590 # by wShowWindow, but the argument should be silently
591 # ignored
592 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
593 startupinfo=startupinfo)
594
595 def test_creationflags(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000596 # creationflags argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000597 CREATE_NEW_CONSOLE = 16
Tim Peters876c4322004-10-13 03:21:35 +0000598 sys.stderr.write(" a DOS box should flash briefly ...\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000599 subprocess.call(sys.executable +
Tim Peters876c4322004-10-13 03:21:35 +0000600 ' -c "import time; time.sleep(0.25)"',
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601 creationflags=CREATE_NEW_CONSOLE)
602
603 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000604 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000605 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000606 [sys.executable,
607 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000608 preexec_fn=lambda: 1)
609 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000610 [sys.executable,
611 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000612 close_fds=True)
613
614 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000615 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616 newenv = os.environ.copy()
617 newenv["FRUIT"] = "physalis"
618 p = subprocess.Popen(["set"], shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000619 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000620 env=newenv)
621 self.assertNotEqual(p.stdout.read().find("physalis"), -1)
622
623 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000624 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000625 newenv = os.environ.copy()
626 newenv["FRUIT"] = "physalis"
627 p = subprocess.Popen("set", shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000628 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000629 env=newenv)
630 self.assertNotEqual(p.stdout.read().find("physalis"), -1)
631
632 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000633 # call() function with string argument on Windows
Tim Peters3b01a702004-10-12 22:19:32 +0000634 rc = subprocess.call(sys.executable +
635 ' -c "import sys; sys.exit(47)"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000636 self.assertEqual(rc, 47)
637
638
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000639def test_main():
640 test_support.run_unittest(ProcessTestCase)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000641 if hasattr(test_support, "reap_children"):
642 test_support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643
644if __name__ == "__main__":
645 test_main()