blob: ff9945b70eb779fbe3dde8c744824c64570ce711 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003import subprocess
4import sys
5import signal
6import os
Gregory P. Smith3fff44d2010-03-01 00:43:08 +00007import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008import tempfile
9import time
Tim Peters3761e8d2004-10-13 04:07:12 +000010import re
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011
12mswindows = (sys.platform == "win32")
13
14#
15# Depends on the following external programs: Python
16#
17
18if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000019 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
20 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000021else:
22 SETBINARY = ''
23
Tim Peters3761e8d2004-10-13 04:07:12 +000024# In a debug build, stuff like "[6580 refs]" is printed to stderr at
25# shutdown time. That frustrates tests trying to check stderr produced
26# from a spawned Python process.
27def remove_stderr_debug_decorations(stderr):
Guido van Rossum98297ee2007-11-06 21:34:58 +000028 return re.sub("\[\d+ refs\]\r?\n?$", "", stderr.decode()).encode()
29 #return re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr)
Tim Peters3761e8d2004-10-13 04:07:12 +000030
Benjamin Petersona0baf552010-08-08 19:17:15 +000031class ProcessTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000032 def setUp(self):
33 # Try to minimize the number of children we have so this test
34 # doesn't crash on some buildbots (Alphas in particular).
Benjamin Petersonee8712c2008-05-20 21:35:26 +000035 if hasattr(support, "reap_children"):
36 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000037
38 def tearDown(self):
39 # Try to minimize the number of children we have so this test
40 # doesn't crash on some buildbots (Alphas in particular).
Benjamin Petersonee8712c2008-05-20 21:35:26 +000041 if hasattr(support, "reap_children"):
42 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000043
Benjamin Petersona0baf552010-08-08 19:17:15 +000044 def mkstemp(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000045 """wrapper for mkstemp, calling mktemp if mkstemp is not available"""
46 if hasattr(tempfile, "mkstemp"):
Benjamin Petersona0baf552010-08-08 19:17:15 +000047 return tempfile.mkstemp()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000048 else:
Benjamin Petersona0baf552010-08-08 19:17:15 +000049 fname = tempfile.mktemp()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000050 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
Tim Peterse718f612004-10-12 21:51:32 +000051
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000052 #
53 # Generic tests
54 #
55 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000056 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000057 rc = subprocess.call([sys.executable, "-c",
58 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000059 self.assertEqual(rc, 47)
60
Peter Astrand454f7672005-01-01 09:36:35 +000061 def test_check_call_zero(self):
62 # check_call() function with zero return code
63 rc = subprocess.check_call([sys.executable, "-c",
64 "import sys; sys.exit(0)"])
65 self.assertEqual(rc, 0)
66
67 def test_check_call_nonzero(self):
68 # check_call() function with non-zero return code
69 try:
70 subprocess.check_call([sys.executable, "-c",
71 "import sys; sys.exit(47)"])
Guido van Rossumb940e112007-01-10 16:19:56 +000072 except subprocess.CalledProcessError as e:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073 self.assertEqual(e.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000074 else:
75 self.fail("Expected CalledProcessError")
76
Georg Brandlf9734072008-12-07 15:30:06 +000077 def test_check_output(self):
78 # check_output() function with zero return code
79 output = subprocess.check_output(
80 [sys.executable, "-c", "print('BDFL')"])
81 self.assertTrue(b'BDFL' in output)
82
83 def test_check_output_nonzero(self):
84 # check_call() function with non-zero return code
85 try:
86 subprocess.check_output(
87 [sys.executable, "-c", "import sys; sys.exit(5)"])
88 except subprocess.CalledProcessError as e:
89 self.assertEqual(e.returncode, 5)
90 else:
91 self.fail("Expected CalledProcessError")
92
93 def test_check_output_stderr(self):
94 # check_output() function stderr redirected to stdout
95 output = subprocess.check_output(
96 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
97 stderr=subprocess.STDOUT)
98 self.assertTrue(b'BDFL' in output)
99
100 def test_check_output_stdout_arg(self):
101 # check_output() function stderr redirected to stdout
102 try:
103 output = subprocess.check_output(
104 [sys.executable, "-c", "print('will not be run')"],
105 stdout=sys.stdout)
106 except ValueError as e:
107 self.assertTrue('stdout' in e.args[0])
108 else:
109 self.fail("Expected ValueError when stdout arg supplied.")
110
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000111 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000112 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000113 newenv = os.environ.copy()
114 newenv["FRUIT"] = "banana"
115 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000116 'import sys, os;'
117 'sys.exit(os.getenv("FRUIT")=="banana")'],
118 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000119 self.assertEqual(rc, 1)
120
121 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000122 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000123 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000124 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
125 p.wait()
126 self.assertEqual(p.stdin, None)
127
128 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000129 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000130 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000131 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000132 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000133 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000134 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000135 p.wait()
136 self.assertEqual(p.stdout, None)
137
138 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000139 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000140 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000141 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
142 p.wait()
143 self.assertEqual(p.stderr, None)
144
145 def test_executable(self):
Antoine Pitrou55503652009-03-29 19:30:55 +0000146 arg0 = os.path.join(os.path.dirname(sys.executable),
147 "somethingyoudonthave")
148 p = subprocess.Popen([arg0, "-c", "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000149 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000150 p.wait()
151 self.assertEqual(p.returncode, 47)
152
153 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000154 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000155 p = subprocess.Popen([sys.executable, "-c",
156 'import sys; sys.exit(sys.stdin.read() == "pear")'],
157 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000158 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000159 p.stdin.close()
160 p.wait()
161 self.assertEqual(p.returncode, 1)
162
163 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000164 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000165 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000166 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000167 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000168 os.lseek(d, 0, 0)
169 p = subprocess.Popen([sys.executable, "-c",
170 'import sys; sys.exit(sys.stdin.read() == "pear")'],
171 stdin=d)
172 p.wait()
173 self.assertEqual(p.returncode, 1)
174
175 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000176 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000177 tf = tempfile.TemporaryFile()
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000178 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000179 tf.seek(0)
180 p = subprocess.Popen([sys.executable, "-c",
181 'import sys; sys.exit(sys.stdin.read() == "pear")'],
182 stdin=tf)
183 p.wait()
184 self.assertEqual(p.returncode, 1)
185
186 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000187 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000188 p = subprocess.Popen([sys.executable, "-c",
189 'import sys; sys.stdout.write("orange")'],
190 stdout=subprocess.PIPE)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000191 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000192
193 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000194 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000195 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000196 d = tf.fileno()
197 p = subprocess.Popen([sys.executable, "-c",
198 'import sys; sys.stdout.write("orange")'],
199 stdout=d)
200 p.wait()
201 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000202 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000203
204 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000205 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000206 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000207 p = subprocess.Popen([sys.executable, "-c",
208 'import sys; sys.stdout.write("orange")'],
209 stdout=tf)
210 p.wait()
211 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000212 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000213
214 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000215 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000216 p = subprocess.Popen([sys.executable, "-c",
217 'import sys; sys.stderr.write("strawberry")'],
218 stderr=subprocess.PIPE)
Tim Peters3761e8d2004-10-13 04:07:12 +0000219 self.assertEqual(remove_stderr_debug_decorations(p.stderr.read()),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000220 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000221
222 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000223 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000224 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000225 d = tf.fileno()
226 p = subprocess.Popen([sys.executable, "-c",
227 'import sys; sys.stderr.write("strawberry")'],
228 stderr=d)
229 p.wait()
230 os.lseek(d, 0, 0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000231 self.assertEqual(remove_stderr_debug_decorations(os.read(d, 1024)),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000232 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233
234 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000235 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000236 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000237 p = subprocess.Popen([sys.executable, "-c",
238 'import sys; sys.stderr.write("strawberry")'],
239 stderr=tf)
240 p.wait()
241 tf.seek(0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000242 self.assertEqual(remove_stderr_debug_decorations(tf.read()),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000243 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244
245 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000246 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000248 'import sys;'
249 'sys.stdout.write("apple");'
250 'sys.stdout.flush();'
251 'sys.stderr.write("orange")'],
252 stdout=subprocess.PIPE,
253 stderr=subprocess.STDOUT)
Tim Peters3761e8d2004-10-13 04:07:12 +0000254 output = p.stdout.read()
255 stripped = remove_stderr_debug_decorations(output)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000256 self.assertEqual(stripped, b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000257
258 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000259 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000260 tf = tempfile.TemporaryFile()
261 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000262 'import sys;'
263 'sys.stdout.write("apple");'
264 'sys.stdout.flush();'
265 'sys.stderr.write("orange")'],
266 stdout=tf,
267 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268 p.wait()
269 tf.seek(0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000270 output = tf.read()
271 stripped = remove_stderr_debug_decorations(output)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000272 self.assertEqual(stripped, b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000273
Thomas Wouters89f507f2006-12-13 04:49:30 +0000274 def test_stdout_filedes_of_stdout(self):
275 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000276 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000277 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
278 self.assertEquals(rc, 2)
279
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000280 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000281 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000282 # We cannot use os.path.realpath to canonicalize the path,
283 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
284 cwd = os.getcwd()
285 os.chdir(tmpdir)
286 tmpdir = os.getcwd()
287 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000288 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000289 'import sys,os;'
290 'sys.stdout.write(os.getcwd())'],
291 stdout=subprocess.PIPE,
292 cwd=tmpdir)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000293 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000294 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
295 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296
297 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298 newenv = os.environ.copy()
299 newenv["FRUIT"] = "orange"
300 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000301 'import sys,os;'
302 'sys.stdout.write(os.getenv("FRUIT"))'],
303 stdout=subprocess.PIPE,
304 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000305 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306
Peter Astrandcbac93c2005-03-03 20:24:28 +0000307 def test_communicate_stdin(self):
308 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000309 'import sys;'
310 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000311 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000312 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000313 self.assertEqual(p.returncode, 1)
314
315 def test_communicate_stdout(self):
316 p = subprocess.Popen([sys.executable, "-c",
317 'import sys; sys.stdout.write("pineapple")'],
318 stdout=subprocess.PIPE)
319 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000320 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000321 self.assertEqual(stderr, None)
322
323 def test_communicate_stderr(self):
324 p = subprocess.Popen([sys.executable, "-c",
325 'import sys; sys.stderr.write("pineapple")'],
326 stderr=subprocess.PIPE)
327 (stdout, stderr) = p.communicate()
328 self.assertEqual(stdout, None)
Brett Cannon653a5ad2005-03-05 06:40:52 +0000329 # When running with a pydebug build, the # of references is outputted
330 # to stderr, so just check if stderr at least started with "pinapple"
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000331 self.assertEqual(remove_stderr_debug_decorations(stderr), b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000332
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000333 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000335 'import sys,os;'
336 'sys.stderr.write("pineapple");'
337 'sys.stdout.write(sys.stdin.read())'],
338 stdin=subprocess.PIPE,
339 stdout=subprocess.PIPE,
340 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000341 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000342 self.assertEqual(stdout, b"banana")
Tim Peters3761e8d2004-10-13 04:07:12 +0000343 self.assertEqual(remove_stderr_debug_decorations(stderr),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000344 b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000345
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000346 # This test is Linux specific for simplicity to at least have
347 # some coverage. It is not a platform specific bug.
348 if os.path.isdir('/proc/%d/fd' % os.getpid()):
349 # Test for the fd leak reported in http://bugs.python.org/issue2791.
350 def test_communicate_pipe_fd_leak(self):
351 fd_directory = '/proc/%d/fd' % os.getpid()
352 num_fds_before_popen = len(os.listdir(fd_directory))
353 p = subprocess.Popen([sys.executable, '-c', 'print()'],
354 stdout=subprocess.PIPE)
355 p.communicate()
356 num_fds_after_communicate = len(os.listdir(fd_directory))
357 del p
358 num_fds_after_destruction = len(os.listdir(fd_directory))
359 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
360 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
361
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000363 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000364 p = subprocess.Popen([sys.executable, "-c",
365 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000366 (stdout, stderr) = p.communicate()
367 self.assertEqual(stdout, None)
368 self.assertEqual(stderr, None)
369
370 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000371 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000372 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000373 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000374 x, y = os.pipe()
375 if mswindows:
376 pipe_buf = 512
377 else:
378 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
379 os.close(x)
380 os.close(y)
381 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000382 'import sys,os;'
383 'sys.stdout.write(sys.stdin.read(47));'
384 'sys.stderr.write("xyz"*%d);'
385 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
386 stdin=subprocess.PIPE,
387 stdout=subprocess.PIPE,
388 stderr=subprocess.PIPE)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000389 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390 (stdout, stderr) = p.communicate(string_to_write)
391 self.assertEqual(stdout, string_to_write)
392
393 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000394 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000395 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000396 'import sys,os;'
397 'sys.stdout.write(sys.stdin.read())'],
398 stdin=subprocess.PIPE,
399 stdout=subprocess.PIPE,
400 stderr=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000401 p.stdin.write(b"banana")
402 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000403 self.assertEqual(stdout, b"bananasplit")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000404 self.assertEqual(remove_stderr_debug_decorations(stderr), b"")
Tim Peterse718f612004-10-12 21:51:32 +0000405
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000406 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000407 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000408 'import sys,os;' + SETBINARY +
409 'sys.stdout.write("line1\\n");'
410 'sys.stdout.flush();'
411 'sys.stdout.write("line2\\n");'
412 'sys.stdout.flush();'
413 'sys.stdout.write("line3\\r\\n");'
414 'sys.stdout.flush();'
415 'sys.stdout.write("line4\\r");'
416 'sys.stdout.flush();'
417 'sys.stdout.write("\\nline5");'
418 'sys.stdout.flush();'
419 'sys.stdout.write("\\nline6");'],
420 stdout=subprocess.PIPE,
421 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000422 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000423 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424
425 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000426 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000427 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000428 'import sys,os;' + SETBINARY +
429 'sys.stdout.write("line1\\n");'
430 'sys.stdout.flush();'
431 'sys.stdout.write("line2\\n");'
432 'sys.stdout.flush();'
433 'sys.stdout.write("line3\\r\\n");'
434 'sys.stdout.flush();'
435 'sys.stdout.write("line4\\r");'
436 'sys.stdout.flush();'
437 'sys.stdout.write("\\nline5");'
438 'sys.stdout.flush();'
439 'sys.stdout.write("\\nline6");'],
440 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
441 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000442 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000443 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444
445 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000446 # Make sure we leak no resources
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000447 if (not hasattr(support, "is_resource_enabled") or
448 support.is_resource_enabled("subprocess") and not mswindows):
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000449 max_handles = 1026 # too much for most UNIX systems
450 else:
Tim Peterseba28be2005-03-28 01:08:02 +0000451 max_handles = 65
Fredrik Lundh9e29fc52004-10-13 07:54:54 +0000452 for i in range(max_handles):
Tim Peters3b01a702004-10-12 22:19:32 +0000453 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000454 "import sys;"
455 "sys.stdout.write(sys.stdin.read())"],
456 stdin=subprocess.PIPE,
457 stdout=subprocess.PIPE,
458 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000459 data = p.communicate(b"lime")[0]
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000460 self.assertEqual(data, b"lime")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000461
462
463 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
465 '"a b c" d e')
466 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
467 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000468 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
469 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
471 'a\\\\\\b "de fg" h')
472 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
473 'a\\\\\\"b c d')
474 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
475 '"a\\\\b c" d e')
476 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
477 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000478 self.assertEqual(subprocess.list2cmdline(['ab', '']),
479 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000480
481
482 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000484 "-c", "import time; time.sleep(1)"])
485 count = 0
486 while p.poll() is None:
487 time.sleep(0.1)
488 count += 1
489 # We expect that the poll loop probably went around about 10 times,
490 # but, based on system scheduling we can't control, it's possible
491 # poll() never returned None. It "should be" very rare that it
492 # didn't go around at least twice.
Georg Brandlab91fde2009-08-13 08:51:18 +0000493 self.assertTrue(count >= 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 # Subsequent invocations should just return the returncode
495 self.assertEqual(p.poll(), 0)
496
497
498 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000499 p = subprocess.Popen([sys.executable,
500 "-c", "import time; time.sleep(2)"])
501 self.assertEqual(p.wait(), 0)
502 # Subsequent invocations should just return the returncode
503 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000504
Peter Astrand738131d2004-11-30 21:04:45 +0000505
506 def test_invalid_bufsize(self):
507 # an invalid type of the bufsize argument should raise
508 # TypeError.
509 try:
510 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
511 except TypeError:
512 pass
513 else:
514 self.fail("Expected TypeError")
515
Guido van Rossum46a05a72007-06-07 21:56:45 +0000516 def test_bufsize_is_none(self):
517 # bufsize=None should be the same as bufsize=0.
518 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
519 self.assertEqual(p.wait(), 0)
520 # Again with keyword arg
521 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
522 self.assertEqual(p.wait(), 0)
523
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000524 def test_leaking_fds_on_error(self):
525 # see bug #5179: Popen leaks file descriptors to PIPEs if
526 # the child fails to execute; this will eventually exhaust
527 # the maximum number of open fds. 1024 seems a very common
528 # value for that limit, but Windows has 2048, so we loop
529 # 1024 times (each call leaked two fds).
530 for i in range(1024):
531 try:
532 subprocess.Popen(['nonexisting_i_hope'],
533 stdout=subprocess.PIPE,
534 stderr=subprocess.PIPE)
535 # Windows raises IOError
536 except (IOError, OSError) as err:
537 if err.errno != 2: # ignore "no such file"
Benjamin Peterson4b068192009-02-20 03:19:25 +0000538 raise
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000539
Victor Stinner86c73bf2010-05-21 20:39:17 +0000540 def test_issue8780(self):
541 # Ensure that stdout is inherited from the parent
542 # if stdout=PIPE is not used
543 code = ';'.join((
544 'import subprocess, sys',
545 'retcode = subprocess.call('
546 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
547 'assert retcode == 0'))
548 output = subprocess.check_output([sys.executable, '-c', code])
549 self.assert_(output.startswith(b'Hello World!'), ascii(output))
550
Tim Golden40b37442010-08-06 13:20:12 +0000551 def test_handles_closed_on_exception(self):
552 # If CreateProcess exits with an error, ensure the
553 # duplicate output handles are released
554 ifhandle, ifname = self.mkstemp()
555 ofhandle, ofname = self.mkstemp()
556 efhandle, efname = self.mkstemp()
557 try:
558 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
559 stderr=efhandle)
560 except OSError:
561 os.close(ifhandle)
562 os.remove(ifname)
563 os.close(ofhandle)
564 os.remove(ofname)
565 os.close(efhandle)
566 os.remove(efname)
567 self.assertFalse(os.path.exists(ifname))
568 self.assertFalse(os.path.exists(ofname))
569 self.assertFalse(os.path.exists(efname))
570
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000571 #
572 # POSIX tests
573 #
574 if not mswindows:
575 def test_exceptions(self):
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000576 # caught & re-raised exceptions
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000577 try:
578 p = subprocess.Popen([sys.executable, "-c", ""],
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000579 cwd="/this/path/does/not/exist")
Guido van Rossumb940e112007-01-10 16:19:56 +0000580 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000581 # The attribute child_traceback should contain "os.chdir"
582 # somewhere.
583 self.assertNotEqual(e.child_traceback.find("os.chdir"), -1)
584 else:
585 self.fail("Expected OSError")
Tim Peterse718f612004-10-12 21:51:32 +0000586
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000587 def _suppress_core_files(self):
588 """Try to prevent core files from being created.
589 Returns previous ulimit if successful, else None.
590 """
Ronald Oussorend7eb3a82010-07-23 10:35:20 +0000591 if sys.platform == 'darwin':
592 # Check if the 'Crash Reporter' on OSX was configured
593 # in 'Developer' mode and warn that it will get triggered
594 # when it is.
595 #
596 # This assumes that this context manager is used in tests
597 # that might trigger the next manager.
598 value = subprocess.Popen(['/usr/bin/defaults', 'read',
599 'com.apple.CrashReporter', 'DialogType'],
600 stdout=subprocess.PIPE).communicate()[0]
601 if value.strip() == b'developer':
602 print("this tests triggers the Crash Reporter, "
603 "that is intentional", end='')
604 sys.stdout.flush()
605
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000606 try:
607 import resource
608 old_limit = resource.getrlimit(resource.RLIMIT_CORE)
609 resource.setrlimit(resource.RLIMIT_CORE, (0,0))
610 return old_limit
611 except (ImportError, ValueError, resource.error):
612 return None
613
Ronald Oussorend7eb3a82010-07-23 10:35:20 +0000614
615
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000616 def _unsuppress_core_files(self, old_limit):
617 """Return core file behavior to default."""
618 if old_limit is None:
619 return
620 try:
621 import resource
622 resource.setrlimit(resource.RLIMIT_CORE, old_limit)
623 except (ImportError, ValueError, resource.error):
624 return
625
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000626 def test_run_abort(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000627 # returncode handles signal termination
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000628 old_limit = self._suppress_core_files()
629 try:
630 p = subprocess.Popen([sys.executable,
631 "-c", "import os; os.abort()"])
632 finally:
633 self._unsuppress_core_files(old_limit)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000634 p.wait()
635 self.assertEqual(-p.returncode, signal.SIGABRT)
636
637 def test_preexec(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000638 # preexec function
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000639 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000640 'import sys,os;'
641 'sys.stdout.write(os.getenv("FRUIT"))'],
642 stdout=subprocess.PIPE,
643 preexec_fn=lambda: os.putenv("FRUIT",
644 "apple"))
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000645 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647 def test_args_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000648 # args is a string
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000649 fd, fname = self.mkstemp()
650 # reopen in text mode
651 with open(fd, "w") as fobj:
652 fobj.write("#!/bin/sh\n")
653 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
654 sys.executable)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000655 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000656 p = subprocess.Popen(fname)
657 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000658 os.remove(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000659 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000660
661 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000662 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000664 [sys.executable,
665 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000666 startupinfo=47)
667 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000668 [sys.executable,
669 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000670 creationflags=47)
671
672 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000673 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000674 newenv = os.environ.copy()
675 newenv["FRUIT"] = "apple"
676 p = subprocess.Popen(["echo $FRUIT"], shell=1,
677 stdout=subprocess.PIPE,
678 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000679 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000680
681 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000682 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000683 newenv = os.environ.copy()
684 newenv["FRUIT"] = "apple"
685 p = subprocess.Popen("echo $FRUIT", shell=1,
686 stdout=subprocess.PIPE,
687 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000688 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000689
690 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000691 # call() function with string argument on UNIX
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000692 fd, fname = self.mkstemp()
693 # reopen in text mode
694 with open(fd, "w") as fobj:
695 fobj.write("#!/bin/sh\n")
696 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
697 sys.executable)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000698 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000699 rc = subprocess.call(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000700 os.remove(fname)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000701 self.assertEqual(rc, 47)
702
Stefan Krah8db99c82010-07-19 14:39:36 +0000703 def test_specific_shell(self):
704 # Issue #9265: Incorrect name passed as arg[0].
705 shells = []
706 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
707 for name in ['bash', 'ksh']:
708 sh = os.path.join(prefix, name)
709 if os.path.isfile(sh):
710 shells.append(sh)
711 if not shells: # Will probably work for any shell but csh.
712 self.skipTest("bash or ksh required for this test")
713 sh = '/bin/sh'
714 if os.path.isfile(sh) and not os.path.islink(sh):
715 # Test will fail if /bin/sh is a symlink to csh.
716 shells.append(sh)
717 for sh in shells:
718 p = subprocess.Popen("echo $0", executable=sh, shell=True,
719 stdout=subprocess.PIPE)
720 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
721
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000722 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000723 p = subprocess.Popen([sys.executable,
724 "-c", "input()"])
725
Georg Brandlab91fde2009-08-13 08:51:18 +0000726 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000727 p.send_signal(signal.SIGINT)
728 self.assertNotEqual(p.wait(), 0)
729
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000730 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000731 p = subprocess.Popen([sys.executable,
732 "-c", "input()"])
733
Georg Brandlab91fde2009-08-13 08:51:18 +0000734 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000735 p.kill()
736 self.assertEqual(p.wait(), -signal.SIGKILL)
737
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000738 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000739 p = subprocess.Popen([sys.executable,
740 "-c", "input()"])
741
Georg Brandlab91fde2009-08-13 08:51:18 +0000742 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000743 p.terminate()
744 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000745
Victor Stinner097d1b72010-04-27 18:29:45 +0000746 def test_undecodable_env(self):
747 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
748 value_repr = repr(value).encode("ascii")
749
750 # test str with surrogates
751 script = "import os; print(repr(os.getenv(%s)))" % repr(key)
752 env = os.environ.copy()
753 env[key] = value
754 stdout = subprocess.check_output(
755 [sys.executable, "-c", script],
756 env=env)
757 stdout = stdout.rstrip(b'\n\r')
758 self.assertEquals(stdout, value_repr)
759
760 # test bytes
761 key = key.encode("ascii", "surrogateescape")
762 value = value.encode("ascii", "surrogateescape")
763 script = "import os; print(repr(os.getenv(%s)))" % repr(key)
764 env = os.environ.copy()
765 env[key] = value
766 stdout = subprocess.check_output(
767 [sys.executable, "-c", script],
768 env=env)
769 stdout = stdout.rstrip(b'\n\r')
770 self.assertEquals(stdout, value_repr)
771
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772 #
773 # Windows tests
774 #
775 if mswindows:
776 def test_startupinfo(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000777 # startupinfo argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000778 # We uses hardcoded constants, because we do not want to
Tim Peterse718f612004-10-12 21:51:32 +0000779 # depend on win32all.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000780 STARTF_USESHOWWINDOW = 1
781 SW_MAXIMIZE = 3
782 startupinfo = subprocess.STARTUPINFO()
783 startupinfo.dwFlags = STARTF_USESHOWWINDOW
784 startupinfo.wShowWindow = SW_MAXIMIZE
785 # Since Python is a console process, it won't be affected
786 # by wShowWindow, but the argument should be silently
787 # ignored
788 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
789 startupinfo=startupinfo)
790
791 def test_creationflags(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000792 # creationflags argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000793 CREATE_NEW_CONSOLE = 16
Tim Peters876c4322004-10-13 03:21:35 +0000794 sys.stderr.write(" a DOS box should flash briefly ...\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000795 subprocess.call(sys.executable +
Tim Peters876c4322004-10-13 03:21:35 +0000796 ' -c "import time; time.sleep(0.25)"',
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000797 creationflags=CREATE_NEW_CONSOLE)
798
799 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000800 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000801 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000802 [sys.executable,
803 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000804 preexec_fn=lambda: 1)
805 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000806 [sys.executable,
807 "-c", "import sys; sys.exit(47)"],
Guido van Rossume7ba4952007-06-06 23:52:48 +0000808 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000809 close_fds=True)
810
Guido van Rossume7ba4952007-06-06 23:52:48 +0000811 def test_close_fds(self):
812 # close file descriptors
813 rc = subprocess.call([sys.executable, "-c",
814 "import sys; sys.exit(47)"],
815 close_fds=True)
816 self.assertEqual(rc, 47)
817
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000818 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000819 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000820 newenv = os.environ.copy()
821 newenv["FRUIT"] = "physalis"
822 p = subprocess.Popen(["set"], shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000823 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000824 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000825 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000826
827 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000828 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000829 newenv = os.environ.copy()
830 newenv["FRUIT"] = "physalis"
831 p = subprocess.Popen("set", shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000832 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000833 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000834 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000835
836 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000837 # call() function with string argument on Windows
Tim Peters3b01a702004-10-12 22:19:32 +0000838 rc = subprocess.call(sys.executable +
839 ' -c "import sys; sys.exit(47)"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000840 self.assertEqual(rc, 47)
841
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000842 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000843 p = subprocess.Popen([sys.executable,
844 "-c", "input()"])
845
Georg Brandlab91fde2009-08-13 08:51:18 +0000846 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000847 p.send_signal(signal.SIGTERM)
848 self.assertNotEqual(p.wait(), 0)
849
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000850 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000851 p = subprocess.Popen([sys.executable,
852 "-c", "input()"])
853
Georg Brandlab91fde2009-08-13 08:51:18 +0000854 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000855 p.kill()
856 self.assertNotEqual(p.wait(), 0)
857
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000858 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000859 p = subprocess.Popen([sys.executable,
860 "-c", "input()"])
861
Georg Brandlab91fde2009-08-13 08:51:18 +0000862 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000863 p.terminate()
864 self.assertNotEqual(p.wait(), 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000865
Brett Cannona23810f2008-05-26 19:04:21 +0000866class CommandTests(unittest.TestCase):
867# The module says:
868# "NB This only works (and is only relevant) for UNIX."
869#
870# Actually, getoutput should work on any platform with an os.popen, but
871# I'll take the comment as given, and skip this suite.
872 if os.name == 'posix':
873
874 def test_getoutput(self):
875 self.assertEquals(subprocess.getoutput('echo xyzzy'), 'xyzzy')
876 self.assertEquals(subprocess.getstatusoutput('echo xyzzy'),
877 (0, 'xyzzy'))
878
879 # we use mkdtemp in the next line to create an empty directory
880 # under our exclusive control; from that, we can invent a pathname
881 # that we _know_ won't exist. This is guaranteed to fail.
882 dir = None
883 try:
884 dir = tempfile.mkdtemp()
885 name = os.path.join(dir, "foo")
886
887 status, output = subprocess.getstatusoutput('cat ' + name)
888 self.assertNotEquals(status, 0)
889 finally:
890 if dir is not None:
891 os.rmdir(dir)
892
Georg Brandlae83d6e2009-08-13 09:04:31 +0000893
894unit_tests = [ProcessTestCase, CommandTests]
895
Gregory P. Smith10d29522009-08-13 18:33:30 +0000896if getattr(subprocess, '_has_poll', False):
Georg Brandlae83d6e2009-08-13 09:04:31 +0000897 class ProcessTestCaseNoPoll(ProcessTestCase):
898 def setUp(self):
899 subprocess._has_poll = False
900 ProcessTestCase.setUp(self)
901
902 def tearDown(self):
903 subprocess._has_poll = True
904 ProcessTestCase.tearDown(self)
905
906 unit_tests.append(ProcessTestCaseNoPoll)
907
908
Gregory P. Smith3fff44d2010-03-01 00:43:08 +0000909class HelperFunctionTests(unittest.TestCase):
Gregory P. Smith5cab2812010-03-01 02:58:43 +0000910 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smith3fff44d2010-03-01 00:43:08 +0000911 def test_eintr_retry_call(self):
912 record_calls = []
913 def fake_os_func(*args):
914 record_calls.append(args)
915 if len(record_calls) == 2:
916 raise OSError(errno.EINTR, "fake interrupted system call")
917 return tuple(reversed(args))
918
919 self.assertEqual((999, 256),
920 subprocess._eintr_retry_call(fake_os_func, 256, 999))
921 self.assertEqual([(256, 999)], record_calls)
922 # This time there will be an EINTR so it will loop once.
923 self.assertEqual((666,),
924 subprocess._eintr_retry_call(fake_os_func, 666))
925 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
926
927unit_tests.append(HelperFunctionTests)
928
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000929def test_main():
Georg Brandlae83d6e2009-08-13 09:04:31 +0000930 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +0000931 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000932
933if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +0000934 test_main()