blob: 2421a6b1106deaf50a01f3f627a17d0355fb606d [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):
Guido van Rossumc9e363c2007-05-15 23:18:55 +000027 return re.sub(r"\[\d+ refs\]\r?\n?$", "", str8(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)"])
Guido van Rossumb940e112007-01-10 16:19:56 +000070 except subprocess.CalledProcessError as 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
Georg Brandl88fc6642007-02-09 21:28:07 +000087 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000088 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",
Georg Brandl88fc6642007-02-09 21:28:07 +000095 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +000096 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +000097 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +000098 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
Georg Brandl88fc6642007-02-09 21:28:07 +0000104 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000105 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)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000154 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000155
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)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000165 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000166
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)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000175 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000176
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
Thomas Wouters89f507f2006-12-13 04:49:30 +0000237 def test_stdout_filedes_of_stdout(self):
238 # stdout is set to 1 (#1531862).
239 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), '.\n'))"
240 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
241 self.assertEquals(rc, 2)
242
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000243 def test_cwd(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244 tmpdir = os.getenv("TEMP", "/tmp")
Peter Astrand195404f2004-11-12 15:51:48 +0000245 # We cannot use os.path.realpath to canonicalize the path,
246 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
247 cwd = os.getcwd()
248 os.chdir(tmpdir)
249 tmpdir = os.getcwd()
250 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251 p = subprocess.Popen([sys.executable, "-c",
252 'import sys,os;' \
253 'sys.stdout.write(os.getcwd())'],
254 stdout=subprocess.PIPE,
255 cwd=tmpdir)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000256 normcase = os.path.normcase
257 self.assertEqual(normcase(p.stdout.read()), normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000258
259 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000260 newenv = os.environ.copy()
261 newenv["FRUIT"] = "orange"
262 p = subprocess.Popen([sys.executable, "-c",
263 'import sys,os;' \
264 'sys.stdout.write(os.getenv("FRUIT"))'],
265 stdout=subprocess.PIPE,
266 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000267 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268
Peter Astrandcbac93c2005-03-03 20:24:28 +0000269 def test_communicate_stdin(self):
270 p = subprocess.Popen([sys.executable, "-c",
271 'import sys; sys.exit(sys.stdin.read() == "pear")'],
272 stdin=subprocess.PIPE)
273 p.communicate("pear")
274 self.assertEqual(p.returncode, 1)
275
276 def test_communicate_stdout(self):
277 p = subprocess.Popen([sys.executable, "-c",
278 'import sys; sys.stdout.write("pineapple")'],
279 stdout=subprocess.PIPE)
280 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000281 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000282 self.assertEqual(stderr, None)
283
284 def test_communicate_stderr(self):
285 p = subprocess.Popen([sys.executable, "-c",
286 'import sys; sys.stderr.write("pineapple")'],
287 stderr=subprocess.PIPE)
288 (stdout, stderr) = p.communicate()
289 self.assertEqual(stdout, None)
Brett Cannon653a5ad2005-03-05 06:40:52 +0000290 # When running with a pydebug build, the # of references is outputted
291 # to stderr, so just check if stderr at least started with "pinapple"
292 self.assert_(stderr.startswith("pineapple"))
Peter Astrandcbac93c2005-03-03 20:24:28 +0000293
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000295 p = subprocess.Popen([sys.executable, "-c",
296 'import sys,os;' \
297 'sys.stderr.write("pineapple");' \
298 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000299 stdin=subprocess.PIPE,
300 stdout=subprocess.PIPE,
301 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000302 (stdout, stderr) = p.communicate("banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000303 self.assertEqual(stdout, b"banana")
Tim Peters3761e8d2004-10-13 04:07:12 +0000304 self.assertEqual(remove_stderr_debug_decorations(stderr),
305 "pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306
307 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000308 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000309 p = subprocess.Popen([sys.executable, "-c",
310 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000311 (stdout, stderr) = p.communicate()
312 self.assertEqual(stdout, None)
313 self.assertEqual(stderr, None)
314
315 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000316 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000317 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000318 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000319 x, y = os.pipe()
320 if mswindows:
321 pipe_buf = 512
322 else:
323 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
324 os.close(x)
325 os.close(y)
326 p = subprocess.Popen([sys.executable, "-c",
Tim Peterse718f612004-10-12 21:51:32 +0000327 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000328 'sys.stdout.write(sys.stdin.read(47));' \
329 'sys.stderr.write("xyz"*%d);' \
330 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
Tim Peters3b01a702004-10-12 22:19:32 +0000331 stdin=subprocess.PIPE,
332 stdout=subprocess.PIPE,
333 stderr=subprocess.PIPE)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000334 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000335 (stdout, stderr) = p.communicate(string_to_write)
336 self.assertEqual(stdout, string_to_write)
337
338 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000339 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000340 p = subprocess.Popen([sys.executable, "-c",
341 'import sys,os;' \
342 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000343 stdin=subprocess.PIPE,
344 stdout=subprocess.PIPE,
345 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000346 p.stdin.write("banana")
347 (stdout, stderr) = p.communicate("split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000348 self.assertEqual(stdout, b"bananasplit")
Tim Peters3761e8d2004-10-13 04:07:12 +0000349 self.assertEqual(remove_stderr_debug_decorations(stderr), "")
Tim Peterse718f612004-10-12 21:51:32 +0000350
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000351 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000352 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000353 'import sys,os;' + SETBINARY +
354 'sys.stdout.write("line1\\n");'
355 'sys.stdout.flush();'
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000356 'sys.stdout.write("line2\\n");'
Tim Peters3b01a702004-10-12 22:19:32 +0000357 'sys.stdout.flush();'
358 'sys.stdout.write("line3\\r\\n");'
359 'sys.stdout.flush();'
360 'sys.stdout.write("line4\\r");'
361 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000363 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000364 'sys.stdout.write("\\nline6");'],
365 stdout=subprocess.PIPE,
366 universal_newlines=1)
367 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000368 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000369
370 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000371 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000372 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000373 'import sys,os;' + SETBINARY +
374 'sys.stdout.write("line1\\n");'
375 'sys.stdout.flush();'
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000376 'sys.stdout.write("line2\\n");'
Tim Peters3b01a702004-10-12 22:19:32 +0000377 'sys.stdout.flush();'
378 'sys.stdout.write("line3\\r\\n");'
379 'sys.stdout.flush();'
380 'sys.stdout.write("line4\\r");'
381 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000382 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000383 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000384 'sys.stdout.write("\\nline6");'],
385 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
386 universal_newlines=1)
387 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000388 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000389
390 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000391 # Make sure we leak no resources
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000392 if not hasattr(test_support, "is_resource_enabled") \
393 or test_support.is_resource_enabled("subprocess") and not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000394 max_handles = 1026 # too much for most UNIX systems
395 else:
Tim Peterseba28be2005-03-28 01:08:02 +0000396 max_handles = 65
Fredrik Lundh9e29fc52004-10-13 07:54:54 +0000397 for i in range(max_handles):
Tim Peters3b01a702004-10-12 22:19:32 +0000398 p = subprocess.Popen([sys.executable, "-c",
399 "import sys;sys.stdout.write(sys.stdin.read())"],
400 stdin=subprocess.PIPE,
401 stdout=subprocess.PIPE,
402 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000403 data = p.communicate("lime")[0]
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000404 self.assertEqual(data, b"lime")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000405
406
407 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000408 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
409 '"a b c" d e')
410 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
411 'ab\\"c \\ d')
412 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
413 'a\\\\\\b "de fg" h')
414 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
415 'a\\\\\\"b c d')
416 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
417 '"a\\\\b c" d e')
418 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
419 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000420 self.assertEqual(subprocess.list2cmdline(['ab', '']),
421 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000422
423
424 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000425 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000426 "-c", "import time; time.sleep(1)"])
427 count = 0
428 while p.poll() is None:
429 time.sleep(0.1)
430 count += 1
431 # We expect that the poll loop probably went around about 10 times,
432 # but, based on system scheduling we can't control, it's possible
433 # poll() never returned None. It "should be" very rare that it
434 # didn't go around at least twice.
435 self.assert_(count >= 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000436 # Subsequent invocations should just return the returncode
437 self.assertEqual(p.poll(), 0)
438
439
440 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000441 p = subprocess.Popen([sys.executable,
442 "-c", "import time; time.sleep(2)"])
443 self.assertEqual(p.wait(), 0)
444 # Subsequent invocations should just return the returncode
445 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000446
Peter Astrand738131d2004-11-30 21:04:45 +0000447
448 def test_invalid_bufsize(self):
449 # an invalid type of the bufsize argument should raise
450 # TypeError.
451 try:
452 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
453 except TypeError:
454 pass
455 else:
456 self.fail("Expected TypeError")
457
Guido van Rossum46a05a72007-06-07 21:56:45 +0000458 def test_bufsize_is_none(self):
459 # bufsize=None should be the same as bufsize=0.
460 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
461 self.assertEqual(p.wait(), 0)
462 # Again with keyword arg
463 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
464 self.assertEqual(p.wait(), 0)
465
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466 #
467 # POSIX tests
468 #
469 if not mswindows:
470 def test_exceptions(self):
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000471 # caught & re-raised exceptions
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000472 try:
473 p = subprocess.Popen([sys.executable, "-c", ""],
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000474 cwd="/this/path/does/not/exist")
Guido van Rossumb940e112007-01-10 16:19:56 +0000475 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476 # The attribute child_traceback should contain "os.chdir"
477 # somewhere.
478 self.assertNotEqual(e.child_traceback.find("os.chdir"), -1)
479 else:
480 self.fail("Expected OSError")
Tim Peterse718f612004-10-12 21:51:32 +0000481
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000482 def _suppress_core_files(self):
483 """Try to prevent core files from being created.
484 Returns previous ulimit if successful, else None.
485 """
486 try:
487 import resource
488 old_limit = resource.getrlimit(resource.RLIMIT_CORE)
489 resource.setrlimit(resource.RLIMIT_CORE, (0,0))
490 return old_limit
491 except (ImportError, ValueError, resource.error):
492 return None
493
494 def _unsuppress_core_files(self, old_limit):
495 """Return core file behavior to default."""
496 if old_limit is None:
497 return
498 try:
499 import resource
500 resource.setrlimit(resource.RLIMIT_CORE, old_limit)
501 except (ImportError, ValueError, resource.error):
502 return
503
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504 def test_run_abort(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000505 # returncode handles signal termination
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506 old_limit = self._suppress_core_files()
507 try:
508 p = subprocess.Popen([sys.executable,
509 "-c", "import os; os.abort()"])
510 finally:
511 self._unsuppress_core_files(old_limit)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 p.wait()
513 self.assertEqual(-p.returncode, signal.SIGABRT)
514
515 def test_preexec(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000516 # preexec function
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 p = subprocess.Popen([sys.executable, "-c",
518 'import sys,os;' \
519 'sys.stdout.write(os.getenv("FRUIT"))'],
520 stdout=subprocess.PIPE,
521 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000522 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000524 def test_args_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000525 # args is a string
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526 f, fname = self.mkstemp()
527 os.write(f, "#!/bin/sh\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000528 os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" %
529 sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530 os.close(f)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000531 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532 p = subprocess.Popen(fname)
533 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534 os.remove(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000535 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000536
537 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000538 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000539 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000540 [sys.executable,
541 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542 startupinfo=47)
543 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000544 [sys.executable,
545 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546 creationflags=47)
547
548 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000549 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000550 newenv = os.environ.copy()
551 newenv["FRUIT"] = "apple"
552 p = subprocess.Popen(["echo $FRUIT"], shell=1,
553 stdout=subprocess.PIPE,
554 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000555 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556
557 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000558 # Run command through the shell (string)
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_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000567 # call() function with string argument on UNIX
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568 f, fname = self.mkstemp()
569 os.write(f, "#!/bin/sh\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000570 os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" %
571 sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000572 os.close(f)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000573 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000574 rc = subprocess.call(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000575 os.remove(fname)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000576 self.assertEqual(rc, 47)
577
Tim Peterse718f612004-10-12 21:51:32 +0000578
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000579 #
580 # Windows tests
581 #
582 if mswindows:
583 def test_startupinfo(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000584 # startupinfo argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000585 # We uses hardcoded constants, because we do not want to
Tim Peterse718f612004-10-12 21:51:32 +0000586 # depend on win32all.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000587 STARTF_USESHOWWINDOW = 1
588 SW_MAXIMIZE = 3
589 startupinfo = subprocess.STARTUPINFO()
590 startupinfo.dwFlags = STARTF_USESHOWWINDOW
591 startupinfo.wShowWindow = SW_MAXIMIZE
592 # Since Python is a console process, it won't be affected
593 # by wShowWindow, but the argument should be silently
594 # ignored
595 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
596 startupinfo=startupinfo)
597
598 def test_creationflags(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000599 # creationflags argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000600 CREATE_NEW_CONSOLE = 16
Tim Peters876c4322004-10-13 03:21:35 +0000601 sys.stderr.write(" a DOS box should flash briefly ...\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000602 subprocess.call(sys.executable +
Tim Peters876c4322004-10-13 03:21:35 +0000603 ' -c "import time; time.sleep(0.25)"',
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000604 creationflags=CREATE_NEW_CONSOLE)
605
606 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000607 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000608 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000609 [sys.executable,
610 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000611 preexec_fn=lambda: 1)
612 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000613 [sys.executable,
614 "-c", "import sys; sys.exit(47)"],
Guido van Rossume7ba4952007-06-06 23:52:48 +0000615 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616 close_fds=True)
617
Guido van Rossume7ba4952007-06-06 23:52:48 +0000618 def test_close_fds(self):
619 # close file descriptors
620 rc = subprocess.call([sys.executable, "-c",
621 "import sys; sys.exit(47)"],
622 close_fds=True)
623 self.assertEqual(rc, 47)
624
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000625 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000626 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000627 newenv = os.environ.copy()
628 newenv["FRUIT"] = "physalis"
629 p = subprocess.Popen(["set"], shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000630 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631 env=newenv)
632 self.assertNotEqual(p.stdout.read().find("physalis"), -1)
633
634 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000635 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000636 newenv = os.environ.copy()
637 newenv["FRUIT"] = "physalis"
638 p = subprocess.Popen("set", shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000639 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000640 env=newenv)
641 self.assertNotEqual(p.stdout.read().find("physalis"), -1)
642
643 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000644 # call() function with string argument on Windows
Tim Peters3b01a702004-10-12 22:19:32 +0000645 rc = subprocess.call(sys.executable +
646 ' -c "import sys; sys.exit(47)"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647 self.assertEqual(rc, 47)
648
649
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000650def test_main():
651 test_support.run_unittest(ProcessTestCase)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000652 if hasattr(test_support, "reap_children"):
653 test_support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000654
655if __name__ == "__main__":
656 test_main()