blob: 7711293a3248e89dd45ce639f6080fa40e781fe0 [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
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000031class ProcessTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000032 def setUp(self):
33 # Try to minimize the number of children we have so this test
34 # doesn't crash on some buildbots (Alphas in particular).
Benjamin Petersonee8712c2008-05-20 21:35:26 +000035 if hasattr(support, "reap_children"):
36 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000037
38 def tearDown(self):
39 # Try to minimize the number of children we have so this test
40 # doesn't crash on some buildbots (Alphas in particular).
Benjamin Petersonee8712c2008-05-20 21:35:26 +000041 if hasattr(support, "reap_children"):
42 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000043
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000044 def mkstemp(self):
45 """wrapper for mkstemp, calling mktemp if mkstemp is not available"""
46 if hasattr(tempfile, "mkstemp"):
47 return tempfile.mkstemp()
48 else:
49 fname = tempfile.mktemp()
50 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
Tim Peterse718f612004-10-12 21:51:32 +000051
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000052 #
53 # Generic tests
54 #
55 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000056 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000057 rc = subprocess.call([sys.executable, "-c",
58 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000059 self.assertEqual(rc, 47)
60
Peter Astrand454f7672005-01-01 09:36:35 +000061 def test_check_call_zero(self):
62 # check_call() function with zero return code
63 rc = subprocess.check_call([sys.executable, "-c",
64 "import sys; sys.exit(0)"])
65 self.assertEqual(rc, 0)
66
67 def test_check_call_nonzero(self):
68 # check_call() function with non-zero return code
69 try:
70 subprocess.check_call([sys.executable, "-c",
71 "import sys; sys.exit(47)"])
Guido van Rossumb940e112007-01-10 16:19:56 +000072 except subprocess.CalledProcessError as e:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073 self.assertEqual(e.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000074 else:
75 self.fail("Expected CalledProcessError")
76
Georg Brandlf9734072008-12-07 15:30:06 +000077 def test_check_output(self):
78 # check_output() function with zero return code
79 output = subprocess.check_output(
80 [sys.executable, "-c", "print('BDFL')"])
81 self.assertTrue(b'BDFL' in output)
82
83 def test_check_output_nonzero(self):
84 # check_call() function with non-zero return code
85 try:
86 subprocess.check_output(
87 [sys.executable, "-c", "import sys; sys.exit(5)"])
88 except subprocess.CalledProcessError as e:
89 self.assertEqual(e.returncode, 5)
90 else:
91 self.fail("Expected CalledProcessError")
92
93 def test_check_output_stderr(self):
94 # check_output() function stderr redirected to stdout
95 output = subprocess.check_output(
96 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
97 stderr=subprocess.STDOUT)
98 self.assertTrue(b'BDFL' in output)
99
100 def test_check_output_stdout_arg(self):
101 # check_output() function stderr redirected to stdout
102 try:
103 output = subprocess.check_output(
104 [sys.executable, "-c", "print('will not be run')"],
105 stdout=sys.stdout)
106 except ValueError as e:
107 self.assertTrue('stdout' in e.args[0])
108 else:
109 self.fail("Expected ValueError when stdout arg supplied.")
110
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000111 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000112 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000113 newenv = os.environ.copy()
114 newenv["FRUIT"] = "banana"
115 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000116 'import sys, os;'
117 'sys.exit(os.getenv("FRUIT")=="banana")'],
118 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000119 self.assertEqual(rc, 1)
120
121 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000122 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000123 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000124 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
125 p.wait()
126 self.assertEqual(p.stdin, None)
127
128 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000129 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000130 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000131 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000132 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000133 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000134 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000135 p.wait()
136 self.assertEqual(p.stdout, None)
137
138 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000139 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000140 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000141 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
142 p.wait()
143 self.assertEqual(p.stderr, None)
144
145 def test_executable(self):
Antoine Pitrou55503652009-03-29 19:30:55 +0000146 arg0 = os.path.join(os.path.dirname(sys.executable),
147 "somethingyoudonthave")
148 p = subprocess.Popen([arg0, "-c", "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000149 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000150 p.wait()
151 self.assertEqual(p.returncode, 47)
152
153 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000154 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000155 p = subprocess.Popen([sys.executable, "-c",
156 'import sys; sys.exit(sys.stdin.read() == "pear")'],
157 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000158 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000159 p.stdin.close()
160 p.wait()
161 self.assertEqual(p.returncode, 1)
162
163 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000164 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000165 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000166 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000167 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000168 os.lseek(d, 0, 0)
169 p = subprocess.Popen([sys.executable, "-c",
170 'import sys; sys.exit(sys.stdin.read() == "pear")'],
171 stdin=d)
172 p.wait()
173 self.assertEqual(p.returncode, 1)
174
175 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000176 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000177 tf = tempfile.TemporaryFile()
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000178 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000179 tf.seek(0)
180 p = subprocess.Popen([sys.executable, "-c",
181 'import sys; sys.exit(sys.stdin.read() == "pear")'],
182 stdin=tf)
183 p.wait()
184 self.assertEqual(p.returncode, 1)
185
186 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000187 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000188 p = subprocess.Popen([sys.executable, "-c",
189 'import sys; sys.stdout.write("orange")'],
190 stdout=subprocess.PIPE)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000191 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000192
193 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000194 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000195 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000196 d = tf.fileno()
197 p = subprocess.Popen([sys.executable, "-c",
198 'import sys; sys.stdout.write("orange")'],
199 stdout=d)
200 p.wait()
201 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000202 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000203
204 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000205 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000206 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000207 p = subprocess.Popen([sys.executable, "-c",
208 'import sys; sys.stdout.write("orange")'],
209 stdout=tf)
210 p.wait()
211 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000212 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000213
214 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000215 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000216 p = subprocess.Popen([sys.executable, "-c",
217 'import sys; sys.stderr.write("strawberry")'],
218 stderr=subprocess.PIPE)
Tim Peters3761e8d2004-10-13 04:07:12 +0000219 self.assertEqual(remove_stderr_debug_decorations(p.stderr.read()),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000220 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000221
222 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000223 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000224 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000225 d = tf.fileno()
226 p = subprocess.Popen([sys.executable, "-c",
227 'import sys; sys.stderr.write("strawberry")'],
228 stderr=d)
229 p.wait()
230 os.lseek(d, 0, 0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000231 self.assertEqual(remove_stderr_debug_decorations(os.read(d, 1024)),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000232 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233
234 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000235 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000236 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000237 p = subprocess.Popen([sys.executable, "-c",
238 'import sys; sys.stderr.write("strawberry")'],
239 stderr=tf)
240 p.wait()
241 tf.seek(0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000242 self.assertEqual(remove_stderr_debug_decorations(tf.read()),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000243 b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244
245 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000246 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000248 'import sys;'
249 'sys.stdout.write("apple");'
250 'sys.stdout.flush();'
251 'sys.stderr.write("orange")'],
252 stdout=subprocess.PIPE,
253 stderr=subprocess.STDOUT)
Tim Peters3761e8d2004-10-13 04:07:12 +0000254 output = p.stdout.read()
255 stripped = remove_stderr_debug_decorations(output)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000256 self.assertEqual(stripped, b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000257
258 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000259 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000260 tf = tempfile.TemporaryFile()
261 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000262 'import sys;'
263 'sys.stdout.write("apple");'
264 'sys.stdout.flush();'
265 'sys.stderr.write("orange")'],
266 stdout=tf,
267 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268 p.wait()
269 tf.seek(0)
Tim Peters3761e8d2004-10-13 04:07:12 +0000270 output = tf.read()
271 stripped = remove_stderr_debug_decorations(output)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000272 self.assertEqual(stripped, b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000273
Thomas Wouters89f507f2006-12-13 04:49:30 +0000274 def test_stdout_filedes_of_stdout(self):
275 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000276 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000277 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
278 self.assertEquals(rc, 2)
279
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000280 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000281 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000282 # We cannot use os.path.realpath to canonicalize the path,
283 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
284 cwd = os.getcwd()
285 os.chdir(tmpdir)
286 tmpdir = os.getcwd()
287 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000288 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000289 'import sys,os;'
290 'sys.stdout.write(os.getcwd())'],
291 stdout=subprocess.PIPE,
292 cwd=tmpdir)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000293 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000294 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
295 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296
297 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298 newenv = os.environ.copy()
299 newenv["FRUIT"] = "orange"
300 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000301 'import sys,os;'
302 'sys.stdout.write(os.getenv("FRUIT"))'],
303 stdout=subprocess.PIPE,
304 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000305 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306
Peter Astrandcbac93c2005-03-03 20:24:28 +0000307 def test_communicate_stdin(self):
308 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000309 'import sys;'
310 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000311 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000312 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000313 self.assertEqual(p.returncode, 1)
314
315 def test_communicate_stdout(self):
316 p = subprocess.Popen([sys.executable, "-c",
317 'import sys; sys.stdout.write("pineapple")'],
318 stdout=subprocess.PIPE)
319 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000320 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000321 self.assertEqual(stderr, None)
322
323 def test_communicate_stderr(self):
324 p = subprocess.Popen([sys.executable, "-c",
325 'import sys; sys.stderr.write("pineapple")'],
326 stderr=subprocess.PIPE)
327 (stdout, stderr) = p.communicate()
328 self.assertEqual(stdout, None)
Brett Cannon653a5ad2005-03-05 06:40:52 +0000329 # When running with a pydebug build, the # of references is outputted
330 # to stderr, so just check if stderr at least started with "pinapple"
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000331 self.assertEqual(remove_stderr_debug_decorations(stderr), b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000332
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000333 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000335 'import sys,os;'
336 'sys.stderr.write("pineapple");'
337 'sys.stdout.write(sys.stdin.read())'],
338 stdin=subprocess.PIPE,
339 stdout=subprocess.PIPE,
340 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000341 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000342 self.assertEqual(stdout, b"banana")
Tim Peters3761e8d2004-10-13 04:07:12 +0000343 self.assertEqual(remove_stderr_debug_decorations(stderr),
Guido van Rossum98297ee2007-11-06 21:34:58 +0000344 b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000345
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000346 # This test is Linux specific for simplicity to at least have
347 # some coverage. It is not a platform specific bug.
348 if os.path.isdir('/proc/%d/fd' % os.getpid()):
349 # Test for the fd leak reported in http://bugs.python.org/issue2791.
350 def test_communicate_pipe_fd_leak(self):
351 fd_directory = '/proc/%d/fd' % os.getpid()
352 num_fds_before_popen = len(os.listdir(fd_directory))
353 p = subprocess.Popen([sys.executable, '-c', 'print()'],
354 stdout=subprocess.PIPE)
355 p.communicate()
356 num_fds_after_communicate = len(os.listdir(fd_directory))
357 del p
358 num_fds_after_destruction = len(os.listdir(fd_directory))
359 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
360 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
361
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000363 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000364 p = subprocess.Popen([sys.executable, "-c",
365 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000366 (stdout, stderr) = p.communicate()
367 self.assertEqual(stdout, None)
368 self.assertEqual(stderr, None)
369
370 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000371 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000372 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000373 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000374 x, y = os.pipe()
375 if mswindows:
376 pipe_buf = 512
377 else:
378 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
379 os.close(x)
380 os.close(y)
381 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000382 'import sys,os;'
383 'sys.stdout.write(sys.stdin.read(47));'
384 'sys.stderr.write("xyz"*%d);'
385 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
386 stdin=subprocess.PIPE,
387 stdout=subprocess.PIPE,
388 stderr=subprocess.PIPE)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000389 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390 (stdout, stderr) = p.communicate(string_to_write)
391 self.assertEqual(stdout, string_to_write)
392
393 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000394 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000395 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000396 'import sys,os;'
397 'sys.stdout.write(sys.stdin.read())'],
398 stdin=subprocess.PIPE,
399 stdout=subprocess.PIPE,
400 stderr=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000401 p.stdin.write(b"banana")
402 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000403 self.assertEqual(stdout, b"bananasplit")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000404 self.assertEqual(remove_stderr_debug_decorations(stderr), b"")
Tim Peterse718f612004-10-12 21:51:32 +0000405
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000406 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000407 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000408 'import sys,os;' + SETBINARY +
409 'sys.stdout.write("line1\\n");'
410 'sys.stdout.flush();'
411 'sys.stdout.write("line2\\n");'
412 'sys.stdout.flush();'
413 'sys.stdout.write("line3\\r\\n");'
414 'sys.stdout.flush();'
415 'sys.stdout.write("line4\\r");'
416 'sys.stdout.flush();'
417 'sys.stdout.write("\\nline5");'
418 'sys.stdout.flush();'
419 'sys.stdout.write("\\nline6");'],
420 stdout=subprocess.PIPE,
421 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000422 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000423 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424
425 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000426 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000427 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000428 'import sys,os;' + SETBINARY +
429 'sys.stdout.write("line1\\n");'
430 'sys.stdout.flush();'
431 'sys.stdout.write("line2\\n");'
432 'sys.stdout.flush();'
433 'sys.stdout.write("line3\\r\\n");'
434 'sys.stdout.flush();'
435 'sys.stdout.write("line4\\r");'
436 'sys.stdout.flush();'
437 'sys.stdout.write("\\nline5");'
438 'sys.stdout.flush();'
439 'sys.stdout.write("\\nline6");'],
440 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
441 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000442 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000443 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444
445 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000446 # Make sure we leak no resources
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000447 if (not hasattr(support, "is_resource_enabled") or
448 support.is_resource_enabled("subprocess") and not mswindows):
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000449 max_handles = 1026 # too much for most UNIX systems
450 else:
Tim Peterseba28be2005-03-28 01:08:02 +0000451 max_handles = 65
Fredrik Lundh9e29fc52004-10-13 07:54:54 +0000452 for i in range(max_handles):
Tim Peters3b01a702004-10-12 22:19:32 +0000453 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000454 "import sys;"
455 "sys.stdout.write(sys.stdin.read())"],
456 stdin=subprocess.PIPE,
457 stdout=subprocess.PIPE,
458 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000459 data = p.communicate(b"lime")[0]
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000460 self.assertEqual(data, b"lime")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000461
462
463 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
465 '"a b c" d e')
466 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
467 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000468 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
469 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
471 'a\\\\\\b "de fg" h')
472 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
473 'a\\\\\\"b c d')
474 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
475 '"a\\\\b c" d e')
476 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
477 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000478 self.assertEqual(subprocess.list2cmdline(['ab', '']),
479 'ab ""')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000480 self.assertEqual(subprocess.list2cmdline(['echo', 'foo|bar']),
481 'echo "foo|bar"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482
483
484 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000486 "-c", "import time; time.sleep(1)"])
487 count = 0
488 while p.poll() is None:
489 time.sleep(0.1)
490 count += 1
491 # We expect that the poll loop probably went around about 10 times,
492 # but, based on system scheduling we can't control, it's possible
493 # poll() never returned None. It "should be" very rare that it
494 # didn't go around at least twice.
Georg Brandlab91fde2009-08-13 08:51:18 +0000495 self.assertTrue(count >= 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000496 # Subsequent invocations should just return the returncode
497 self.assertEqual(p.poll(), 0)
498
499
500 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501 p = subprocess.Popen([sys.executable,
502 "-c", "import time; time.sleep(2)"])
503 self.assertEqual(p.wait(), 0)
504 # Subsequent invocations should just return the returncode
505 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000506
Peter Astrand738131d2004-11-30 21:04:45 +0000507
508 def test_invalid_bufsize(self):
509 # an invalid type of the bufsize argument should raise
510 # TypeError.
511 try:
512 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
513 except TypeError:
514 pass
515 else:
516 self.fail("Expected TypeError")
517
Guido van Rossum46a05a72007-06-07 21:56:45 +0000518 def test_bufsize_is_none(self):
519 # bufsize=None should be the same as bufsize=0.
520 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
521 self.assertEqual(p.wait(), 0)
522 # Again with keyword arg
523 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
524 self.assertEqual(p.wait(), 0)
525
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000526 def test_leaking_fds_on_error(self):
527 # see bug #5179: Popen leaks file descriptors to PIPEs if
528 # the child fails to execute; this will eventually exhaust
529 # the maximum number of open fds. 1024 seems a very common
530 # value for that limit, but Windows has 2048, so we loop
531 # 1024 times (each call leaked two fds).
532 for i in range(1024):
533 try:
534 subprocess.Popen(['nonexisting_i_hope'],
535 stdout=subprocess.PIPE,
536 stderr=subprocess.PIPE)
537 # Windows raises IOError
538 except (IOError, OSError) as err:
539 if err.errno != 2: # ignore "no such file"
Benjamin Peterson4b068192009-02-20 03:19:25 +0000540 raise
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000541
Victor Stinnera27dcb72010-04-25 22:39:07 +0000542 def test_undecodable_env(self):
543 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
544 value_repr = repr(value).encode("ascii")
545
546 # test str with surrogates
547 script = "import os; print(repr(os.getenv(%s)))" % repr(key)
548 env = os.environ.copy()
549 env[key] = value
550 stdout = subprocess.check_output(
551 [sys.executable, "-c", script],
552 env=env)
553 stdout = stdout.rstrip(b'\n\r')
554 self.assertEquals(stdout, value_repr)
555
556 # test bytes
557 key = key.encode("ascii", "surrogateescape")
558 value = value.encode("ascii", "surrogateescape")
559 script = "import os; print(repr(os.getenv(%s)))" % repr(key)
560 env = os.environ.copy()
561 env[key] = value
562 stdout = subprocess.check_output(
563 [sys.executable, "-c", script],
564 env=env)
565 stdout = stdout.rstrip(b'\n\r')
566 self.assertEquals(stdout, value_repr)
567
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568 #
569 # POSIX tests
570 #
571 if not mswindows:
572 def test_exceptions(self):
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000573 # caught & re-raised exceptions
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000574 try:
575 p = subprocess.Popen([sys.executable, "-c", ""],
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000576 cwd="/this/path/does/not/exist")
Guido van Rossumb940e112007-01-10 16:19:56 +0000577 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578 # The attribute child_traceback should contain "os.chdir"
579 # somewhere.
580 self.assertNotEqual(e.child_traceback.find("os.chdir"), -1)
581 else:
582 self.fail("Expected OSError")
Tim Peterse718f612004-10-12 21:51:32 +0000583
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000584 def _suppress_core_files(self):
585 """Try to prevent core files from being created.
586 Returns previous ulimit if successful, else None.
587 """
588 try:
589 import resource
590 old_limit = resource.getrlimit(resource.RLIMIT_CORE)
591 resource.setrlimit(resource.RLIMIT_CORE, (0,0))
592 return old_limit
593 except (ImportError, ValueError, resource.error):
594 return None
595
596 def _unsuppress_core_files(self, old_limit):
597 """Return core file behavior to default."""
598 if old_limit is None:
599 return
600 try:
601 import resource
602 resource.setrlimit(resource.RLIMIT_CORE, old_limit)
603 except (ImportError, ValueError, resource.error):
604 return
605
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000606 def test_run_abort(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000607 # returncode handles signal termination
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000608 old_limit = self._suppress_core_files()
609 try:
610 p = subprocess.Popen([sys.executable,
611 "-c", "import os; os.abort()"])
612 finally:
613 self._unsuppress_core_files(old_limit)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000614 p.wait()
615 self.assertEqual(-p.returncode, signal.SIGABRT)
616
617 def test_preexec(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000618 # preexec function
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000620 'import sys,os;'
621 'sys.stdout.write(os.getenv("FRUIT"))'],
622 stdout=subprocess.PIPE,
623 preexec_fn=lambda: os.putenv("FRUIT",
624 "apple"))
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000625 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000626
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000627 def test_args_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000628 # args is a string
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000629 fd, fname = self.mkstemp()
630 # reopen in text mode
631 with open(fd, "w") as fobj:
632 fobj.write("#!/bin/sh\n")
633 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
634 sys.executable)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000635 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000636 p = subprocess.Popen(fname)
637 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000638 os.remove(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000639 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000640
641 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000642 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000644 [sys.executable,
645 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646 startupinfo=47)
647 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000648 [sys.executable,
649 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000650 creationflags=47)
651
652 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000653 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000654 newenv = os.environ.copy()
655 newenv["FRUIT"] = "apple"
656 p = subprocess.Popen(["echo $FRUIT"], shell=1,
657 stdout=subprocess.PIPE,
658 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000659 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000660
661 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000662 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663 newenv = os.environ.copy()
664 newenv["FRUIT"] = "apple"
665 p = subprocess.Popen("echo $FRUIT", shell=1,
666 stdout=subprocess.PIPE,
667 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000668 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000669
670 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000671 # call() function with string argument on UNIX
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000672 fd, fname = self.mkstemp()
673 # reopen in text mode
674 with open(fd, "w") as fobj:
675 fobj.write("#!/bin/sh\n")
676 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
677 sys.executable)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000678 os.chmod(fname, 0o700)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000679 rc = subprocess.call(fname)
Peter Astrand2224be62004-11-17 20:06:35 +0000680 os.remove(fname)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000681 self.assertEqual(rc, 47)
682
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000683 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000684 p = subprocess.Popen([sys.executable,
685 "-c", "input()"])
686
Georg Brandlab91fde2009-08-13 08:51:18 +0000687 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000688 p.send_signal(signal.SIGINT)
689 self.assertNotEqual(p.wait(), 0)
690
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000691 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000692 p = subprocess.Popen([sys.executable,
693 "-c", "input()"])
694
Georg Brandlab91fde2009-08-13 08:51:18 +0000695 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000696 p.kill()
697 self.assertEqual(p.wait(), -signal.SIGKILL)
698
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000699 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000700 p = subprocess.Popen([sys.executable,
701 "-c", "input()"])
702
Georg Brandlab91fde2009-08-13 08:51:18 +0000703 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000704 p.terminate()
705 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000706
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000707 #
708 # Windows tests
709 #
710 if mswindows:
711 def test_startupinfo(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000712 # startupinfo argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000713 # We uses hardcoded constants, because we do not want to
Tim Peterse718f612004-10-12 21:51:32 +0000714 # depend on win32all.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000715 STARTF_USESHOWWINDOW = 1
716 SW_MAXIMIZE = 3
717 startupinfo = subprocess.STARTUPINFO()
718 startupinfo.dwFlags = STARTF_USESHOWWINDOW
719 startupinfo.wShowWindow = SW_MAXIMIZE
720 # Since Python is a console process, it won't be affected
721 # by wShowWindow, but the argument should be silently
722 # ignored
723 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
724 startupinfo=startupinfo)
725
726 def test_creationflags(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000727 # creationflags argument
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000728 CREATE_NEW_CONSOLE = 16
Tim Peters876c4322004-10-13 03:21:35 +0000729 sys.stderr.write(" a DOS box should flash briefly ...\n")
Tim Peters3b01a702004-10-12 22:19:32 +0000730 subprocess.call(sys.executable +
Tim Peters876c4322004-10-13 03:21:35 +0000731 ' -c "import time; time.sleep(0.25)"',
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000732 creationflags=CREATE_NEW_CONSOLE)
733
734 def test_invalid_args(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000735 # invalid arguments should raise ValueError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000736 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000737 [sys.executable,
738 "-c", "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000739 preexec_fn=lambda: 1)
740 self.assertRaises(ValueError, subprocess.call,
Tim Peters3b01a702004-10-12 22:19:32 +0000741 [sys.executable,
742 "-c", "import sys; sys.exit(47)"],
Guido van Rossume7ba4952007-06-06 23:52:48 +0000743 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000744 close_fds=True)
745
Guido van Rossume7ba4952007-06-06 23:52:48 +0000746 def test_close_fds(self):
747 # close file descriptors
748 rc = subprocess.call([sys.executable, "-c",
749 "import sys; sys.exit(47)"],
750 close_fds=True)
751 self.assertEqual(rc, 47)
752
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000753 def test_shell_sequence(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000754 # Run command through the shell (sequence)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000755 newenv = os.environ.copy()
756 newenv["FRUIT"] = "physalis"
757 p = subprocess.Popen(["set"], shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000758 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000759 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000760 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000761
762 def test_shell_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000763 # Run command through the shell (string)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764 newenv = os.environ.copy()
765 newenv["FRUIT"] = "physalis"
766 p = subprocess.Popen("set", shell=1,
Tim Peterse718f612004-10-12 21:51:32 +0000767 stdout=subprocess.PIPE,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000768 env=newenv)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000769 self.assertNotEqual(p.stdout.read().find(b"physalis"), -1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000770
771 def test_call_string(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000772 # call() function with string argument on Windows
Tim Peters3b01a702004-10-12 22:19:32 +0000773 rc = subprocess.call(sys.executable +
774 ' -c "import sys; sys.exit(47)"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000775 self.assertEqual(rc, 47)
776
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000777 def DISABLED_test_send_signal(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000778 p = subprocess.Popen([sys.executable,
779 "-c", "input()"])
780
Georg Brandlab91fde2009-08-13 08:51:18 +0000781 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000782 p.send_signal(signal.SIGTERM)
783 self.assertNotEqual(p.wait(), 0)
784
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000785 def DISABLED_test_kill(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000786 p = subprocess.Popen([sys.executable,
787 "-c", "input()"])
788
Georg Brandlab91fde2009-08-13 08:51:18 +0000789 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000790 p.kill()
791 self.assertNotEqual(p.wait(), 0)
792
Christian Heimes75ca4ea2008-05-06 23:48:04 +0000793 def DISABLED_test_terminate(self):
Christian Heimesa342c012008-04-20 21:01:16 +0000794 p = subprocess.Popen([sys.executable,
795 "-c", "input()"])
796
Georg Brandlab91fde2009-08-13 08:51:18 +0000797 self.assertTrue(p.poll() is None, p.poll())
Christian Heimesa342c012008-04-20 21:01:16 +0000798 p.terminate()
799 self.assertNotEqual(p.wait(), 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000800
Brett Cannona23810f2008-05-26 19:04:21 +0000801class CommandTests(unittest.TestCase):
802# The module says:
803# "NB This only works (and is only relevant) for UNIX."
804#
805# Actually, getoutput should work on any platform with an os.popen, but
806# I'll take the comment as given, and skip this suite.
807 if os.name == 'posix':
808
809 def test_getoutput(self):
810 self.assertEquals(subprocess.getoutput('echo xyzzy'), 'xyzzy')
811 self.assertEquals(subprocess.getstatusoutput('echo xyzzy'),
812 (0, 'xyzzy'))
813
814 # we use mkdtemp in the next line to create an empty directory
815 # under our exclusive control; from that, we can invent a pathname
816 # that we _know_ won't exist. This is guaranteed to fail.
817 dir = None
818 try:
819 dir = tempfile.mkdtemp()
820 name = os.path.join(dir, "foo")
821
822 status, output = subprocess.getstatusoutput('cat ' + name)
823 self.assertNotEquals(status, 0)
824 finally:
825 if dir is not None:
826 os.rmdir(dir)
827
Georg Brandlae83d6e2009-08-13 09:04:31 +0000828
829unit_tests = [ProcessTestCase, CommandTests]
830
Gregory P. Smith10d29522009-08-13 18:33:30 +0000831if getattr(subprocess, '_has_poll', False):
Georg Brandlae83d6e2009-08-13 09:04:31 +0000832 class ProcessTestCaseNoPoll(ProcessTestCase):
833 def setUp(self):
834 subprocess._has_poll = False
835 ProcessTestCase.setUp(self)
836
837 def tearDown(self):
838 subprocess._has_poll = True
839 ProcessTestCase.tearDown(self)
840
841 unit_tests.append(ProcessTestCaseNoPoll)
842
843
Gregory P. Smith3fff44d2010-03-01 00:43:08 +0000844class HelperFunctionTests(unittest.TestCase):
Gregory P. Smith5cab2812010-03-01 02:58:43 +0000845 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smith3fff44d2010-03-01 00:43:08 +0000846 def test_eintr_retry_call(self):
847 record_calls = []
848 def fake_os_func(*args):
849 record_calls.append(args)
850 if len(record_calls) == 2:
851 raise OSError(errno.EINTR, "fake interrupted system call")
852 return tuple(reversed(args))
853
854 self.assertEqual((999, 256),
855 subprocess._eintr_retry_call(fake_os_func, 256, 999))
856 self.assertEqual([(256, 999)], record_calls)
857 # This time there will be an EINTR so it will loop once.
858 self.assertEqual((666,),
859 subprocess._eintr_retry_call(fake_os_func, 666))
860 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
861
862unit_tests.append(HelperFunctionTests)
863
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000864def test_main():
Georg Brandlae83d6e2009-08-13 09:04:31 +0000865 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +0000866 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000867
868if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +0000869 test_main()