blob: 20b72e69ce76c82ca774880b7757a316f8169654 [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
Gregory P. Smith81ce6852011-03-15 02:04:11 -040011import shutil
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000012
13mswindows = (sys.platform == "win32")
14
15#
16# Depends on the following external programs: Python
17#
18
19if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000020 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
21 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000022else:
23 SETBINARY = ''
24
Tim Peters3761e8d2004-10-13 04:07:12 +000025# In a debug build, stuff like "[6580 refs]" is printed to stderr at
26# shutdown time. That frustrates tests trying to check stderr produced
27# from a spawned Python process.
28def remove_stderr_debug_decorations(stderr):
Guido van Rossum98297ee2007-11-06 21:34:58 +000029 return re.sub("\[\d+ refs\]\r?\n?$", "", stderr.decode()).encode()
30 #return re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr)
Tim Peters3761e8d2004-10-13 04:07:12 +000031
Tim Golden595c8d32010-08-12 09:45:25 +000032class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000033 def setUp(self):
34 # Try to minimize the number of children we have so this test
35 # doesn't crash on some buildbots (Alphas in particular).
Benjamin Petersonee8712c2008-05-20 21:35:26 +000036 if hasattr(support, "reap_children"):
37 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000038
39 def tearDown(self):
40 # Try to minimize the number of children we have so this test
41 # doesn't crash on some buildbots (Alphas in particular).
Benjamin Petersonee8712c2008-05-20 21:35:26 +000042 if hasattr(support, "reap_children"):
43 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000044
Tim Golden595c8d32010-08-12 09:45:25 +000045 def mkstemp(self, *args, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000046 """wrapper for mkstemp, calling mktemp if mkstemp is not available"""
47 if hasattr(tempfile, "mkstemp"):
Tim Golden595c8d32010-08-12 09:45:25 +000048 return tempfile.mkstemp(*args, **kwargs)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000049 else:
Tim Golden595c8d32010-08-12 09:45:25 +000050 fname = tempfile.mktemp(*args, **kwargs)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000051 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
Tim Peterse718f612004-10-12 21:51:32 +000052
Tim Golden595c8d32010-08-12 09:45:25 +000053class ProcessTestCase(BaseTestCase):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000054 #
55 # Generic tests
56 #
57 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000058 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000059 rc = subprocess.call([sys.executable, "-c",
60 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000061 self.assertEqual(rc, 47)
62
Peter Astrand454f7672005-01-01 09:36:35 +000063 def test_check_call_zero(self):
64 # check_call() function with zero return code
65 rc = subprocess.check_call([sys.executable, "-c",
66 "import sys; sys.exit(0)"])
67 self.assertEqual(rc, 0)
68
69 def test_check_call_nonzero(self):
70 # check_call() function with non-zero return code
71 try:
72 subprocess.check_call([sys.executable, "-c",
73 "import sys; sys.exit(47)"])
Guido van Rossumb940e112007-01-10 16:19:56 +000074 except subprocess.CalledProcessError as e:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075 self.assertEqual(e.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000076 else:
77 self.fail("Expected CalledProcessError")
78
Georg Brandlf9734072008-12-07 15:30:06 +000079 def test_check_output(self):
80 # check_output() function with zero return code
81 output = subprocess.check_output(
82 [sys.executable, "-c", "print('BDFL')"])
83 self.assertTrue(b'BDFL' in output)
84
85 def test_check_output_nonzero(self):
86 # check_call() function with non-zero return code
87 try:
88 subprocess.check_output(
89 [sys.executable, "-c", "import sys; sys.exit(5)"])
90 except subprocess.CalledProcessError as e:
91 self.assertEqual(e.returncode, 5)
92 else:
93 self.fail("Expected CalledProcessError")
94
95 def test_check_output_stderr(self):
96 # check_output() function stderr redirected to stdout
97 output = subprocess.check_output(
98 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
99 stderr=subprocess.STDOUT)
100 self.assertTrue(b'BDFL' in output)
101
102 def test_check_output_stdout_arg(self):
103 # check_output() function stderr redirected to stdout
104 try:
105 output = subprocess.check_output(
106 [sys.executable, "-c", "print('will not be run')"],
107 stdout=sys.stdout)
108 except ValueError as e:
109 self.assertTrue('stdout' in e.args[0])
110 else:
111 self.fail("Expected ValueError when stdout arg supplied.")
112
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000113 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000114 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000115 newenv = os.environ.copy()
116 newenv["FRUIT"] = "banana"
117 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000118 'import sys, os;'
119 'sys.exit(os.getenv("FRUIT")=="banana")'],
120 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000121 self.assertEqual(rc, 1)
122
123 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000124 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000125 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000126 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
127 p.wait()
128 self.assertEqual(p.stdin, None)
129
130 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000131 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000132 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000133 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000134 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000135 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000136 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000137 p.wait()
138 self.assertEqual(p.stdout, None)
139
140 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000141 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000142 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000143 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
144 p.wait()
145 self.assertEqual(p.stderr, None)
146
147 def test_executable(self):
Antoine Pitrou55503652009-03-29 19:30:55 +0000148 arg0 = os.path.join(os.path.dirname(sys.executable),
149 "somethingyoudonthave")
150 p = subprocess.Popen([arg0, "-c", "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000151 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000152 p.wait()
153 self.assertEqual(p.returncode, 47)
154
155 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000156 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000157 p = subprocess.Popen([sys.executable, "-c",
158 'import sys; sys.exit(sys.stdin.read() == "pear")'],
159 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000160 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000161 p.stdin.close()
162 p.wait()
163 self.assertEqual(p.returncode, 1)
164
165 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000166 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000167 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000168 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000169 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000170 os.lseek(d, 0, 0)
171 p = subprocess.Popen([sys.executable, "-c",
172 'import sys; sys.exit(sys.stdin.read() == "pear")'],
173 stdin=d)
174 p.wait()
175 self.assertEqual(p.returncode, 1)
176
177 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000178 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000179 tf = tempfile.TemporaryFile()
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000180 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000181 tf.seek(0)
182 p = subprocess.Popen([sys.executable, "-c",
183 'import sys; sys.exit(sys.stdin.read() == "pear")'],
184 stdin=tf)
185 p.wait()
186 self.assertEqual(p.returncode, 1)
187
188 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000189 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000190 p = subprocess.Popen([sys.executable, "-c",
191 'import sys; sys.stdout.write("orange")'],
192 stdout=subprocess.PIPE)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000193 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000194
195 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000196 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000197 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000198 d = tf.fileno()
199 p = subprocess.Popen([sys.executable, "-c",
200 'import sys; sys.stdout.write("orange")'],
201 stdout=d)
202 p.wait()
203 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000204 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000205
206 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000207 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000208 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000209 p = subprocess.Popen([sys.executable, "-c",
210 'import sys; sys.stdout.write("orange")'],
211 stdout=tf)
212 p.wait()
213 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000214 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000215
216 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000217 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000218 p = subprocess.Popen([sys.executable, "-c",
219 'import sys; sys.stderr.write("strawberry")'],
220 stderr=subprocess.PIPE)
Tim Peters3761e8d2004-10-13 04:07:12 +0000221 self.assertEqual(remove_stderr_debug_decorations(p.stderr.read()),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000222 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223
224 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000225 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000226 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 d = tf.fileno()
228 p = subprocess.Popen([sys.executable, "-c",
229 'import sys; sys.stderr.write("strawberry")'],
230 stderr=d)
231 p.wait()
232 os.lseek(d, 0, 0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000233 self.assertEqual(remove_stderr_debug_decorations(os.read(d, 1024)),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000234 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000235
236 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000237 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000238 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239 p = subprocess.Popen([sys.executable, "-c",
240 'import sys; sys.stderr.write("strawberry")'],
241 stderr=tf)
242 p.wait()
243 tf.seek(0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000244 self.assertEqual(remove_stderr_debug_decorations(tf.read()),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000245 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000246
247 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000248 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000249 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000250 'import sys;'
251 'sys.stdout.write("apple");'
252 'sys.stdout.flush();'
253 'sys.stderr.write("orange")'],
254 stdout=subprocess.PIPE,
255 stderr=subprocess.STDOUT)
Tim Peters3761e8d2004-10-13 04:07:12 +0000256 output = p.stdout.read()
257 stripped = remove_stderr_debug_decorations(output)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000258 self.assertEqual(stripped, b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000259
260 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000261 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262 tf = tempfile.TemporaryFile()
263 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000264 'import sys;'
265 'sys.stdout.write("apple");'
266 'sys.stdout.flush();'
267 'sys.stderr.write("orange")'],
268 stdout=tf,
269 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270 p.wait()
271 tf.seek(0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000272 output = tf.read()
273 stripped = remove_stderr_debug_decorations(output)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000274 self.assertEqual(stripped, b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000275
Thomas Wouters89f507f2006-12-13 04:49:30 +0000276 def test_stdout_filedes_of_stdout(self):
277 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000278 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000279 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000280 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000281
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000283 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000284 # We cannot use os.path.realpath to canonicalize the path,
285 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
286 cwd = os.getcwd()
287 os.chdir(tmpdir)
288 tmpdir = os.getcwd()
289 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000290 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000291 'import sys,os;'
292 'sys.stdout.write(os.getcwd())'],
293 stdout=subprocess.PIPE,
294 cwd=tmpdir)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000295 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000296 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
297 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298
299 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000300 newenv = os.environ.copy()
301 newenv["FRUIT"] = "orange"
302 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000303 'import sys,os;'
304 'sys.stdout.write(os.getenv("FRUIT"))'],
305 stdout=subprocess.PIPE,
306 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000307 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308
Peter Astrandcbac93c2005-03-03 20:24:28 +0000309 def test_communicate_stdin(self):
310 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000311 'import sys;'
312 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000313 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000314 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000315 self.assertEqual(p.returncode, 1)
316
317 def test_communicate_stdout(self):
318 p = subprocess.Popen([sys.executable, "-c",
319 'import sys; sys.stdout.write("pineapple")'],
320 stdout=subprocess.PIPE)
321 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000322 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000323 self.assertEqual(stderr, None)
324
325 def test_communicate_stderr(self):
326 p = subprocess.Popen([sys.executable, "-c",
327 'import sys; sys.stderr.write("pineapple")'],
328 stderr=subprocess.PIPE)
329 (stdout, stderr) = p.communicate()
330 self.assertEqual(stdout, None)
Brett Cannon653a5ad2005-03-05 06:40:52 +0000331 # When running with a pydebug build, the # of references is outputted
332 # to stderr, so just check if stderr at least started with "pinapple"
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000333 self.assertEqual(remove_stderr_debug_decorations(stderr), b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000334
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000335 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000336 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000337 'import sys,os;'
338 'sys.stderr.write("pineapple");'
339 'sys.stdout.write(sys.stdin.read())'],
340 stdin=subprocess.PIPE,
341 stdout=subprocess.PIPE,
342 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000343 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000344 self.assertEqual(stdout, b"banana")
Tim Peters3761e8d2004-10-13 04:07:12 +0000345 self.assertEqual(remove_stderr_debug_decorations(stderr),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000346 b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000347
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000348 # This test is Linux specific for simplicity to at least have
349 # some coverage. It is not a platform specific bug.
350 if os.path.isdir('/proc/%d/fd' % os.getpid()):
351 # Test for the fd leak reported in http://bugs.python.org/issue2791.
352 def test_communicate_pipe_fd_leak(self):
353 fd_directory = '/proc/%d/fd' % os.getpid()
354 num_fds_before_popen = len(os.listdir(fd_directory))
355 p = subprocess.Popen([sys.executable, '-c', 'print()'],
356 stdout=subprocess.PIPE)
357 p.communicate()
358 num_fds_after_communicate = len(os.listdir(fd_directory))
359 del p
360 num_fds_after_destruction = len(os.listdir(fd_directory))
361 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
362 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
363
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000364 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000365 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000366 p = subprocess.Popen([sys.executable, "-c",
367 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000368 (stdout, stderr) = p.communicate()
369 self.assertEqual(stdout, None)
370 self.assertEqual(stderr, None)
371
372 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000373 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000374 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000375 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000376 x, y = os.pipe()
377 if mswindows:
378 pipe_buf = 512
379 else:
380 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
381 os.close(x)
382 os.close(y)
383 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000384 'import sys,os;'
385 'sys.stdout.write(sys.stdin.read(47));'
386 'sys.stderr.write("xyz"*%d);'
387 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
388 stdin=subprocess.PIPE,
389 stdout=subprocess.PIPE,
390 stderr=subprocess.PIPE)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000391 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000392 (stdout, stderr) = p.communicate(string_to_write)
393 self.assertEqual(stdout, string_to_write)
394
395 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000396 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000397 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000398 'import sys,os;'
399 'sys.stdout.write(sys.stdin.read())'],
400 stdin=subprocess.PIPE,
401 stdout=subprocess.PIPE,
402 stderr=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000403 p.stdin.write(b"banana")
404 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000405 self.assertEqual(stdout, b"bananasplit")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000406 self.assertEqual(remove_stderr_debug_decorations(stderr), b"")
Tim Peterse718f612004-10-12 21:51:32 +0000407
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000408 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000409 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000410 'import sys,os;' + SETBINARY +
411 'sys.stdout.write("line1\\n");'
412 'sys.stdout.flush();'
413 'sys.stdout.write("line2\\n");'
414 'sys.stdout.flush();'
415 'sys.stdout.write("line3\\r\\n");'
416 'sys.stdout.flush();'
417 'sys.stdout.write("line4\\r");'
418 'sys.stdout.flush();'
419 'sys.stdout.write("\\nline5");'
420 'sys.stdout.flush();'
421 'sys.stdout.write("\\nline6");'],
422 stdout=subprocess.PIPE,
423 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000425 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426
427 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000428 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000429 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000430 'import sys,os;' + SETBINARY +
431 'sys.stdout.write("line1\\n");'
432 'sys.stdout.flush();'
433 'sys.stdout.write("line2\\n");'
434 'sys.stdout.flush();'
435 'sys.stdout.write("line3\\r\\n");'
436 'sys.stdout.flush();'
437 'sys.stdout.write("line4\\r");'
438 'sys.stdout.flush();'
439 'sys.stdout.write("\\nline5");'
440 'sys.stdout.flush();'
441 'sys.stdout.write("\\nline6");'],
442 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
443 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000445 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000446
447 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000448 # Make sure we leak no resources
Antoine Pitrou6fab1f62010-09-18 22:40:56 +0000449 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000450 max_handles = 1026 # too much for most UNIX systems
451 else:
Antoine Pitrou6fab1f62010-09-18 22:40:56 +0000452 max_handles = 2050 # too much for (at least some) Windows setups
453 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400454 tmpdir = tempfile.mkdtemp()
Antoine Pitrou6fab1f62010-09-18 22:40:56 +0000455 try:
456 for i in range(max_handles):
457 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400458 tmpfile = os.path.join(tmpdir, support.TESTFN)
459 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou6fab1f62010-09-18 22:40:56 +0000460 except OSError as e:
461 if e.errno != errno.EMFILE:
462 raise
463 break
464 else:
465 self.skipTest("failed to reach the file descriptor limit "
466 "(tried %d)" % max_handles)
467 # Close a couple of them (should be enough for a subprocess)
468 for i in range(10):
469 os.close(handles.pop())
470 # Loop creating some subprocesses. If one of them leaks some fds,
471 # the next loop iteration will fail by reaching the max fd limit.
472 for i in range(15):
473 p = subprocess.Popen([sys.executable, "-c",
474 "import sys;"
475 "sys.stdout.write(sys.stdin.read())"],
476 stdin=subprocess.PIPE,
477 stdout=subprocess.PIPE,
478 stderr=subprocess.PIPE)
479 data = p.communicate(b"lime")[0]
480 self.assertEqual(data, b"lime")
481 finally:
482 for h in handles:
483 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400484 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485
486 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000487 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
488 '"a b c" d e')
489 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
490 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000491 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
492 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000493 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
494 'a\\\\\\b "de fg" h')
495 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
496 'a\\\\\\"b c d')
497 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
498 '"a\\\\b c" d e')
499 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
500 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000501 self.assertEqual(subprocess.list2cmdline(['ab', '']),
502 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000503
504
505 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000506 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000507 "-c", "import time; time.sleep(1)"])
508 count = 0
509 while p.poll() is None:
510 time.sleep(0.1)
511 count += 1
512 # We expect that the poll loop probably went around about 10 times,
513 # but, based on system scheduling we can't control, it's possible
514 # poll() never returned None. It "should be" very rare that it
515 # didn't go around at least twice.
Georg Brandlab91fde2009-08-13 08:51:18 +0000516 self.assertTrue(count >= 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 # Subsequent invocations should just return the returncode
518 self.assertEqual(p.poll(), 0)
519
520
521 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 p = subprocess.Popen([sys.executable,
523 "-c", "import time; time.sleep(2)"])
524 self.assertEqual(p.wait(), 0)
525 # Subsequent invocations should just return the returncode
526 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000527
Peter Astrand738131d2004-11-30 21:04:45 +0000528
529 def test_invalid_bufsize(self):
530 # an invalid type of the bufsize argument should raise
531 # TypeError.
532 try:
533 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
534 except TypeError:
535 pass
536 else:
537 self.fail("Expected TypeError")
538
Guido van Rossum46a05a72007-06-07 21:56:45 +0000539 def test_bufsize_is_none(self):
540 # bufsize=None should be the same as bufsize=0.
541 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
542 self.assertEqual(p.wait(), 0)
543 # Again with keyword arg
544 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
545 self.assertEqual(p.wait(), 0)
546
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000547 def test_leaking_fds_on_error(self):
548 # see bug #5179: Popen leaks file descriptors to PIPEs if
549 # the child fails to execute; this will eventually exhaust
550 # the maximum number of open fds. 1024 seems a very common
551 # value for that limit, but Windows has 2048, so we loop
552 # 1024 times (each call leaked two fds).
553 for i in range(1024):
554 try:
555 subprocess.Popen(['nonexisting_i_hope'],
556 stdout=subprocess.PIPE,
557 stderr=subprocess.PIPE)
558 # Windows raises IOError
559 except (IOError, OSError) as err:
R David Murrayd79210a2011-03-13 22:13:09 -0400560 # ignore errors that indicate the command was not found
Antoine Pitrou126848a2011-03-15 21:17:10 +0100561 if err.errno not in (errno.ENOENT, errno.EACCES):
Benjamin Peterson4b068192009-02-20 03:19:25 +0000562 raise
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000563
Victor Stinner86c73bf2010-05-21 20:39:17 +0000564 def test_issue8780(self):
565 # Ensure that stdout is inherited from the parent
566 # if stdout=PIPE is not used
567 code = ';'.join((
568 'import subprocess, sys',
569 'retcode = subprocess.call('
570 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
571 'assert retcode == 0'))
572 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000573 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinner86c73bf2010-05-21 20:39:17 +0000574
Tim Golden40b37442010-08-06 13:20:12 +0000575 def test_handles_closed_on_exception(self):
576 # If CreateProcess exits with an error, ensure the
577 # duplicate output handles are released
578 ifhandle, ifname = self.mkstemp()
579 ofhandle, ofname = self.mkstemp()
580 efhandle, efname = self.mkstemp()
581 try:
582 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
583 stderr=efhandle)
584 except OSError:
585 os.close(ifhandle)
586 os.remove(ifname)
587 os.close(ofhandle)
588 os.remove(ofname)
589 os.close(efhandle)
590 os.remove(efname)
591 self.assertFalse(os.path.exists(ifname))
592 self.assertFalse(os.path.exists(ofname))
593 self.assertFalse(os.path.exists(efname))
594
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200595 def test_communicate_epipe(self):
596 # Issue 10963: communicate() should hide EPIPE
597 p = subprocess.Popen([sys.executable, "-c", 'pass'],
598 stdin=subprocess.PIPE,
599 stdout=subprocess.PIPE,
600 stderr=subprocess.PIPE)
601 self.addCleanup(p.stdout.close)
602 self.addCleanup(p.stderr.close)
603 self.addCleanup(p.stdin.close)
604 p.communicate(b"x" * 2**20)
605
606 def test_communicate_epipe_only_stdin(self):
607 # Issue 10963: communicate() should hide EPIPE
608 p = subprocess.Popen([sys.executable, "-c", 'pass'],
609 stdin=subprocess.PIPE)
610 self.addCleanup(p.stdin.close)
611 time.sleep(2)
612 p.communicate(b"x" * 2**20)
613
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000614 #
615 # POSIX tests
616 #
617 if not mswindows:
618 def test_exceptions(self):
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000619 # caught & re-raised exceptions
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000620 try:
621 p = subprocess.Popen([sys.executable, "-c", ""],
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000622 cwd="/this/path/does/not/exist")
Guido van Rossumb940e112007-01-10 16:19:56 +0000623 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624 # The attribute child_traceback should contain "os.chdir"
625 # somewhere.
626 self.assertNotEqual(e.child_traceback.find("os.chdir"), -1)
627 else:
628 self.fail("Expected OSError")
Tim Peterse718f612004-10-12 21:51:32 +0000629
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000630 def _suppress_core_files(self):
631 """Try to prevent core files from being created.
632 Returns previous ulimit if successful, else None.
633 """
Ronald Oussorend7eb3a82010-07-23 10:35:20 +0000634 if sys.platform == 'darwin':
635 # Check if the 'Crash Reporter' on OSX was configured
636 # in 'Developer' mode and warn that it will get triggered
637 # when it is.
638 #
639 # This assumes that this context manager is used in tests
640 # that might trigger the next manager.
641 value = subprocess.Popen(['/usr/bin/defaults', 'read',
642 'com.apple.CrashReporter', 'DialogType'],
643 stdout=subprocess.PIPE).communicate()[0]
644 if value.strip() == b'developer':
645 print("this tests triggers the Crash Reporter, "
646 "that is intentional", end='')
647 sys.stdout.flush()
648
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000649 try:
650 import resource
651 old_limit = resource.getrlimit(resource.RLIMIT_CORE)
652 resource.setrlimit(resource.RLIMIT_CORE, (0,0))
653 return old_limit
654 except (ImportError, ValueError, resource.error):
655 return None
656
Ronald Oussorend7eb3a82010-07-23 10:35:20 +0000657
658
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000659 def _unsuppress_core_files(self, old_limit):
660 """Return core file behavior to default."""
661 if old_limit is None:
662 return
663 try:
664 import resource
665 resource.setrlimit(resource.RLIMIT_CORE, old_limit)
666 except (ImportError, ValueError, resource.error):
667 return
668
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000669 def test_run_abort(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000670 # returncode handles signal termination
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000671 old_limit = self._suppress_core_files()
672 try:
673 p = subprocess.Popen([sys.executable,
674 "-c", "import os; os.abort()"])
675 finally:
676 self._unsuppress_core_files(old_limit)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000677 p.wait()
678 self.assertEqual(-p.returncode, signal.SIGABRT)
679
680 def test_preexec(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000681 # preexec function
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000682 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000683 'import sys,os;'
684 'sys.stdout.write(os.getenv("FRUIT"))'],
685 stdout=subprocess.PIPE,
686 preexec_fn=lambda: os.putenv("FRUIT",
687 "apple"))
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000688 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000689
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000690 def test_args_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000691 # args is a string
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 p = subprocess.Popen(fname)
700 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000701 os.remove(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000702 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000703
704 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000705 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000706 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000707 [sys.executable,
708 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000709 startupinfo=47)
710 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000711 [sys.executable,
712 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000713 creationflags=47)
714
715 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000716 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000717 newenv = os.environ.copy()
718 newenv["FRUIT"] = "apple"
719 p = subprocess.Popen(["echo $FRUIT"], shell=1,
720 stdout=subprocess.PIPE,
721 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000722 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000723
724 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000725 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000726 newenv = os.environ.copy()
727 newenv["FRUIT"] = "apple"
728 p = subprocess.Popen("echo $FRUIT", shell=1,
729 stdout=subprocess.PIPE,
730 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000731 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000732
733 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000734 # call() function with string argument on UNIX
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000735 fd, fname = self.mkstemp()
736 # reopen in text mode
737 with open(fd, "w") as fobj:
738 fobj.write("#!/bin/sh\n")
739 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
740 sys.executable)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000741 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000742 rc = subprocess.call(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000743 os.remove(fname)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000744 self.assertEqual(rc, 47)
745
Stefan Krah8db99c82010-07-19 14:39:36 +0000746 def test_specific_shell(self):
747 # Issue #9265: Incorrect name passed as arg[0].
748 shells = []
749 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
750 for name in ['bash', 'ksh']:
751 sh = os.path.join(prefix, name)
752 if os.path.isfile(sh):
753 shells.append(sh)
754 if not shells: # Will probably work for any shell but csh.
755 self.skipTest("bash or ksh required for this test")
756 sh = '/bin/sh'
757 if os.path.isfile(sh) and not os.path.islink(sh):
758 # Test will fail if /bin/sh is a symlink to csh.
759 shells.append(sh)
760 for sh in shells:
761 p = subprocess.Popen("echo $0", executable=sh, shell=True,
762 stdout=subprocess.PIPE)
763 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
764
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000765 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000766 p = subprocess.Popen([sys.executable,
767 "-c", "input()"])
768
Georg Brandlab91fde2009-08-13 08:51:18 +0000769 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000770 p.send_signal(signal.SIGINT)
771 self.assertNotEqual(p.wait(), 0)
772
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000773 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000774 p = subprocess.Popen([sys.executable,
775 "-c", "input()"])
776
Georg Brandlab91fde2009-08-13 08:51:18 +0000777 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000778 p.kill()
779 self.assertEqual(p.wait(), -signal.SIGKILL)
780
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000781 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000782 p = subprocess.Popen([sys.executable,
783 "-c", "input()"])
784
Georg Brandlab91fde2009-08-13 08:51:18 +0000785 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000786 p.terminate()
787 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000788
Victor Stinner097d1b72010-04-27 18:29:45 +0000789 def test_undecodable_env(self):
790 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Antoine Pitrou4a5dd5c2010-09-20 11:17:39 +0000791 value_repr = ascii(value).encode("ascii")
Victor Stinner097d1b72010-04-27 18:29:45 +0000792
793 # test str with surrogates
Antoine Pitrou4a5dd5c2010-09-20 11:17:39 +0000794 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinner097d1b72010-04-27 18:29:45 +0000795 env = os.environ.copy()
796 env[key] = value
Antoine Pitrou4a5dd5c2010-09-20 11:17:39 +0000797 # Force surrogate-escaping of \xFF in the child process;
798 # otherwise it can be decoded as-is if the default locale
799 # is latin-1.
800 env['PYTHONFSENCODING'] = 'ascii'
Victor Stinner097d1b72010-04-27 18:29:45 +0000801 stdout = subprocess.check_output(
802 [sys.executable, "-c", script],
803 env=env)
804 stdout = stdout.rstrip(b'\n\r')
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000805 self.assertEqual(stdout, value_repr)
Victor Stinner097d1b72010-04-27 18:29:45 +0000806
807 # test bytes
808 key = key.encode("ascii", "surrogateescape")
809 value = value.encode("ascii", "surrogateescape")
Antoine Pitrou4a5dd5c2010-09-20 11:17:39 +0000810 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinner097d1b72010-04-27 18:29:45 +0000811 env = os.environ.copy()
812 env[key] = value
813 stdout = subprocess.check_output(
814 [sys.executable, "-c", script],
815 env=env)
816 stdout = stdout.rstrip(b'\n\r')
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000817 self.assertEqual(stdout, value_repr)
Victor Stinner097d1b72010-04-27 18:29:45 +0000818
Gregory P. Smithb740e762010-12-14 15:16:24 +0000819 def test_wait_when_sigchild_ignored(self):
820 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
821 sigchild_ignore = support.findfile("sigchild_ignore.py",
822 subdir="subprocessdata")
823 p = subprocess.Popen([sys.executable, sigchild_ignore],
824 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
825 stdout, stderr = p.communicate()
826 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smith773d7df2010-12-14 15:25:20 +0000827 " non-zero with this error:\n%s" %
828 stderr.decode('utf8'))
Gregory P. Smithb740e762010-12-14 15:16:24 +0000829
Antoine Pitrouf50a6b62011-01-03 18:36:36 +0000830 def check_close_std_fds(self, fds):
831 # Issue #9905: test that subprocess pipes still work properly with
832 # some standard fds closed
833 stdin = 0
834 newfds = []
835 for a in fds:
836 b = os.dup(a)
837 newfds.append(b)
838 if a == 0:
839 stdin = b
840 try:
841 for fd in fds:
842 os.close(fd)
843 out, err = subprocess.Popen([sys.executable, "-c",
844 'import sys;'
845 'sys.stdout.write("apple");'
846 'sys.stdout.flush();'
847 'sys.stderr.write("orange")'],
848 stdin=stdin,
849 stdout=subprocess.PIPE,
850 stderr=subprocess.PIPE).communicate()
851 err = support.strip_python_stderr(err)
852 self.assertEqual((out, err), (b'apple', b'orange'))
853 finally:
854 for b, a in zip(newfds, fds):
855 os.dup2(b, a)
856 for b in newfds:
857 os.close(b)
858
859 def test_close_fd_0(self):
860 self.check_close_std_fds([0])
861
862 def test_close_fd_1(self):
863 self.check_close_std_fds([1])
864
865 def test_close_fd_2(self):
866 self.check_close_std_fds([2])
867
868 def test_close_fds_0_1(self):
869 self.check_close_std_fds([0, 1])
870
871 def test_close_fds_0_2(self):
872 self.check_close_std_fds([0, 2])
873
874 def test_close_fds_1_2(self):
875 self.check_close_std_fds([1, 2])
876
877 def test_close_fds_0_1_2(self):
878 # Issue #10806: test that subprocess pipes still work properly with
879 # all standard fds closed.
880 self.check_close_std_fds([0, 1, 2])
881
882 def test_surrogates_error_message(self):
883 def prepare():
884 raise ValueError("surrogate:\uDCff")
885
Antoine Pitrou877766d2011-03-19 17:00:37 +0100886 def test_select_unbuffered(self):
887 # Issue #11459: bufsize=0 should really set the pipes as
888 # unbuffered (and therefore let select() work properly).
889 select = support.import_module("select")
890 p = subprocess.Popen([sys.executable, "-c",
891 'import sys;'
892 'sys.stdout.write("apple")'],
893 stdout=subprocess.PIPE,
894 bufsize=0)
895 f = p.stdout
Ross Lagerwallb8a57692011-03-26 21:19:57 +0200896 self.addCleanup(f.close)
Antoine Pitrou877766d2011-03-19 17:00:37 +0100897 try:
898 self.assertEqual(f.read(4), b"appl")
899 self.assertIn(f, select.select([f], [], [], 0.0)[0])
900 finally:
901 p.wait()
Gregory P. Smithb740e762010-12-14 15:16:24 +0000902
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000903 #
904 # Windows tests
905 #
906 if mswindows:
907 def test_startupinfo(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000908 # startupinfo argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000909 # We uses hardcoded constants, because we do not want to
Tim Peterse718f612004-10-12 21:51:32 +0000910 # depend on win32all.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000911 STARTF_USESHOWWINDOW = 1
912 SW_MAXIMIZE = 3
913 startupinfo = subprocess.STARTUPINFO()
914 startupinfo.dwFlags = STARTF_USESHOWWINDOW
915 startupinfo.wShowWindow = SW_MAXIMIZE
916 # Since Python is a console process, it won't be affected
917 # by wShowWindow, but the argument should be silently
918 # ignored
919 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
920 startupinfo=startupinfo)
921
922 def test_creationflags(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000923 # creationflags argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000924 CREATE_NEW_CONSOLE = 16
Tim Peters876c4322004-10-13 03:21:35 +0000925 sys.stderr.write(" a DOS box should flash briefly ...\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000926 subprocess.call(sys.executable +
Tim Peters876c4322004-10-13 03:21:35 +0000927 ' -c "import time; time.sleep(0.25)"',
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000928 creationflags=CREATE_NEW_CONSOLE)
929
930 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000931 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000932 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000933 [sys.executable,
934 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000935 preexec_fn=lambda: 1)
936 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000937 [sys.executable,
938 "-c", "import sys; sys.exit(47)"],
Guido van Rossume7ba4952007-06-06 23:52:48 +0000939 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940 close_fds=True)
941
Guido van Rossume7ba4952007-06-06 23:52:48 +0000942 def test_close_fds(self):
943 # close file descriptors
944 rc = subprocess.call([sys.executable, "-c",
945 "import sys; sys.exit(47)"],
946 close_fds=True)
947 self.assertEqual(rc, 47)
948
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000949 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000950 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000951 newenv = os.environ.copy()
952 newenv["FRUIT"] = "physalis"
953 p = subprocess.Popen(["set"], shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000954 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000955 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000956 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000957
958 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000959 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000960 newenv = os.environ.copy()
961 newenv["FRUIT"] = "physalis"
962 p = subprocess.Popen("set", shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000963 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000964 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000965 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000966
967 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000968 # call() function with string argument on Windows
Tim Peters3b01a702004-10-12 22:19:32 +0000969 rc = subprocess.call(sys.executable +
970 ' -c "import sys; sys.exit(47)"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000971 self.assertEqual(rc, 47)
972
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000973 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000974 p = subprocess.Popen([sys.executable,
975 "-c", "input()"])
976
Georg Brandlab91fde2009-08-13 08:51:18 +0000977 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000978 p.send_signal(signal.SIGTERM)
979 self.assertNotEqual(p.wait(), 0)
980
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000981 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000982 p = subprocess.Popen([sys.executable,
983 "-c", "input()"])
984
Georg Brandlab91fde2009-08-13 08:51:18 +0000985 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000986 p.kill()
987 self.assertNotEqual(p.wait(), 0)
988
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000989 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000990 p = subprocess.Popen([sys.executable,
991 "-c", "input()"])
992
Georg Brandlab91fde2009-08-13 08:51:18 +0000993 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000994 p.terminate()
995 self.assertNotEqual(p.wait(), 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000996
Tim Golden595c8d32010-08-12 09:45:25 +0000997
Brett Cannona23810f2008-05-26 19:04:21 +0000998class CommandTests(unittest.TestCase):
999# The module says:
1000# "NB This only works (and is only relevant) for UNIX."
1001#
1002# Actually, getoutput should work on any platform with an os.popen, but
1003# I'll take the comment as given, and skip this suite.
1004 if os.name == 'posix':
1005
1006 def test_getoutput(self):
Ezio Melotti19f2aeb2010-11-21 01:30:29 +00001007 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1008 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1009 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001010
1011 # we use mkdtemp in the next line to create an empty directory
1012 # under our exclusive control; from that, we can invent a pathname
1013 # that we _know_ won't exist. This is guaranteed to fail.
1014 dir = None
1015 try:
1016 dir = tempfile.mkdtemp()
1017 name = os.path.join(dir, "foo")
1018
1019 status, output = subprocess.getstatusoutput('cat ' + name)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +00001020 self.assertNotEqual(status, 0)
Brett Cannona23810f2008-05-26 19:04:21 +00001021 finally:
1022 if dir is not None:
1023 os.rmdir(dir)
1024
Georg Brandlae83d6e2009-08-13 09:04:31 +00001025
1026unit_tests = [ProcessTestCase, CommandTests]
1027
Tim Golden595c8d32010-08-12 09:45:25 +00001028if mswindows:
1029 class CommandsWithSpaces (BaseTestCase):
1030
1031 def setUp(self):
1032 super().setUp()
1033 f, fname = self.mkstemp(".py", "te st")
1034 self.fname = fname.lower ()
1035 os.write(f, b"import sys;"
1036 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1037 )
1038 os.close(f)
1039
1040 def tearDown(self):
1041 os.remove(self.fname)
1042 super().tearDown()
1043
1044 def with_spaces(self, *args, **kwargs):
1045 kwargs['stdout'] = subprocess.PIPE
1046 p = subprocess.Popen(*args, **kwargs)
1047 self.assertEqual(
1048 p.stdout.read ().decode("mbcs"),
1049 "2 [%r, 'ab cd']" % self.fname
1050 )
1051
1052 def test_shell_string_with_spaces(self):
1053 # call() function with string argument with spaces on Windows
Brian Curtinf263c052010-08-13 20:59:27 +00001054 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1055 "ab cd"), shell=1)
Tim Golden595c8d32010-08-12 09:45:25 +00001056
1057 def test_shell_sequence_with_spaces(self):
1058 # call() function with sequence argument with spaces on Windows
Brian Curtinf263c052010-08-13 20:59:27 +00001059 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden595c8d32010-08-12 09:45:25 +00001060
1061 def test_noshell_string_with_spaces(self):
1062 # call() function with string argument with spaces on Windows
1063 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1064 "ab cd"))
1065
1066 def test_noshell_sequence_with_spaces(self):
1067 # call() function with sequence argument with spaces on Windows
1068 self.with_spaces([sys.executable, self.fname, "ab cd"])
1069
1070 unit_tests.append(CommandsWithSpaces)
1071
1072
Gregory P. Smith10d29522009-08-13 18:33:30 +00001073if getattr(subprocess, '_has_poll', False):
Georg Brandlae83d6e2009-08-13 09:04:31 +00001074 class ProcessTestCaseNoPoll(ProcessTestCase):
1075 def setUp(self):
1076 subprocess._has_poll = False
1077 ProcessTestCase.setUp(self)
1078
1079 def tearDown(self):
1080 subprocess._has_poll = True
1081 ProcessTestCase.tearDown(self)
1082
1083 unit_tests.append(ProcessTestCaseNoPoll)
1084
1085
Gregory P. Smith3fff44d2010-03-01 00:43:08 +00001086class HelperFunctionTests(unittest.TestCase):
Gregory P. Smith5cab2812010-03-01 02:58:43 +00001087 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smith3fff44d2010-03-01 00:43:08 +00001088 def test_eintr_retry_call(self):
1089 record_calls = []
1090 def fake_os_func(*args):
1091 record_calls.append(args)
1092 if len(record_calls) == 2:
1093 raise OSError(errno.EINTR, "fake interrupted system call")
1094 return tuple(reversed(args))
1095
1096 self.assertEqual((999, 256),
1097 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1098 self.assertEqual([(256, 999)], record_calls)
1099 # This time there will be an EINTR so it will loop once.
1100 self.assertEqual((666,),
1101 subprocess._eintr_retry_call(fake_os_func, 666))
1102 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1103
1104unit_tests.append(HelperFunctionTests)
1105
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001106def test_main():
Georg Brandlae83d6e2009-08-13 09:04:31 +00001107 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +00001108 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001109
1110if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +00001111 test_main()