blob: 410849fc286ece42a48d28c1ab7b938b9205000b [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
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000595 #
596 # POSIX tests
597 #
598 if not mswindows:
599 def test_exceptions(self):
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000600 # caught & re-raised exceptions
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601 try:
602 p = subprocess.Popen([sys.executable, "-c", ""],
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000603 cwd="/this/path/does/not/exist")
Guido van Rossumb940e112007-01-10 16:19:56 +0000604 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000605 # The attribute child_traceback should contain "os.chdir"
606 # somewhere.
607 self.assertNotEqual(e.child_traceback.find("os.chdir"), -1)
608 else:
609 self.fail("Expected OSError")
Tim Peterse718f612004-10-12 21:51:32 +0000610
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000611 def _suppress_core_files(self):
612 """Try to prevent core files from being created.
613 Returns previous ulimit if successful, else None.
614 """
Ronald Oussorend7eb3a82010-07-23 10:35:20 +0000615 if sys.platform == 'darwin':
616 # Check if the 'Crash Reporter' on OSX was configured
617 # in 'Developer' mode and warn that it will get triggered
618 # when it is.
619 #
620 # This assumes that this context manager is used in tests
621 # that might trigger the next manager.
622 value = subprocess.Popen(['/usr/bin/defaults', 'read',
623 'com.apple.CrashReporter', 'DialogType'],
624 stdout=subprocess.PIPE).communicate()[0]
625 if value.strip() == b'developer':
626 print("this tests triggers the Crash Reporter, "
627 "that is intentional", end='')
628 sys.stdout.flush()
629
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000630 try:
631 import resource
632 old_limit = resource.getrlimit(resource.RLIMIT_CORE)
633 resource.setrlimit(resource.RLIMIT_CORE, (0,0))
634 return old_limit
635 except (ImportError, ValueError, resource.error):
636 return None
637
Ronald Oussorend7eb3a82010-07-23 10:35:20 +0000638
639
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000640 def _unsuppress_core_files(self, old_limit):
641 """Return core file behavior to default."""
642 if old_limit is None:
643 return
644 try:
645 import resource
646 resource.setrlimit(resource.RLIMIT_CORE, old_limit)
647 except (ImportError, ValueError, resource.error):
648 return
649
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000650 def test_run_abort(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000651 # returncode handles signal termination
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000652 old_limit = self._suppress_core_files()
653 try:
654 p = subprocess.Popen([sys.executable,
655 "-c", "import os; os.abort()"])
656 finally:
657 self._unsuppress_core_files(old_limit)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000658 p.wait()
659 self.assertEqual(-p.returncode, signal.SIGABRT)
660
661 def test_preexec(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000662 # preexec function
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000664 'import sys,os;'
665 'sys.stdout.write(os.getenv("FRUIT"))'],
666 stdout=subprocess.PIPE,
667 preexec_fn=lambda: os.putenv("FRUIT",
668 "apple"))
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000669 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000670
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000671 def test_args_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000672 # args is a string
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000673 fd, fname = self.mkstemp()
674 # reopen in text mode
675 with open(fd, "w") as fobj:
676 fobj.write("#!/bin/sh\n")
677 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
678 sys.executable)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000679 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000680 p = subprocess.Popen(fname)
681 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000682 os.remove(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000683 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000684
685 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000686 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000687 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000688 [sys.executable,
689 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000690 startupinfo=47)
691 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000692 [sys.executable,
693 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000694 creationflags=47)
695
696 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000697 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000698 newenv = os.environ.copy()
699 newenv["FRUIT"] = "apple"
700 p = subprocess.Popen(["echo $FRUIT"], shell=1,
701 stdout=subprocess.PIPE,
702 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000703 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000704
705 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000706 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000707 newenv = os.environ.copy()
708 newenv["FRUIT"] = "apple"
709 p = subprocess.Popen("echo $FRUIT", shell=1,
710 stdout=subprocess.PIPE,
711 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000712 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000713
714 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000715 # call() function with string argument on UNIX
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000716 fd, fname = self.mkstemp()
717 # reopen in text mode
718 with open(fd, "w") as fobj:
719 fobj.write("#!/bin/sh\n")
720 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
721 sys.executable)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000722 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000723 rc = subprocess.call(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000724 os.remove(fname)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000725 self.assertEqual(rc, 47)
726
Stefan Krah8db99c82010-07-19 14:39:36 +0000727 def test_specific_shell(self):
728 # Issue #9265: Incorrect name passed as arg[0].
729 shells = []
730 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
731 for name in ['bash', 'ksh']:
732 sh = os.path.join(prefix, name)
733 if os.path.isfile(sh):
734 shells.append(sh)
735 if not shells: # Will probably work for any shell but csh.
736 self.skipTest("bash or ksh required for this test")
737 sh = '/bin/sh'
738 if os.path.isfile(sh) and not os.path.islink(sh):
739 # Test will fail if /bin/sh is a symlink to csh.
740 shells.append(sh)
741 for sh in shells:
742 p = subprocess.Popen("echo $0", executable=sh, shell=True,
743 stdout=subprocess.PIPE)
744 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
745
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000746 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000747 p = subprocess.Popen([sys.executable,
748 "-c", "input()"])
749
Georg Brandlab91fde2009-08-13 08:51:18 +0000750 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000751 p.send_signal(signal.SIGINT)
752 self.assertNotEqual(p.wait(), 0)
753
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000754 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000755 p = subprocess.Popen([sys.executable,
756 "-c", "input()"])
757
Georg Brandlab91fde2009-08-13 08:51:18 +0000758 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000759 p.kill()
760 self.assertEqual(p.wait(), -signal.SIGKILL)
761
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000762 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000763 p = subprocess.Popen([sys.executable,
764 "-c", "input()"])
765
Georg Brandlab91fde2009-08-13 08:51:18 +0000766 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000767 p.terminate()
768 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000769
Victor Stinner097d1b72010-04-27 18:29:45 +0000770 def test_undecodable_env(self):
771 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Antoine Pitrou4a5dd5c2010-09-20 11:17:39 +0000772 value_repr = ascii(value).encode("ascii")
Victor Stinner097d1b72010-04-27 18:29:45 +0000773
774 # test str with surrogates
Antoine Pitrou4a5dd5c2010-09-20 11:17:39 +0000775 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinner097d1b72010-04-27 18:29:45 +0000776 env = os.environ.copy()
777 env[key] = value
Antoine Pitrou4a5dd5c2010-09-20 11:17:39 +0000778 # Force surrogate-escaping of \xFF in the child process;
779 # otherwise it can be decoded as-is if the default locale
780 # is latin-1.
781 env['PYTHONFSENCODING'] = 'ascii'
Victor Stinner097d1b72010-04-27 18:29:45 +0000782 stdout = subprocess.check_output(
783 [sys.executable, "-c", script],
784 env=env)
785 stdout = stdout.rstrip(b'\n\r')
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000786 self.assertEqual(stdout, value_repr)
Victor Stinner097d1b72010-04-27 18:29:45 +0000787
788 # test bytes
789 key = key.encode("ascii", "surrogateescape")
790 value = value.encode("ascii", "surrogateescape")
Antoine Pitrou4a5dd5c2010-09-20 11:17:39 +0000791 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinner097d1b72010-04-27 18:29:45 +0000792 env = os.environ.copy()
793 env[key] = value
794 stdout = subprocess.check_output(
795 [sys.executable, "-c", script],
796 env=env)
797 stdout = stdout.rstrip(b'\n\r')
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000798 self.assertEqual(stdout, value_repr)
Victor Stinner097d1b72010-04-27 18:29:45 +0000799
Gregory P. Smithb740e762010-12-14 15:16:24 +0000800 def test_wait_when_sigchild_ignored(self):
801 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
802 sigchild_ignore = support.findfile("sigchild_ignore.py",
803 subdir="subprocessdata")
804 p = subprocess.Popen([sys.executable, sigchild_ignore],
805 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
806 stdout, stderr = p.communicate()
807 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smith773d7df2010-12-14 15:25:20 +0000808 " non-zero with this error:\n%s" %
809 stderr.decode('utf8'))
Gregory P. Smithb740e762010-12-14 15:16:24 +0000810
Antoine Pitrouf50a6b62011-01-03 18:36:36 +0000811 def check_close_std_fds(self, fds):
812 # Issue #9905: test that subprocess pipes still work properly with
813 # some standard fds closed
814 stdin = 0
815 newfds = []
816 for a in fds:
817 b = os.dup(a)
818 newfds.append(b)
819 if a == 0:
820 stdin = b
821 try:
822 for fd in fds:
823 os.close(fd)
824 out, err = subprocess.Popen([sys.executable, "-c",
825 'import sys;'
826 'sys.stdout.write("apple");'
827 'sys.stdout.flush();'
828 'sys.stderr.write("orange")'],
829 stdin=stdin,
830 stdout=subprocess.PIPE,
831 stderr=subprocess.PIPE).communicate()
832 err = support.strip_python_stderr(err)
833 self.assertEqual((out, err), (b'apple', b'orange'))
834 finally:
835 for b, a in zip(newfds, fds):
836 os.dup2(b, a)
837 for b in newfds:
838 os.close(b)
839
840 def test_close_fd_0(self):
841 self.check_close_std_fds([0])
842
843 def test_close_fd_1(self):
844 self.check_close_std_fds([1])
845
846 def test_close_fd_2(self):
847 self.check_close_std_fds([2])
848
849 def test_close_fds_0_1(self):
850 self.check_close_std_fds([0, 1])
851
852 def test_close_fds_0_2(self):
853 self.check_close_std_fds([0, 2])
854
855 def test_close_fds_1_2(self):
856 self.check_close_std_fds([1, 2])
857
858 def test_close_fds_0_1_2(self):
859 # Issue #10806: test that subprocess pipes still work properly with
860 # all standard fds closed.
861 self.check_close_std_fds([0, 1, 2])
862
863 def test_surrogates_error_message(self):
864 def prepare():
865 raise ValueError("surrogate:\uDCff")
866
Antoine Pitrou877766d2011-03-19 17:00:37 +0100867 def test_select_unbuffered(self):
868 # Issue #11459: bufsize=0 should really set the pipes as
869 # unbuffered (and therefore let select() work properly).
870 select = support.import_module("select")
871 p = subprocess.Popen([sys.executable, "-c",
872 'import sys;'
873 'sys.stdout.write("apple")'],
874 stdout=subprocess.PIPE,
875 bufsize=0)
876 f = p.stdout
877 try:
878 self.assertEqual(f.read(4), b"appl")
879 self.assertIn(f, select.select([f], [], [], 0.0)[0])
880 finally:
881 p.wait()
Gregory P. Smithb740e762010-12-14 15:16:24 +0000882
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000883 #
884 # Windows tests
885 #
886 if mswindows:
887 def test_startupinfo(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000888 # startupinfo argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000889 # We uses hardcoded constants, because we do not want to
Tim Peterse718f612004-10-12 21:51:32 +0000890 # depend on win32all.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000891 STARTF_USESHOWWINDOW = 1
892 SW_MAXIMIZE = 3
893 startupinfo = subprocess.STARTUPINFO()
894 startupinfo.dwFlags = STARTF_USESHOWWINDOW
895 startupinfo.wShowWindow = SW_MAXIMIZE
896 # Since Python is a console process, it won't be affected
897 # by wShowWindow, but the argument should be silently
898 # ignored
899 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
900 startupinfo=startupinfo)
901
902 def test_creationflags(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000903 # creationflags argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000904 CREATE_NEW_CONSOLE = 16
Tim Peters876c4322004-10-13 03:21:35 +0000905 sys.stderr.write(" a DOS box should flash briefly ...\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000906 subprocess.call(sys.executable +
Tim Peters876c4322004-10-13 03:21:35 +0000907 ' -c "import time; time.sleep(0.25)"',
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000908 creationflags=CREATE_NEW_CONSOLE)
909
910 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000911 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000912 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000913 [sys.executable,
914 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000915 preexec_fn=lambda: 1)
916 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000917 [sys.executable,
918 "-c", "import sys; sys.exit(47)"],
Guido van Rossume7ba4952007-06-06 23:52:48 +0000919 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000920 close_fds=True)
921
Guido van Rossume7ba4952007-06-06 23:52:48 +0000922 def test_close_fds(self):
923 # close file descriptors
924 rc = subprocess.call([sys.executable, "-c",
925 "import sys; sys.exit(47)"],
926 close_fds=True)
927 self.assertEqual(rc, 47)
928
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000929 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000930 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931 newenv = os.environ.copy()
932 newenv["FRUIT"] = "physalis"
933 p = subprocess.Popen(["set"], shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000934 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000935 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000936 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000937
938 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000939 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940 newenv = os.environ.copy()
941 newenv["FRUIT"] = "physalis"
942 p = subprocess.Popen("set", shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000943 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000944 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000945 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000946
947 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000948 # call() function with string argument on Windows
Tim Peters3b01a702004-10-12 22:19:32 +0000949 rc = subprocess.call(sys.executable +
950 ' -c "import sys; sys.exit(47)"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000951 self.assertEqual(rc, 47)
952
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000953 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000954 p = subprocess.Popen([sys.executable,
955 "-c", "input()"])
956
Georg Brandlab91fde2009-08-13 08:51:18 +0000957 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000958 p.send_signal(signal.SIGTERM)
959 self.assertNotEqual(p.wait(), 0)
960
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000961 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000962 p = subprocess.Popen([sys.executable,
963 "-c", "input()"])
964
Georg Brandlab91fde2009-08-13 08:51:18 +0000965 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000966 p.kill()
967 self.assertNotEqual(p.wait(), 0)
968
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000969 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000970 p = subprocess.Popen([sys.executable,
971 "-c", "input()"])
972
Georg Brandlab91fde2009-08-13 08:51:18 +0000973 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000974 p.terminate()
975 self.assertNotEqual(p.wait(), 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000976
Tim Golden595c8d32010-08-12 09:45:25 +0000977
Brett Cannona23810f2008-05-26 19:04:21 +0000978class CommandTests(unittest.TestCase):
979# The module says:
980# "NB This only works (and is only relevant) for UNIX."
981#
982# Actually, getoutput should work on any platform with an os.popen, but
983# I'll take the comment as given, and skip this suite.
984 if os.name == 'posix':
985
986 def test_getoutput(self):
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000987 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
988 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
989 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +0000990
991 # we use mkdtemp in the next line to create an empty directory
992 # under our exclusive control; from that, we can invent a pathname
993 # that we _know_ won't exist. This is guaranteed to fail.
994 dir = None
995 try:
996 dir = tempfile.mkdtemp()
997 name = os.path.join(dir, "foo")
998
999 status, output = subprocess.getstatusoutput('cat ' + name)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +00001000 self.assertNotEqual(status, 0)
Brett Cannona23810f2008-05-26 19:04:21 +00001001 finally:
1002 if dir is not None:
1003 os.rmdir(dir)
1004
Georg Brandlae83d6e2009-08-13 09:04:31 +00001005
1006unit_tests = [ProcessTestCase, CommandTests]
1007
Tim Golden595c8d32010-08-12 09:45:25 +00001008if mswindows:
1009 class CommandsWithSpaces (BaseTestCase):
1010
1011 def setUp(self):
1012 super().setUp()
1013 f, fname = self.mkstemp(".py", "te st")
1014 self.fname = fname.lower ()
1015 os.write(f, b"import sys;"
1016 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1017 )
1018 os.close(f)
1019
1020 def tearDown(self):
1021 os.remove(self.fname)
1022 super().tearDown()
1023
1024 def with_spaces(self, *args, **kwargs):
1025 kwargs['stdout'] = subprocess.PIPE
1026 p = subprocess.Popen(*args, **kwargs)
1027 self.assertEqual(
1028 p.stdout.read ().decode("mbcs"),
1029 "2 [%r, 'ab cd']" % self.fname
1030 )
1031
1032 def test_shell_string_with_spaces(self):
1033 # call() function with string argument with spaces on Windows
Brian Curtinf263c052010-08-13 20:59:27 +00001034 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1035 "ab cd"), shell=1)
Tim Golden595c8d32010-08-12 09:45:25 +00001036
1037 def test_shell_sequence_with_spaces(self):
1038 # call() function with sequence argument with spaces on Windows
Brian Curtinf263c052010-08-13 20:59:27 +00001039 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden595c8d32010-08-12 09:45:25 +00001040
1041 def test_noshell_string_with_spaces(self):
1042 # call() function with string argument with spaces on Windows
1043 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1044 "ab cd"))
1045
1046 def test_noshell_sequence_with_spaces(self):
1047 # call() function with sequence argument with spaces on Windows
1048 self.with_spaces([sys.executable, self.fname, "ab cd"])
1049
1050 unit_tests.append(CommandsWithSpaces)
1051
1052
Gregory P. Smith10d29522009-08-13 18:33:30 +00001053if getattr(subprocess, '_has_poll', False):
Georg Brandlae83d6e2009-08-13 09:04:31 +00001054 class ProcessTestCaseNoPoll(ProcessTestCase):
1055 def setUp(self):
1056 subprocess._has_poll = False
1057 ProcessTestCase.setUp(self)
1058
1059 def tearDown(self):
1060 subprocess._has_poll = True
1061 ProcessTestCase.tearDown(self)
1062
1063 unit_tests.append(ProcessTestCaseNoPoll)
1064
1065
Gregory P. Smith3fff44d2010-03-01 00:43:08 +00001066class HelperFunctionTests(unittest.TestCase):
Gregory P. Smith5cab2812010-03-01 02:58:43 +00001067 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smith3fff44d2010-03-01 00:43:08 +00001068 def test_eintr_retry_call(self):
1069 record_calls = []
1070 def fake_os_func(*args):
1071 record_calls.append(args)
1072 if len(record_calls) == 2:
1073 raise OSError(errno.EINTR, "fake interrupted system call")
1074 return tuple(reversed(args))
1075
1076 self.assertEqual((999, 256),
1077 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1078 self.assertEqual([(256, 999)], record_calls)
1079 # This time there will be an EINTR so it will loop once.
1080 self.assertEqual((666,),
1081 subprocess._eintr_retry_call(fake_os_func, 666))
1082 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1083
1084unit_tests.append(HelperFunctionTests)
1085
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001086def test_main():
Georg Brandlae83d6e2009-08-13 09:04:31 +00001087 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +00001088 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001089
1090if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +00001091 test_main()