blob: 64fbe2189d8ffd166709d6b205c3ec00b07a9027 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003import subprocess
4import sys
5import signal
6import os
Gregory P. Smith3fff44d2010-03-01 00:43:08 +00007import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008import tempfile
9import time
Tim Peters3761e8d2004-10-13 04:07:12 +000010import re
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011
12mswindows = (sys.platform == "win32")
13
14#
15# Depends on the following external programs: Python
16#
17
18if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000019 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
20 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000021else:
22 SETBINARY = ''
23
Tim Peters3761e8d2004-10-13 04:07:12 +000024# In a debug build, stuff like "[6580 refs]" is printed to stderr at
25# shutdown time. That frustrates tests trying to check stderr produced
26# from a spawned Python process.
27def remove_stderr_debug_decorations(stderr):
Guido van Rossum98297ee2007-11-06 21:34:58 +000028 return re.sub("\[\d+ refs\]\r?\n?$", "", stderr.decode()).encode()
29 #return re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr)
Tim Peters3761e8d2004-10-13 04:07:12 +000030
Tim Golden595c8d32010-08-12 09:45:25 +000031class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000032 def setUp(self):
33 # Try to minimize the number of children we have so this test
34 # doesn't crash on some buildbots (Alphas in particular).
Benjamin Petersonee8712c2008-05-20 21:35:26 +000035 if hasattr(support, "reap_children"):
36 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000037
38 def tearDown(self):
39 # Try to minimize the number of children we have so this test
40 # doesn't crash on some buildbots (Alphas in particular).
Benjamin Petersonee8712c2008-05-20 21:35:26 +000041 if hasattr(support, "reap_children"):
42 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000043
Tim Golden595c8d32010-08-12 09:45:25 +000044 def mkstemp(self, *args, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000045 """wrapper for mkstemp, calling mktemp if mkstemp is not available"""
46 if hasattr(tempfile, "mkstemp"):
Tim Golden595c8d32010-08-12 09:45:25 +000047 return tempfile.mkstemp(*args, **kwargs)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000048 else:
Tim Golden595c8d32010-08-12 09:45:25 +000049 fname = tempfile.mktemp(*args, **kwargs)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000050 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
Tim Peterse718f612004-10-12 21:51:32 +000051
Tim Golden595c8d32010-08-12 09:45:25 +000052class ProcessTestCase(BaseTestCase):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000053 #
54 # Generic tests
55 #
56 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000057 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000058 rc = subprocess.call([sys.executable, "-c",
59 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000060 self.assertEqual(rc, 47)
61
Peter Astrand454f7672005-01-01 09:36:35 +000062 def test_check_call_zero(self):
63 # check_call() function with zero return code
64 rc = subprocess.check_call([sys.executable, "-c",
65 "import sys; sys.exit(0)"])
66 self.assertEqual(rc, 0)
67
68 def test_check_call_nonzero(self):
69 # check_call() function with non-zero return code
70 try:
71 subprocess.check_call([sys.executable, "-c",
72 "import sys; sys.exit(47)"])
Guido van Rossumb940e112007-01-10 16:19:56 +000073 except subprocess.CalledProcessError as e:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074 self.assertEqual(e.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000075 else:
76 self.fail("Expected CalledProcessError")
77
Georg Brandlf9734072008-12-07 15:30:06 +000078 def test_check_output(self):
79 # check_output() function with zero return code
80 output = subprocess.check_output(
81 [sys.executable, "-c", "print('BDFL')"])
82 self.assertTrue(b'BDFL' in output)
83
84 def test_check_output_nonzero(self):
85 # check_call() function with non-zero return code
86 try:
87 subprocess.check_output(
88 [sys.executable, "-c", "import sys; sys.exit(5)"])
89 except subprocess.CalledProcessError as e:
90 self.assertEqual(e.returncode, 5)
91 else:
92 self.fail("Expected CalledProcessError")
93
94 def test_check_output_stderr(self):
95 # check_output() function stderr redirected to stdout
96 output = subprocess.check_output(
97 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
98 stderr=subprocess.STDOUT)
99 self.assertTrue(b'BDFL' in output)
100
101 def test_check_output_stdout_arg(self):
102 # check_output() function stderr redirected to stdout
103 try:
104 output = subprocess.check_output(
105 [sys.executable, "-c", "print('will not be run')"],
106 stdout=sys.stdout)
107 except ValueError as e:
108 self.assertTrue('stdout' in e.args[0])
109 else:
110 self.fail("Expected ValueError when stdout arg supplied.")
111
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000112 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000113 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 newenv = os.environ.copy()
115 newenv["FRUIT"] = "banana"
116 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000117 'import sys, os;'
118 'sys.exit(os.getenv("FRUIT")=="banana")'],
119 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000120 self.assertEqual(rc, 1)
121
122 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000123 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000124 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000125 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
126 p.wait()
127 self.assertEqual(p.stdin, None)
128
129 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000130 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000131 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000132 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000133 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000134 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000135 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000136 p.wait()
137 self.assertEqual(p.stdout, None)
138
139 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000140 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000141 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000142 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
143 p.wait()
144 self.assertEqual(p.stderr, None)
145
146 def test_executable(self):
Antoine Pitrou55503652009-03-29 19:30:55 +0000147 arg0 = os.path.join(os.path.dirname(sys.executable),
148 "somethingyoudonthave")
149 p = subprocess.Popen([arg0, "-c", "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000150 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000151 p.wait()
152 self.assertEqual(p.returncode, 47)
153
154 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000155 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000156 p = subprocess.Popen([sys.executable, "-c",
157 'import sys; sys.exit(sys.stdin.read() == "pear")'],
158 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000159 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000160 p.stdin.close()
161 p.wait()
162 self.assertEqual(p.returncode, 1)
163
164 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000165 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000166 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000167 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000168 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000169 os.lseek(d, 0, 0)
170 p = subprocess.Popen([sys.executable, "-c",
171 'import sys; sys.exit(sys.stdin.read() == "pear")'],
172 stdin=d)
173 p.wait()
174 self.assertEqual(p.returncode, 1)
175
176 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000177 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000178 tf = tempfile.TemporaryFile()
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000179 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000180 tf.seek(0)
181 p = subprocess.Popen([sys.executable, "-c",
182 'import sys; sys.exit(sys.stdin.read() == "pear")'],
183 stdin=tf)
184 p.wait()
185 self.assertEqual(p.returncode, 1)
186
187 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000188 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 p = subprocess.Popen([sys.executable, "-c",
190 'import sys; sys.stdout.write("orange")'],
191 stdout=subprocess.PIPE)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000192 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000193
194 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000195 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000196 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000197 d = tf.fileno()
198 p = subprocess.Popen([sys.executable, "-c",
199 'import sys; sys.stdout.write("orange")'],
200 stdout=d)
201 p.wait()
202 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000203 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000204
205 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000206 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000207 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000208 p = subprocess.Popen([sys.executable, "-c",
209 'import sys; sys.stdout.write("orange")'],
210 stdout=tf)
211 p.wait()
212 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000213 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000214
215 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000216 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000217 p = subprocess.Popen([sys.executable, "-c",
218 'import sys; sys.stderr.write("strawberry")'],
219 stderr=subprocess.PIPE)
Tim Peters3761e8d2004-10-13 04:07:12 +0000220 self.assertEqual(remove_stderr_debug_decorations(p.stderr.read()),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000221 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000222
223 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000224 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000225 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000226 d = tf.fileno()
227 p = subprocess.Popen([sys.executable, "-c",
228 'import sys; sys.stderr.write("strawberry")'],
229 stderr=d)
230 p.wait()
231 os.lseek(d, 0, 0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000232 self.assertEqual(remove_stderr_debug_decorations(os.read(d, 1024)),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000233 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000234
235 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000236 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000237 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238 p = subprocess.Popen([sys.executable, "-c",
239 'import sys; sys.stderr.write("strawberry")'],
240 stderr=tf)
241 p.wait()
242 tf.seek(0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000243 self.assertEqual(remove_stderr_debug_decorations(tf.read()),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000244 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245
246 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000247 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000248 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000249 'import sys;'
250 'sys.stdout.write("apple");'
251 'sys.stdout.flush();'
252 'sys.stderr.write("orange")'],
253 stdout=subprocess.PIPE,
254 stderr=subprocess.STDOUT)
Tim Peters3761e8d2004-10-13 04:07:12 +0000255 output = p.stdout.read()
256 stripped = remove_stderr_debug_decorations(output)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000257 self.assertEqual(stripped, b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000258
259 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000260 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000261 tf = tempfile.TemporaryFile()
262 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000263 'import sys;'
264 'sys.stdout.write("apple");'
265 'sys.stdout.flush();'
266 'sys.stderr.write("orange")'],
267 stdout=tf,
268 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269 p.wait()
270 tf.seek(0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000271 output = tf.read()
272 stripped = remove_stderr_debug_decorations(output)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000273 self.assertEqual(stripped, b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274
Thomas Wouters89f507f2006-12-13 04:49:30 +0000275 def test_stdout_filedes_of_stdout(self):
276 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000277 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000278 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
279 self.assertEquals(rc, 2)
280
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000282 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000283 # We cannot use os.path.realpath to canonicalize the path,
284 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
285 cwd = os.getcwd()
286 os.chdir(tmpdir)
287 tmpdir = os.getcwd()
288 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000289 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000290 'import sys,os;'
291 'sys.stdout.write(os.getcwd())'],
292 stdout=subprocess.PIPE,
293 cwd=tmpdir)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000294 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000295 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
296 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000297
298 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000299 newenv = os.environ.copy()
300 newenv["FRUIT"] = "orange"
301 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000302 'import sys,os;'
303 'sys.stdout.write(os.getenv("FRUIT"))'],
304 stdout=subprocess.PIPE,
305 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000306 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000307
Peter Astrandcbac93c2005-03-03 20:24:28 +0000308 def test_communicate_stdin(self):
309 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000310 'import sys;'
311 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000312 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000313 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000314 self.assertEqual(p.returncode, 1)
315
316 def test_communicate_stdout(self):
317 p = subprocess.Popen([sys.executable, "-c",
318 'import sys; sys.stdout.write("pineapple")'],
319 stdout=subprocess.PIPE)
320 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000321 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000322 self.assertEqual(stderr, None)
323
324 def test_communicate_stderr(self):
325 p = subprocess.Popen([sys.executable, "-c",
326 'import sys; sys.stderr.write("pineapple")'],
327 stderr=subprocess.PIPE)
328 (stdout, stderr) = p.communicate()
329 self.assertEqual(stdout, None)
Brett Cannon653a5ad2005-03-05 06:40:52 +0000330 # When running with a pydebug build, the # of references is outputted
331 # to stderr, so just check if stderr at least started with "pinapple"
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000332 self.assertEqual(remove_stderr_debug_decorations(stderr), b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000333
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000335 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000336 'import sys,os;'
337 'sys.stderr.write("pineapple");'
338 'sys.stdout.write(sys.stdin.read())'],
339 stdin=subprocess.PIPE,
340 stdout=subprocess.PIPE,
341 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000342 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000343 self.assertEqual(stdout, b"banana")
Tim Peters3761e8d2004-10-13 04:07:12 +0000344 self.assertEqual(remove_stderr_debug_decorations(stderr),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000345 b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000346
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000347 # This test is Linux specific for simplicity to at least have
348 # some coverage. It is not a platform specific bug.
349 if os.path.isdir('/proc/%d/fd' % os.getpid()):
350 # Test for the fd leak reported in http://bugs.python.org/issue2791.
351 def test_communicate_pipe_fd_leak(self):
352 fd_directory = '/proc/%d/fd' % os.getpid()
353 num_fds_before_popen = len(os.listdir(fd_directory))
354 p = subprocess.Popen([sys.executable, '-c', 'print()'],
355 stdout=subprocess.PIPE)
356 p.communicate()
357 num_fds_after_communicate = len(os.listdir(fd_directory))
358 del p
359 num_fds_after_destruction = len(os.listdir(fd_directory))
360 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
361 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
362
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000363 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000364 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000365 p = subprocess.Popen([sys.executable, "-c",
366 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000367 (stdout, stderr) = p.communicate()
368 self.assertEqual(stdout, None)
369 self.assertEqual(stderr, None)
370
371 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000372 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000373 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000374 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000375 x, y = os.pipe()
376 if mswindows:
377 pipe_buf = 512
378 else:
379 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
380 os.close(x)
381 os.close(y)
382 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000383 'import sys,os;'
384 'sys.stdout.write(sys.stdin.read(47));'
385 'sys.stderr.write("xyz"*%d);'
386 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
387 stdin=subprocess.PIPE,
388 stdout=subprocess.PIPE,
389 stderr=subprocess.PIPE)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000390 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000391 (stdout, stderr) = p.communicate(string_to_write)
392 self.assertEqual(stdout, string_to_write)
393
394 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000395 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000396 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000397 'import sys,os;'
398 'sys.stdout.write(sys.stdin.read())'],
399 stdin=subprocess.PIPE,
400 stdout=subprocess.PIPE,
401 stderr=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000402 p.stdin.write(b"banana")
403 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000404 self.assertEqual(stdout, b"bananasplit")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000405 self.assertEqual(remove_stderr_debug_decorations(stderr), b"")
Tim Peterse718f612004-10-12 21:51:32 +0000406
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000407 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000408 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000409 'import sys,os;' + SETBINARY +
410 'sys.stdout.write("line1\\n");'
411 'sys.stdout.flush();'
412 'sys.stdout.write("line2\\n");'
413 'sys.stdout.flush();'
414 'sys.stdout.write("line3\\r\\n");'
415 'sys.stdout.flush();'
416 'sys.stdout.write("line4\\r");'
417 'sys.stdout.flush();'
418 'sys.stdout.write("\\nline5");'
419 'sys.stdout.flush();'
420 'sys.stdout.write("\\nline6");'],
421 stdout=subprocess.PIPE,
422 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000424 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000425
426 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000427 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000428 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000429 'import sys,os;' + SETBINARY +
430 'sys.stdout.write("line1\\n");'
431 'sys.stdout.flush();'
432 'sys.stdout.write("line2\\n");'
433 'sys.stdout.flush();'
434 'sys.stdout.write("line3\\r\\n");'
435 'sys.stdout.flush();'
436 'sys.stdout.write("line4\\r");'
437 'sys.stdout.flush();'
438 'sys.stdout.write("\\nline5");'
439 'sys.stdout.flush();'
440 'sys.stdout.write("\\nline6");'],
441 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
442 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000443 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000444 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000445
446 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000447 # Make sure we leak no resources
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000448 if (not hasattr(support, "is_resource_enabled") or
449 support.is_resource_enabled("subprocess") and not mswindows):
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000450 max_handles = 1026 # too much for most UNIX systems
451 else:
Tim Peterseba28be2005-03-28 01:08:02 +0000452 max_handles = 65
Fredrik Lundh9e29fc52004-10-13 07:54:54 +0000453 for i in range(max_handles):
Tim Peters3b01a702004-10-12 22:19:32 +0000454 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000455 "import sys;"
456 "sys.stdout.write(sys.stdin.read())"],
457 stdin=subprocess.PIPE,
458 stdout=subprocess.PIPE,
459 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000460 data = p.communicate(b"lime")[0]
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000461 self.assertEqual(data, b"lime")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000462
463
464 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000465 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
466 '"a b c" d e')
467 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
468 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000469 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
470 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
472 'a\\\\\\b "de fg" h')
473 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
474 'a\\\\\\"b c d')
475 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
476 '"a\\\\b c" d e')
477 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
478 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000479 self.assertEqual(subprocess.list2cmdline(['ab', '']),
480 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481
482
483 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000485 "-c", "import time; time.sleep(1)"])
486 count = 0
487 while p.poll() is None:
488 time.sleep(0.1)
489 count += 1
490 # We expect that the poll loop probably went around about 10 times,
491 # but, based on system scheduling we can't control, it's possible
492 # poll() never returned None. It "should be" very rare that it
493 # didn't go around at least twice.
Georg Brandlab91fde2009-08-13 08:51:18 +0000494 self.assertTrue(count >= 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495 # Subsequent invocations should just return the returncode
496 self.assertEqual(p.poll(), 0)
497
498
499 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500 p = subprocess.Popen([sys.executable,
501 "-c", "import time; time.sleep(2)"])
502 self.assertEqual(p.wait(), 0)
503 # Subsequent invocations should just return the returncode
504 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000505
Peter Astrand738131d2004-11-30 21:04:45 +0000506
507 def test_invalid_bufsize(self):
508 # an invalid type of the bufsize argument should raise
509 # TypeError.
510 try:
511 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
512 except TypeError:
513 pass
514 else:
515 self.fail("Expected TypeError")
516
Guido van Rossum46a05a72007-06-07 21:56:45 +0000517 def test_bufsize_is_none(self):
518 # bufsize=None should be the same as bufsize=0.
519 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
520 self.assertEqual(p.wait(), 0)
521 # Again with keyword arg
522 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
523 self.assertEqual(p.wait(), 0)
524
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000525 def test_leaking_fds_on_error(self):
526 # see bug #5179: Popen leaks file descriptors to PIPEs if
527 # the child fails to execute; this will eventually exhaust
528 # the maximum number of open fds. 1024 seems a very common
529 # value for that limit, but Windows has 2048, so we loop
530 # 1024 times (each call leaked two fds).
531 for i in range(1024):
532 try:
533 subprocess.Popen(['nonexisting_i_hope'],
534 stdout=subprocess.PIPE,
535 stderr=subprocess.PIPE)
536 # Windows raises IOError
537 except (IOError, OSError) as err:
538 if err.errno != 2: # ignore "no such file"
Benjamin Peterson4b068192009-02-20 03:19:25 +0000539 raise
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000540
Victor Stinner86c73bf2010-05-21 20:39:17 +0000541 def test_issue8780(self):
542 # Ensure that stdout is inherited from the parent
543 # if stdout=PIPE is not used
544 code = ';'.join((
545 'import subprocess, sys',
546 'retcode = subprocess.call('
547 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
548 'assert retcode == 0'))
549 output = subprocess.check_output([sys.executable, '-c', code])
550 self.assert_(output.startswith(b'Hello World!'), ascii(output))
551
Tim Golden40b37442010-08-06 13:20:12 +0000552 def test_handles_closed_on_exception(self):
553 # If CreateProcess exits with an error, ensure the
554 # duplicate output handles are released
555 ifhandle, ifname = self.mkstemp()
556 ofhandle, ofname = self.mkstemp()
557 efhandle, efname = self.mkstemp()
558 try:
559 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
560 stderr=efhandle)
561 except OSError:
562 os.close(ifhandle)
563 os.remove(ifname)
564 os.close(ofhandle)
565 os.remove(ofname)
566 os.close(efhandle)
567 os.remove(efname)
568 self.assertFalse(os.path.exists(ifname))
569 self.assertFalse(os.path.exists(ofname))
570 self.assertFalse(os.path.exists(efname))
571
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000572 #
573 # POSIX tests
574 #
575 if not mswindows:
576 def test_exceptions(self):
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000577 # caught & re-raised exceptions
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578 try:
579 p = subprocess.Popen([sys.executable, "-c", ""],
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000580 cwd="/this/path/does/not/exist")
Guido van Rossumb940e112007-01-10 16:19:56 +0000581 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000582 # The attribute child_traceback should contain "os.chdir"
583 # somewhere.
584 self.assertNotEqual(e.child_traceback.find("os.chdir"), -1)
585 else:
586 self.fail("Expected OSError")
Tim Peterse718f612004-10-12 21:51:32 +0000587
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000588 def _suppress_core_files(self):
589 """Try to prevent core files from being created.
590 Returns previous ulimit if successful, else None.
591 """
Ronald Oussorend7eb3a82010-07-23 10:35:20 +0000592 if sys.platform == 'darwin':
593 # Check if the 'Crash Reporter' on OSX was configured
594 # in 'Developer' mode and warn that it will get triggered
595 # when it is.
596 #
597 # This assumes that this context manager is used in tests
598 # that might trigger the next manager.
599 value = subprocess.Popen(['/usr/bin/defaults', 'read',
600 'com.apple.CrashReporter', 'DialogType'],
601 stdout=subprocess.PIPE).communicate()[0]
602 if value.strip() == b'developer':
603 print("this tests triggers the Crash Reporter, "
604 "that is intentional", end='')
605 sys.stdout.flush()
606
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000607 try:
608 import resource
609 old_limit = resource.getrlimit(resource.RLIMIT_CORE)
610 resource.setrlimit(resource.RLIMIT_CORE, (0,0))
611 return old_limit
612 except (ImportError, ValueError, resource.error):
613 return None
614
Ronald Oussorend7eb3a82010-07-23 10:35:20 +0000615
616
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000617 def _unsuppress_core_files(self, old_limit):
618 """Return core file behavior to default."""
619 if old_limit is None:
620 return
621 try:
622 import resource
623 resource.setrlimit(resource.RLIMIT_CORE, old_limit)
624 except (ImportError, ValueError, resource.error):
625 return
626
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000627 def test_run_abort(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000628 # returncode handles signal termination
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000629 old_limit = self._suppress_core_files()
630 try:
631 p = subprocess.Popen([sys.executable,
632 "-c", "import os; os.abort()"])
633 finally:
634 self._unsuppress_core_files(old_limit)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000635 p.wait()
636 self.assertEqual(-p.returncode, signal.SIGABRT)
637
638 def test_preexec(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000639 # preexec function
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000640 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000641 'import sys,os;'
642 'sys.stdout.write(os.getenv("FRUIT"))'],
643 stdout=subprocess.PIPE,
644 preexec_fn=lambda: os.putenv("FRUIT",
645 "apple"))
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000646 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000648 def test_args_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000649 # args is a string
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000650 fd, fname = self.mkstemp()
651 # reopen in text mode
652 with open(fd, "w") as fobj:
653 fobj.write("#!/bin/sh\n")
654 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
655 sys.executable)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000656 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000657 p = subprocess.Popen(fname)
658 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659 os.remove(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000660 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000661
662 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000663 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000664 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000665 [sys.executable,
666 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000667 startupinfo=47)
668 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000669 [sys.executable,
670 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000671 creationflags=47)
672
673 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000674 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000675 newenv = os.environ.copy()
676 newenv["FRUIT"] = "apple"
677 p = subprocess.Popen(["echo $FRUIT"], shell=1,
678 stdout=subprocess.PIPE,
679 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000680 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000681
682 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000683 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000684 newenv = os.environ.copy()
685 newenv["FRUIT"] = "apple"
686 p = subprocess.Popen("echo $FRUIT", shell=1,
687 stdout=subprocess.PIPE,
688 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000689 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000690
691 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000692 # call() function with string argument on UNIX
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000693 fd, fname = self.mkstemp()
694 # reopen in text mode
695 with open(fd, "w") as fobj:
696 fobj.write("#!/bin/sh\n")
697 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
698 sys.executable)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000699 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000700 rc = subprocess.call(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000701 os.remove(fname)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000702 self.assertEqual(rc, 47)
703
Stefan Krah8db99c82010-07-19 14:39:36 +0000704 def test_specific_shell(self):
705 # Issue #9265: Incorrect name passed as arg[0].
706 shells = []
707 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
708 for name in ['bash', 'ksh']:
709 sh = os.path.join(prefix, name)
710 if os.path.isfile(sh):
711 shells.append(sh)
712 if not shells: # Will probably work for any shell but csh.
713 self.skipTest("bash or ksh required for this test")
714 sh = '/bin/sh'
715 if os.path.isfile(sh) and not os.path.islink(sh):
716 # Test will fail if /bin/sh is a symlink to csh.
717 shells.append(sh)
718 for sh in shells:
719 p = subprocess.Popen("echo $0", executable=sh, shell=True,
720 stdout=subprocess.PIPE)
721 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
722
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000723 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000724 p = subprocess.Popen([sys.executable,
725 "-c", "input()"])
726
Georg Brandlab91fde2009-08-13 08:51:18 +0000727 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000728 p.send_signal(signal.SIGINT)
729 self.assertNotEqual(p.wait(), 0)
730
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000731 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000732 p = subprocess.Popen([sys.executable,
733 "-c", "input()"])
734
Georg Brandlab91fde2009-08-13 08:51:18 +0000735 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000736 p.kill()
737 self.assertEqual(p.wait(), -signal.SIGKILL)
738
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000739 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000740 p = subprocess.Popen([sys.executable,
741 "-c", "input()"])
742
Georg Brandlab91fde2009-08-13 08:51:18 +0000743 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000744 p.terminate()
745 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000746
Victor Stinner097d1b72010-04-27 18:29:45 +0000747 def test_undecodable_env(self):
748 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
749 value_repr = repr(value).encode("ascii")
750
751 # test str with surrogates
752 script = "import os; print(repr(os.getenv(%s)))" % repr(key)
753 env = os.environ.copy()
754 env[key] = value
755 stdout = subprocess.check_output(
756 [sys.executable, "-c", script],
757 env=env)
758 stdout = stdout.rstrip(b'\n\r')
759 self.assertEquals(stdout, value_repr)
760
761 # test bytes
762 key = key.encode("ascii", "surrogateescape")
763 value = value.encode("ascii", "surrogateescape")
764 script = "import os; print(repr(os.getenv(%s)))" % repr(key)
765 env = os.environ.copy()
766 env[key] = value
767 stdout = subprocess.check_output(
768 [sys.executable, "-c", script],
769 env=env)
770 stdout = stdout.rstrip(b'\n\r')
771 self.assertEquals(stdout, value_repr)
772
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000773 #
774 # Windows tests
775 #
776 if mswindows:
777 def test_startupinfo(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000778 # startupinfo argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000779 # We uses hardcoded constants, because we do not want to
Tim Peterse718f612004-10-12 21:51:32 +0000780 # depend on win32all.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000781 STARTF_USESHOWWINDOW = 1
782 SW_MAXIMIZE = 3
783 startupinfo = subprocess.STARTUPINFO()
784 startupinfo.dwFlags = STARTF_USESHOWWINDOW
785 startupinfo.wShowWindow = SW_MAXIMIZE
786 # Since Python is a console process, it won't be affected
787 # by wShowWindow, but the argument should be silently
788 # ignored
789 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
790 startupinfo=startupinfo)
791
792 def test_creationflags(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000793 # creationflags argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000794 CREATE_NEW_CONSOLE = 16
Tim Peters876c4322004-10-13 03:21:35 +0000795 sys.stderr.write(" a DOS box should flash briefly ...\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000796 subprocess.call(sys.executable +
Tim Peters876c4322004-10-13 03:21:35 +0000797 ' -c "import time; time.sleep(0.25)"',
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000798 creationflags=CREATE_NEW_CONSOLE)
799
800 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000801 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000802 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000803 [sys.executable,
804 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000805 preexec_fn=lambda: 1)
806 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000807 [sys.executable,
808 "-c", "import sys; sys.exit(47)"],
Guido van Rossume7ba4952007-06-06 23:52:48 +0000809 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000810 close_fds=True)
811
Guido van Rossume7ba4952007-06-06 23:52:48 +0000812 def test_close_fds(self):
813 # close file descriptors
814 rc = subprocess.call([sys.executable, "-c",
815 "import sys; sys.exit(47)"],
816 close_fds=True)
817 self.assertEqual(rc, 47)
818
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000819 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000820 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000821 newenv = os.environ.copy()
822 newenv["FRUIT"] = "physalis"
823 p = subprocess.Popen(["set"], shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000824 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000825 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000826 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000827
828 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000829 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000830 newenv = os.environ.copy()
831 newenv["FRUIT"] = "physalis"
832 p = subprocess.Popen("set", shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000833 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000834 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000835 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000836
837 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000838 # call() function with string argument on Windows
Tim Peters3b01a702004-10-12 22:19:32 +0000839 rc = subprocess.call(sys.executable +
840 ' -c "import sys; sys.exit(47)"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000841 self.assertEqual(rc, 47)
842
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000843 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000844 p = subprocess.Popen([sys.executable,
845 "-c", "input()"])
846
Georg Brandlab91fde2009-08-13 08:51:18 +0000847 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000848 p.send_signal(signal.SIGTERM)
849 self.assertNotEqual(p.wait(), 0)
850
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000851 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000852 p = subprocess.Popen([sys.executable,
853 "-c", "input()"])
854
Georg Brandlab91fde2009-08-13 08:51:18 +0000855 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000856 p.kill()
857 self.assertNotEqual(p.wait(), 0)
858
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000859 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000860 p = subprocess.Popen([sys.executable,
861 "-c", "input()"])
862
Georg Brandlab91fde2009-08-13 08:51:18 +0000863 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000864 p.terminate()
865 self.assertNotEqual(p.wait(), 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000866
Tim Golden595c8d32010-08-12 09:45:25 +0000867
Brett Cannona23810f2008-05-26 19:04:21 +0000868class CommandTests(unittest.TestCase):
869# The module says:
870# "NB This only works (and is only relevant) for UNIX."
871#
872# Actually, getoutput should work on any platform with an os.popen, but
873# I'll take the comment as given, and skip this suite.
874 if os.name == 'posix':
875
876 def test_getoutput(self):
877 self.assertEquals(subprocess.getoutput('echo xyzzy'), 'xyzzy')
878 self.assertEquals(subprocess.getstatusoutput('echo xyzzy'),
879 (0, 'xyzzy'))
880
881 # we use mkdtemp in the next line to create an empty directory
882 # under our exclusive control; from that, we can invent a pathname
883 # that we _know_ won't exist. This is guaranteed to fail.
884 dir = None
885 try:
886 dir = tempfile.mkdtemp()
887 name = os.path.join(dir, "foo")
888
889 status, output = subprocess.getstatusoutput('cat ' + name)
890 self.assertNotEquals(status, 0)
891 finally:
892 if dir is not None:
893 os.rmdir(dir)
894
Georg Brandlae83d6e2009-08-13 09:04:31 +0000895
896unit_tests = [ProcessTestCase, CommandTests]
897
Tim Golden595c8d32010-08-12 09:45:25 +0000898if mswindows:
899 class CommandsWithSpaces (BaseTestCase):
900
901 def setUp(self):
902 super().setUp()
903 f, fname = self.mkstemp(".py", "te st")
904 self.fname = fname.lower ()
905 os.write(f, b"import sys;"
906 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
907 )
908 os.close(f)
909
910 def tearDown(self):
911 os.remove(self.fname)
912 super().tearDown()
913
914 def with_spaces(self, *args, **kwargs):
915 kwargs['stdout'] = subprocess.PIPE
916 p = subprocess.Popen(*args, **kwargs)
917 self.assertEqual(
918 p.stdout.read ().decode("mbcs"),
919 "2 [%r, 'ab cd']" % self.fname
920 )
921
922 def test_shell_string_with_spaces(self):
923 # call() function with string argument with spaces on Windows
Brian Curtinf263c052010-08-13 20:59:27 +0000924 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
925 "ab cd"), shell=1)
Tim Golden595c8d32010-08-12 09:45:25 +0000926
927 def test_shell_sequence_with_spaces(self):
928 # call() function with sequence argument with spaces on Windows
Brian Curtinf263c052010-08-13 20:59:27 +0000929 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden595c8d32010-08-12 09:45:25 +0000930
931 def test_noshell_string_with_spaces(self):
932 # call() function with string argument with spaces on Windows
933 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
934 "ab cd"))
935
936 def test_noshell_sequence_with_spaces(self):
937 # call() function with sequence argument with spaces on Windows
938 self.with_spaces([sys.executable, self.fname, "ab cd"])
939
940 unit_tests.append(CommandsWithSpaces)
941
942
Gregory P. Smith10d29522009-08-13 18:33:30 +0000943if getattr(subprocess, '_has_poll', False):
Georg Brandlae83d6e2009-08-13 09:04:31 +0000944 class ProcessTestCaseNoPoll(ProcessTestCase):
945 def setUp(self):
946 subprocess._has_poll = False
947 ProcessTestCase.setUp(self)
948
949 def tearDown(self):
950 subprocess._has_poll = True
951 ProcessTestCase.tearDown(self)
952
953 unit_tests.append(ProcessTestCaseNoPoll)
954
955
Gregory P. Smith3fff44d2010-03-01 00:43:08 +0000956class HelperFunctionTests(unittest.TestCase):
Gregory P. Smith5cab2812010-03-01 02:58:43 +0000957 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smith3fff44d2010-03-01 00:43:08 +0000958 def test_eintr_retry_call(self):
959 record_calls = []
960 def fake_os_func(*args):
961 record_calls.append(args)
962 if len(record_calls) == 2:
963 raise OSError(errno.EINTR, "fake interrupted system call")
964 return tuple(reversed(args))
965
966 self.assertEqual((999, 256),
967 subprocess._eintr_retry_call(fake_os_func, 256, 999))
968 self.assertEqual([(256, 999)], record_calls)
969 # This time there will be an EINTR so it will loop once.
970 self.assertEqual((666,),
971 subprocess._eintr_retry_call(fake_os_func, 666))
972 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
973
974unit_tests.append(HelperFunctionTests)
975
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000976def test_main():
Georg Brandlae83d6e2009-08-13 09:04:31 +0000977 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +0000978 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000979
980if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +0000981 test_main()