blob: 552b9f220d27fa373a930dd57f5246ba1ac4256d [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
Antoine Pitrou6fab1f62010-09-18 22:40:56 +0000448 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000449 max_handles = 1026 # too much for most UNIX systems
450 else:
Antoine Pitrou6fab1f62010-09-18 22:40:56 +0000451 max_handles = 2050 # too much for (at least some) Windows setups
452 handles = []
453 try:
454 for i in range(max_handles):
455 try:
456 handles.append(os.open(support.TESTFN,
457 os.O_WRONLY | os.O_CREAT))
458 except OSError as e:
459 if e.errno != errno.EMFILE:
460 raise
461 break
462 else:
463 self.skipTest("failed to reach the file descriptor limit "
464 "(tried %d)" % max_handles)
465 # Close a couple of them (should be enough for a subprocess)
466 for i in range(10):
467 os.close(handles.pop())
468 # Loop creating some subprocesses. If one of them leaks some fds,
469 # the next loop iteration will fail by reaching the max fd limit.
470 for i in range(15):
471 p = subprocess.Popen([sys.executable, "-c",
472 "import sys;"
473 "sys.stdout.write(sys.stdin.read())"],
474 stdin=subprocess.PIPE,
475 stdout=subprocess.PIPE,
476 stderr=subprocess.PIPE)
477 data = p.communicate(b"lime")[0]
478 self.assertEqual(data, b"lime")
479 finally:
480 for h in handles:
481 os.close(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482
483 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
485 '"a b c" d e')
486 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
487 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000488 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
489 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
491 'a\\\\\\b "de fg" h')
492 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
493 'a\\\\\\"b c d')
494 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
495 '"a\\\\b c" d e')
496 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
497 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000498 self.assertEqual(subprocess.list2cmdline(['ab', '']),
499 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500
501
502 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000503 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000504 "-c", "import time; time.sleep(1)"])
505 count = 0
506 while p.poll() is None:
507 time.sleep(0.1)
508 count += 1
509 # We expect that the poll loop probably went around about 10 times,
510 # but, based on system scheduling we can't control, it's possible
511 # poll() never returned None. It "should be" very rare that it
512 # didn't go around at least twice.
Georg Brandlab91fde2009-08-13 08:51:18 +0000513 self.assertTrue(count >= 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514 # Subsequent invocations should just return the returncode
515 self.assertEqual(p.poll(), 0)
516
517
518 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000519 p = subprocess.Popen([sys.executable,
520 "-c", "import time; time.sleep(2)"])
521 self.assertEqual(p.wait(), 0)
522 # Subsequent invocations should just return the returncode
523 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000524
Peter Astrand738131d2004-11-30 21:04:45 +0000525
526 def test_invalid_bufsize(self):
527 # an invalid type of the bufsize argument should raise
528 # TypeError.
529 try:
530 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
531 except TypeError:
532 pass
533 else:
534 self.fail("Expected TypeError")
535
Guido van Rossum46a05a72007-06-07 21:56:45 +0000536 def test_bufsize_is_none(self):
537 # bufsize=None should be the same as bufsize=0.
538 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
539 self.assertEqual(p.wait(), 0)
540 # Again with keyword arg
541 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
542 self.assertEqual(p.wait(), 0)
543
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000544 def test_leaking_fds_on_error(self):
545 # see bug #5179: Popen leaks file descriptors to PIPEs if
546 # the child fails to execute; this will eventually exhaust
547 # the maximum number of open fds. 1024 seems a very common
548 # value for that limit, but Windows has 2048, so we loop
549 # 1024 times (each call leaked two fds).
550 for i in range(1024):
551 try:
552 subprocess.Popen(['nonexisting_i_hope'],
553 stdout=subprocess.PIPE,
554 stderr=subprocess.PIPE)
555 # Windows raises IOError
556 except (IOError, OSError) as err:
Antoine Pitrouf61045f2010-09-18 18:16:39 +0000557 if err.errno != errno.ENOENT: # ignore "no such file"
Benjamin Peterson4b068192009-02-20 03:19:25 +0000558 raise
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000559
Victor Stinner86c73bf2010-05-21 20:39:17 +0000560 def test_issue8780(self):
561 # Ensure that stdout is inherited from the parent
562 # if stdout=PIPE is not used
563 code = ';'.join((
564 'import subprocess, sys',
565 'retcode = subprocess.call('
566 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
567 'assert retcode == 0'))
568 output = subprocess.check_output([sys.executable, '-c', code])
569 self.assert_(output.startswith(b'Hello World!'), ascii(output))
570
Tim Golden40b37442010-08-06 13:20:12 +0000571 def test_handles_closed_on_exception(self):
572 # If CreateProcess exits with an error, ensure the
573 # duplicate output handles are released
574 ifhandle, ifname = self.mkstemp()
575 ofhandle, ofname = self.mkstemp()
576 efhandle, efname = self.mkstemp()
577 try:
578 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
579 stderr=efhandle)
580 except OSError:
581 os.close(ifhandle)
582 os.remove(ifname)
583 os.close(ofhandle)
584 os.remove(ofname)
585 os.close(efhandle)
586 os.remove(efname)
587 self.assertFalse(os.path.exists(ifname))
588 self.assertFalse(os.path.exists(ofname))
589 self.assertFalse(os.path.exists(efname))
590
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000591 #
592 # POSIX tests
593 #
594 if not mswindows:
595 def test_exceptions(self):
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000596 # caught & re-raised exceptions
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000597 try:
598 p = subprocess.Popen([sys.executable, "-c", ""],
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000599 cwd="/this/path/does/not/exist")
Guido van Rossumb940e112007-01-10 16:19:56 +0000600 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601 # The attribute child_traceback should contain "os.chdir"
602 # somewhere.
603 self.assertNotEqual(e.child_traceback.find("os.chdir"), -1)
604 else:
605 self.fail("Expected OSError")
Tim Peterse718f612004-10-12 21:51:32 +0000606
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000607 def _suppress_core_files(self):
608 """Try to prevent core files from being created.
609 Returns previous ulimit if successful, else None.
610 """
Ronald Oussorend7eb3a82010-07-23 10:35:20 +0000611 if sys.platform == 'darwin':
612 # Check if the 'Crash Reporter' on OSX was configured
613 # in 'Developer' mode and warn that it will get triggered
614 # when it is.
615 #
616 # This assumes that this context manager is used in tests
617 # that might trigger the next manager.
618 value = subprocess.Popen(['/usr/bin/defaults', 'read',
619 'com.apple.CrashReporter', 'DialogType'],
620 stdout=subprocess.PIPE).communicate()[0]
621 if value.strip() == b'developer':
622 print("this tests triggers the Crash Reporter, "
623 "that is intentional", end='')
624 sys.stdout.flush()
625
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000626 try:
627 import resource
628 old_limit = resource.getrlimit(resource.RLIMIT_CORE)
629 resource.setrlimit(resource.RLIMIT_CORE, (0,0))
630 return old_limit
631 except (ImportError, ValueError, resource.error):
632 return None
633
Ronald Oussorend7eb3a82010-07-23 10:35:20 +0000634
635
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000636 def _unsuppress_core_files(self, old_limit):
637 """Return core file behavior to default."""
638 if old_limit is None:
639 return
640 try:
641 import resource
642 resource.setrlimit(resource.RLIMIT_CORE, old_limit)
643 except (ImportError, ValueError, resource.error):
644 return
645
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646 def test_run_abort(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000647 # returncode handles signal termination
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000648 old_limit = self._suppress_core_files()
649 try:
650 p = subprocess.Popen([sys.executable,
651 "-c", "import os; os.abort()"])
652 finally:
653 self._unsuppress_core_files(old_limit)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000654 p.wait()
655 self.assertEqual(-p.returncode, signal.SIGABRT)
656
657 def test_preexec(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000658 # preexec function
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000660 'import sys,os;'
661 'sys.stdout.write(os.getenv("FRUIT"))'],
662 stdout=subprocess.PIPE,
663 preexec_fn=lambda: os.putenv("FRUIT",
664 "apple"))
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000665 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000666
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000667 def test_args_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000668 # args is a string
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000669 fd, fname = self.mkstemp()
670 # reopen in text mode
671 with open(fd, "w") as fobj:
672 fobj.write("#!/bin/sh\n")
673 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
674 sys.executable)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000675 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000676 p = subprocess.Popen(fname)
677 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000678 os.remove(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000679 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000680
681 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000682 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000683 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000684 [sys.executable,
685 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000686 startupinfo=47)
687 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 creationflags=47)
691
692 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000693 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000694 newenv = os.environ.copy()
695 newenv["FRUIT"] = "apple"
696 p = subprocess.Popen(["echo $FRUIT"], shell=1,
697 stdout=subprocess.PIPE,
698 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000699 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000700
701 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000702 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000703 newenv = os.environ.copy()
704 newenv["FRUIT"] = "apple"
705 p = subprocess.Popen("echo $FRUIT", shell=1,
706 stdout=subprocess.PIPE,
707 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000708 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000709
710 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000711 # call() function with string argument on UNIX
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000712 fd, fname = self.mkstemp()
713 # reopen in text mode
714 with open(fd, "w") as fobj:
715 fobj.write("#!/bin/sh\n")
716 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
717 sys.executable)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000718 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000719 rc = subprocess.call(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000720 os.remove(fname)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000721 self.assertEqual(rc, 47)
722
Stefan Krah8db99c82010-07-19 14:39:36 +0000723 def test_specific_shell(self):
724 # Issue #9265: Incorrect name passed as arg[0].
725 shells = []
726 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
727 for name in ['bash', 'ksh']:
728 sh = os.path.join(prefix, name)
729 if os.path.isfile(sh):
730 shells.append(sh)
731 if not shells: # Will probably work for any shell but csh.
732 self.skipTest("bash or ksh required for this test")
733 sh = '/bin/sh'
734 if os.path.isfile(sh) and not os.path.islink(sh):
735 # Test will fail if /bin/sh is a symlink to csh.
736 shells.append(sh)
737 for sh in shells:
738 p = subprocess.Popen("echo $0", executable=sh, shell=True,
739 stdout=subprocess.PIPE)
740 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
741
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000742 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000743 p = subprocess.Popen([sys.executable,
744 "-c", "input()"])
745
Georg Brandlab91fde2009-08-13 08:51:18 +0000746 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000747 p.send_signal(signal.SIGINT)
748 self.assertNotEqual(p.wait(), 0)
749
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000750 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000751 p = subprocess.Popen([sys.executable,
752 "-c", "input()"])
753
Georg Brandlab91fde2009-08-13 08:51:18 +0000754 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000755 p.kill()
756 self.assertEqual(p.wait(), -signal.SIGKILL)
757
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000758 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000759 p = subprocess.Popen([sys.executable,
760 "-c", "input()"])
761
Georg Brandlab91fde2009-08-13 08:51:18 +0000762 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000763 p.terminate()
764 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000765
Victor Stinner097d1b72010-04-27 18:29:45 +0000766 def test_undecodable_env(self):
767 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
768 value_repr = repr(value).encode("ascii")
769
770 # test str with surrogates
771 script = "import os; print(repr(os.getenv(%s)))" % repr(key)
772 env = os.environ.copy()
773 env[key] = value
774 stdout = subprocess.check_output(
775 [sys.executable, "-c", script],
776 env=env)
777 stdout = stdout.rstrip(b'\n\r')
778 self.assertEquals(stdout, value_repr)
779
780 # test bytes
781 key = key.encode("ascii", "surrogateescape")
782 value = value.encode("ascii", "surrogateescape")
783 script = "import os; print(repr(os.getenv(%s)))" % repr(key)
784 env = os.environ.copy()
785 env[key] = value
786 stdout = subprocess.check_output(
787 [sys.executable, "-c", script],
788 env=env)
789 stdout = stdout.rstrip(b'\n\r')
790 self.assertEquals(stdout, value_repr)
791
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000792 #
793 # Windows tests
794 #
795 if mswindows:
796 def test_startupinfo(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000797 # startupinfo argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000798 # We uses hardcoded constants, because we do not want to
Tim Peterse718f612004-10-12 21:51:32 +0000799 # depend on win32all.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000800 STARTF_USESHOWWINDOW = 1
801 SW_MAXIMIZE = 3
802 startupinfo = subprocess.STARTUPINFO()
803 startupinfo.dwFlags = STARTF_USESHOWWINDOW
804 startupinfo.wShowWindow = SW_MAXIMIZE
805 # Since Python is a console process, it won't be affected
806 # by wShowWindow, but the argument should be silently
807 # ignored
808 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
809 startupinfo=startupinfo)
810
811 def test_creationflags(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000812 # creationflags argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000813 CREATE_NEW_CONSOLE = 16
Tim Peters876c4322004-10-13 03:21:35 +0000814 sys.stderr.write(" a DOS box should flash briefly ...\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000815 subprocess.call(sys.executable +
Tim Peters876c4322004-10-13 03:21:35 +0000816 ' -c "import time; time.sleep(0.25)"',
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000817 creationflags=CREATE_NEW_CONSOLE)
818
819 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000820 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000821 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000822 [sys.executable,
823 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000824 preexec_fn=lambda: 1)
825 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000826 [sys.executable,
827 "-c", "import sys; sys.exit(47)"],
Guido van Rossume7ba4952007-06-06 23:52:48 +0000828 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000829 close_fds=True)
830
Guido van Rossume7ba4952007-06-06 23:52:48 +0000831 def test_close_fds(self):
832 # close file descriptors
833 rc = subprocess.call([sys.executable, "-c",
834 "import sys; sys.exit(47)"],
835 close_fds=True)
836 self.assertEqual(rc, 47)
837
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000838 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000839 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000840 newenv = os.environ.copy()
841 newenv["FRUIT"] = "physalis"
842 p = subprocess.Popen(["set"], shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000843 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000844 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000845 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000846
847 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000848 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 newenv = os.environ.copy()
850 newenv["FRUIT"] = "physalis"
851 p = subprocess.Popen("set", shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000852 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000853 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000854 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855
856 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000857 # call() function with string argument on Windows
Tim Peters3b01a702004-10-12 22:19:32 +0000858 rc = subprocess.call(sys.executable +
859 ' -c "import sys; sys.exit(47)"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000860 self.assertEqual(rc, 47)
861
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000862 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000863 p = subprocess.Popen([sys.executable,
864 "-c", "input()"])
865
Georg Brandlab91fde2009-08-13 08:51:18 +0000866 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000867 p.send_signal(signal.SIGTERM)
868 self.assertNotEqual(p.wait(), 0)
869
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000870 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000871 p = subprocess.Popen([sys.executable,
872 "-c", "input()"])
873
Georg Brandlab91fde2009-08-13 08:51:18 +0000874 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000875 p.kill()
876 self.assertNotEqual(p.wait(), 0)
877
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000878 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000879 p = subprocess.Popen([sys.executable,
880 "-c", "input()"])
881
Georg Brandlab91fde2009-08-13 08:51:18 +0000882 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000883 p.terminate()
884 self.assertNotEqual(p.wait(), 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000885
Tim Golden595c8d32010-08-12 09:45:25 +0000886
Brett Cannona23810f2008-05-26 19:04:21 +0000887class CommandTests(unittest.TestCase):
888# The module says:
889# "NB This only works (and is only relevant) for UNIX."
890#
891# Actually, getoutput should work on any platform with an os.popen, but
892# I'll take the comment as given, and skip this suite.
893 if os.name == 'posix':
894
895 def test_getoutput(self):
896 self.assertEquals(subprocess.getoutput('echo xyzzy'), 'xyzzy')
897 self.assertEquals(subprocess.getstatusoutput('echo xyzzy'),
898 (0, 'xyzzy'))
899
900 # we use mkdtemp in the next line to create an empty directory
901 # under our exclusive control; from that, we can invent a pathname
902 # that we _know_ won't exist. This is guaranteed to fail.
903 dir = None
904 try:
905 dir = tempfile.mkdtemp()
906 name = os.path.join(dir, "foo")
907
908 status, output = subprocess.getstatusoutput('cat ' + name)
909 self.assertNotEquals(status, 0)
910 finally:
911 if dir is not None:
912 os.rmdir(dir)
913
Georg Brandlae83d6e2009-08-13 09:04:31 +0000914
915unit_tests = [ProcessTestCase, CommandTests]
916
Tim Golden595c8d32010-08-12 09:45:25 +0000917if mswindows:
918 class CommandsWithSpaces (BaseTestCase):
919
920 def setUp(self):
921 super().setUp()
922 f, fname = self.mkstemp(".py", "te st")
923 self.fname = fname.lower ()
924 os.write(f, b"import sys;"
925 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
926 )
927 os.close(f)
928
929 def tearDown(self):
930 os.remove(self.fname)
931 super().tearDown()
932
933 def with_spaces(self, *args, **kwargs):
934 kwargs['stdout'] = subprocess.PIPE
935 p = subprocess.Popen(*args, **kwargs)
936 self.assertEqual(
937 p.stdout.read ().decode("mbcs"),
938 "2 [%r, 'ab cd']" % self.fname
939 )
940
941 def test_shell_string_with_spaces(self):
942 # call() function with string argument with spaces on Windows
Brian Curtinf263c052010-08-13 20:59:27 +0000943 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
944 "ab cd"), shell=1)
Tim Golden595c8d32010-08-12 09:45:25 +0000945
946 def test_shell_sequence_with_spaces(self):
947 # call() function with sequence argument with spaces on Windows
Brian Curtinf263c052010-08-13 20:59:27 +0000948 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden595c8d32010-08-12 09:45:25 +0000949
950 def test_noshell_string_with_spaces(self):
951 # call() function with string argument with spaces on Windows
952 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
953 "ab cd"))
954
955 def test_noshell_sequence_with_spaces(self):
956 # call() function with sequence argument with spaces on Windows
957 self.with_spaces([sys.executable, self.fname, "ab cd"])
958
959 unit_tests.append(CommandsWithSpaces)
960
961
Gregory P. Smith10d29522009-08-13 18:33:30 +0000962if getattr(subprocess, '_has_poll', False):
Georg Brandlae83d6e2009-08-13 09:04:31 +0000963 class ProcessTestCaseNoPoll(ProcessTestCase):
964 def setUp(self):
965 subprocess._has_poll = False
966 ProcessTestCase.setUp(self)
967
968 def tearDown(self):
969 subprocess._has_poll = True
970 ProcessTestCase.tearDown(self)
971
972 unit_tests.append(ProcessTestCaseNoPoll)
973
974
Gregory P. Smith3fff44d2010-03-01 00:43:08 +0000975class HelperFunctionTests(unittest.TestCase):
Gregory P. Smith5cab2812010-03-01 02:58:43 +0000976 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smith3fff44d2010-03-01 00:43:08 +0000977 def test_eintr_retry_call(self):
978 record_calls = []
979 def fake_os_func(*args):
980 record_calls.append(args)
981 if len(record_calls) == 2:
982 raise OSError(errno.EINTR, "fake interrupted system call")
983 return tuple(reversed(args))
984
985 self.assertEqual((999, 256),
986 subprocess._eintr_retry_call(fake_os_func, 256, 999))
987 self.assertEqual([(256, 999)], record_calls)
988 # This time there will be an EINTR so it will loop once.
989 self.assertEqual((666,),
990 subprocess._eintr_retry_call(fake_os_func, 666))
991 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
992
993unit_tests.append(HelperFunctionTests)
994
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000995def test_main():
Georg Brandlae83d6e2009-08-13 09:04:31 +0000996 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +0000997 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000998
999if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +00001000 test_main()