blob: 37c4e0fc77c0678c1956afa3091a17d6615d40ec [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
2from test import test_support
3import subprocess
4import sys
5import signal
6import os
Gregory P. Smithcce211f2010-03-01 00:05:08 +00007import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008import tempfile
9import time
Tim Peters3761e8d2004-10-13 04:07:12 +000010import re
Ezio Melotti8f6a2872010-02-10 21:40:33 +000011import sysconfig
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000012
13mswindows = (sys.platform == "win32")
14
15#
16# Depends on the following external programs: Python
17#
18
19if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000020 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
21 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000022else:
23 SETBINARY = ''
24
Florent Xicluna98e3fc32010-02-27 19:20:50 +000025
26try:
27 mkstemp = tempfile.mkstemp
28except AttributeError:
29 # tempfile.mkstemp is not available
30 def mkstemp():
31 """Replacement for mkstemp, calling mktemp."""
32 fname = tempfile.mktemp()
33 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
34
Tim Peters3761e8d2004-10-13 04:07:12 +000035
Florent Xiclunafc4d6d72010-03-23 14:36:45 +000036class BaseTestCase(unittest.TestCase):
Neal Norwitzb15ac312006-06-29 04:10:08 +000037 def setUp(self):
Tim Peters38ff36c2006-06-30 06:18:39 +000038 # Try to minimize the number of children we have so this test
39 # doesn't crash on some buildbots (Alphas in particular).
Florent Xicluna98e3fc32010-02-27 19:20:50 +000040 test_support.reap_children()
Neal Norwitzb15ac312006-06-29 04:10:08 +000041
Florent Xiclunaab5e17f2010-03-04 21:31:58 +000042 def tearDown(self):
43 for inst in subprocess._active:
44 inst.wait()
45 subprocess._cleanup()
46 self.assertFalse(subprocess._active, "subprocess._active not empty")
47
Florent Xicluna98e3fc32010-02-27 19:20:50 +000048 def assertStderrEqual(self, stderr, expected, msg=None):
49 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
50 # shutdown time. That frustrates tests trying to check stderr produced
51 # from a spawned Python process.
52 actual = re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr)
53 self.assertEqual(actual, expected, msg)
Neal Norwitzb15ac312006-06-29 04:10:08 +000054
Florent Xiclunafc4d6d72010-03-23 14:36:45 +000055
56class ProcessTestCase(BaseTestCase):
57
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000058 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000059 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000060 rc = subprocess.call([sys.executable, "-c",
61 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000062 self.assertEqual(rc, 47)
63
Peter Astrand454f7672005-01-01 09:36:35 +000064 def test_check_call_zero(self):
65 # check_call() function with zero return code
66 rc = subprocess.check_call([sys.executable, "-c",
67 "import sys; sys.exit(0)"])
68 self.assertEqual(rc, 0)
69
70 def test_check_call_nonzero(self):
71 # check_call() function with non-zero return code
Florent Xicluna98e3fc32010-02-27 19:20:50 +000072 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000073 subprocess.check_call([sys.executable, "-c",
74 "import sys; sys.exit(47)"])
Florent Xicluna98e3fc32010-02-27 19:20:50 +000075 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000076
Gregory P. Smith26576802008-12-05 02:27:01 +000077 def test_check_output(self):
78 # check_output() function with zero return code
79 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +000080 [sys.executable, "-c", "print 'BDFL'"])
Ezio Melottiaa980582010-01-23 23:04:36 +000081 self.assertIn('BDFL', output)
Gregory P. Smith97f49f42008-12-04 20:21:09 +000082
Gregory P. Smith26576802008-12-05 02:27:01 +000083 def test_check_output_nonzero(self):
Gregory P. Smith97f49f42008-12-04 20:21:09 +000084 # check_call() function with non-zero return code
Florent Xicluna98e3fc32010-02-27 19:20:50 +000085 with self.assertRaises(subprocess.CalledProcessError) as c:
Gregory P. Smith26576802008-12-05 02:27:01 +000086 subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +000087 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xicluna98e3fc32010-02-27 19:20:50 +000088 self.assertEqual(c.exception.returncode, 5)
Gregory P. Smith97f49f42008-12-04 20:21:09 +000089
Gregory P. Smith26576802008-12-05 02:27:01 +000090 def test_check_output_stderr(self):
91 # check_output() function stderr redirected to stdout
92 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +000093 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
94 stderr=subprocess.STDOUT)
Ezio Melottiaa980582010-01-23 23:04:36 +000095 self.assertIn('BDFL', output)
Gregory P. Smith97f49f42008-12-04 20:21:09 +000096
Gregory P. Smith26576802008-12-05 02:27:01 +000097 def test_check_output_stdout_arg(self):
98 # check_output() function stderr redirected to stdout
Florent Xicluna98e3fc32010-02-27 19:20:50 +000099 with self.assertRaises(ValueError) as c:
Gregory P. Smith26576802008-12-05 02:27:01 +0000100 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000101 [sys.executable, "-c", "print 'will not be run'"],
102 stdout=sys.stdout)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000103 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000104 self.assertIn('stdout', c.exception.args[0])
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000105
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000106 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000107 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000108 newenv = os.environ.copy()
109 newenv["FRUIT"] = "banana"
110 rc = subprocess.call([sys.executable, "-c",
Florent Xiclunabab22a72010-03-04 19:40:48 +0000111 'import sys, os;'
112 'sys.exit(os.getenv("FRUIT")=="banana")'],
113 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 self.assertEqual(rc, 1)
115
116 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000117 # .stdin is None when not redirected
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000118 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
119 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000120 self.addCleanup(p.stdout.close)
121 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000122 p.wait()
123 self.assertEqual(p.stdin, None)
124
125 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000126 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000127 p = subprocess.Popen([sys.executable, "-c",
Tim Peters4052fe52004-10-13 03:29:54 +0000128 'print " this bit of output is from a '
129 'test of stdout in a different '
130 'process ..."'],
131 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000132 self.addCleanup(p.stdin.close)
133 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000134 p.wait()
135 self.assertEqual(p.stdout, None)
136
137 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000138 # .stderr is None when not redirected
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000139 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
140 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000141 self.addCleanup(p.stdout.close)
142 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000143 p.wait()
144 self.assertEqual(p.stderr, None)
145
Ezio Melotti8f6a2872010-02-10 21:40:33 +0000146 def test_executable_with_cwd(self):
Florent Xicluna63763702010-03-11 01:50:48 +0000147 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti8f6a2872010-02-10 21:40:33 +0000148 p = subprocess.Popen(["somethingyoudonthave", "-c",
149 "import sys; sys.exit(47)"],
150 executable=sys.executable, cwd=python_dir)
151 p.wait()
152 self.assertEqual(p.returncode, 47)
153
154 @unittest.skipIf(sysconfig.is_python_build(),
155 "need an installed Python. See #7774")
156 def test_executable_without_cwd(self):
157 # For a normal installation, it should work without 'cwd'
158 # argument. For test runs in the build directory, see #7774.
159 p = subprocess.Popen(["somethingyoudonthave", "-c",
160 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000161 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000162 p.wait()
163 self.assertEqual(p.returncode, 47)
164
165 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000166 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000167 p = subprocess.Popen([sys.executable, "-c",
168 'import sys; sys.exit(sys.stdin.read() == "pear")'],
169 stdin=subprocess.PIPE)
170 p.stdin.write("pear")
171 p.stdin.close()
172 p.wait()
173 self.assertEqual(p.returncode, 1)
174
175 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000176 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000177 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000178 d = tf.fileno()
179 os.write(d, "pear")
180 os.lseek(d, 0, 0)
181 p = subprocess.Popen([sys.executable, "-c",
182 'import sys; sys.exit(sys.stdin.read() == "pear")'],
183 stdin=d)
184 p.wait()
185 self.assertEqual(p.returncode, 1)
186
187 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000188 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 tf = tempfile.TemporaryFile()
190 tf.write("pear")
191 tf.seek(0)
192 p = subprocess.Popen([sys.executable, "-c",
193 'import sys; sys.exit(sys.stdin.read() == "pear")'],
194 stdin=tf)
195 p.wait()
196 self.assertEqual(p.returncode, 1)
197
198 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000199 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000200 p = subprocess.Popen([sys.executable, "-c",
201 'import sys; sys.stdout.write("orange")'],
202 stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000203 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000204 self.assertEqual(p.stdout.read(), "orange")
205
206 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000207 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000208 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000209 d = tf.fileno()
210 p = subprocess.Popen([sys.executable, "-c",
211 'import sys; sys.stdout.write("orange")'],
212 stdout=d)
213 p.wait()
214 os.lseek(d, 0, 0)
215 self.assertEqual(os.read(d, 1024), "orange")
216
217 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000218 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000219 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000220 p = subprocess.Popen([sys.executable, "-c",
221 'import sys; sys.stdout.write("orange")'],
222 stdout=tf)
223 p.wait()
224 tf.seek(0)
225 self.assertEqual(tf.read(), "orange")
226
227 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000228 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000229 p = subprocess.Popen([sys.executable, "-c",
230 'import sys; sys.stderr.write("strawberry")'],
231 stderr=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000232 self.addCleanup(p.stderr.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000233 self.assertStderrEqual(p.stderr.read(), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000234
235 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000236 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000237 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238 d = tf.fileno()
239 p = subprocess.Popen([sys.executable, "-c",
240 'import sys; sys.stderr.write("strawberry")'],
241 stderr=d)
242 p.wait()
243 os.lseek(d, 0, 0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000244 self.assertStderrEqual(os.read(d, 1024), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245
246 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000247 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000248 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000249 p = subprocess.Popen([sys.executable, "-c",
250 'import sys; sys.stderr.write("strawberry")'],
251 stderr=tf)
252 p.wait()
253 tf.seek(0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000254 self.assertStderrEqual(tf.read(), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000255
256 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000257 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000258 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000259 'import sys;'
260 'sys.stdout.write("apple");'
261 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262 'sys.stderr.write("orange")'],
263 stdout=subprocess.PIPE,
264 stderr=subprocess.STDOUT)
Brian Curtind117b562010-11-05 04:09:09 +0000265 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000266 self.assertStderrEqual(p.stdout.read(), "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000267
268 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000269 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270 tf = tempfile.TemporaryFile()
271 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000272 'import sys;'
273 'sys.stdout.write("apple");'
274 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000275 'sys.stderr.write("orange")'],
276 stdout=tf,
277 stderr=tf)
278 p.wait()
279 tf.seek(0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000280 self.assertStderrEqual(tf.read(), "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281
Gustavo Niemeyerc36bede2006-09-07 00:48:33 +0000282 def test_stdout_filedes_of_stdout(self):
283 # stdout is set to 1 (#1531862).
284 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), '.\n'))"
285 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000286 self.assertEqual(rc, 2)
Gustavo Niemeyerc36bede2006-09-07 00:48:33 +0000287
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000288 def test_cwd(self):
Guido van Rossume9a0e882007-12-20 17:28:10 +0000289 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000290 # We cannot use os.path.realpath to canonicalize the path,
291 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
292 cwd = os.getcwd()
293 os.chdir(tmpdir)
294 tmpdir = os.getcwd()
295 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000297 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298 'sys.stdout.write(os.getcwd())'],
299 stdout=subprocess.PIPE,
300 cwd=tmpdir)
Brian Curtind117b562010-11-05 04:09:09 +0000301 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000302 normcase = os.path.normcase
303 self.assertEqual(normcase(p.stdout.read()), normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000304
305 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306 newenv = os.environ.copy()
307 newenv["FRUIT"] = "orange"
308 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000309 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000310 'sys.stdout.write(os.getenv("FRUIT"))'],
311 stdout=subprocess.PIPE,
312 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000313 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000314 self.assertEqual(p.stdout.read(), "orange")
315
Peter Astrandcbac93c2005-03-03 20:24:28 +0000316 def test_communicate_stdin(self):
317 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000318 'import sys;'
319 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000320 stdin=subprocess.PIPE)
321 p.communicate("pear")
322 self.assertEqual(p.returncode, 1)
323
324 def test_communicate_stdout(self):
325 p = subprocess.Popen([sys.executable, "-c",
326 'import sys; sys.stdout.write("pineapple")'],
327 stdout=subprocess.PIPE)
328 (stdout, stderr) = p.communicate()
329 self.assertEqual(stdout, "pineapple")
330 self.assertEqual(stderr, None)
331
332 def test_communicate_stderr(self):
333 p = subprocess.Popen([sys.executable, "-c",
334 'import sys; sys.stderr.write("pineapple")'],
335 stderr=subprocess.PIPE)
336 (stdout, stderr) = p.communicate()
337 self.assertEqual(stdout, None)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000338 self.assertStderrEqual(stderr, "pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000339
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000340 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000341 p = subprocess.Popen([sys.executable, "-c",
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000342 'import sys,os;'
343 'sys.stderr.write("pineapple");'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000344 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000345 stdin=subprocess.PIPE,
346 stdout=subprocess.PIPE,
347 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000348 self.addCleanup(p.stdout.close)
349 self.addCleanup(p.stderr.close)
350 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000351 (stdout, stderr) = p.communicate("banana")
352 self.assertEqual(stdout, "banana")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000353 self.assertStderrEqual(stderr, "pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000355 # This test is Linux specific for simplicity to at least have
356 # some coverage. It is not a platform specific bug.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000357 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
358 "Linux specific")
359 # Test for the fd leak reported in http://bugs.python.org/issue2791.
360 def test_communicate_pipe_fd_leak(self):
361 fd_directory = '/proc/%d/fd' % os.getpid()
362 num_fds_before_popen = len(os.listdir(fd_directory))
363 p = subprocess.Popen([sys.executable, "-c", "print()"],
364 stdout=subprocess.PIPE)
365 p.communicate()
366 num_fds_after_communicate = len(os.listdir(fd_directory))
367 del p
368 num_fds_after_destruction = len(os.listdir(fd_directory))
369 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
370 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000371
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000372 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000373 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000374 p = subprocess.Popen([sys.executable, "-c",
375 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000376 (stdout, stderr) = p.communicate()
377 self.assertEqual(stdout, None)
378 self.assertEqual(stderr, None)
379
380 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000381 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000382 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000383 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000384 x, y = os.pipe()
385 if mswindows:
386 pipe_buf = 512
387 else:
388 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
389 os.close(x)
390 os.close(y)
391 p = subprocess.Popen([sys.executable, "-c",
Tim Peterse718f612004-10-12 21:51:32 +0000392 'import sys,os;'
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000393 'sys.stdout.write(sys.stdin.read(47));'
394 'sys.stderr.write("xyz"*%d);'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000395 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
Tim Peters3b01a702004-10-12 22:19:32 +0000396 stdin=subprocess.PIPE,
397 stdout=subprocess.PIPE,
398 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000399 self.addCleanup(p.stdout.close)
400 self.addCleanup(p.stderr.close)
401 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000402 string_to_write = "abc"*pipe_buf
403 (stdout, stderr) = p.communicate(string_to_write)
404 self.assertEqual(stdout, string_to_write)
405
406 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000407 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000408 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000409 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000410 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000411 stdin=subprocess.PIPE,
412 stdout=subprocess.PIPE,
413 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000414 self.addCleanup(p.stdout.close)
415 self.addCleanup(p.stderr.close)
416 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000417 p.stdin.write("banana")
418 (stdout, stderr) = p.communicate("split")
419 self.assertEqual(stdout, "bananasplit")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000420 self.assertStderrEqual(stderr, "")
Tim Peterse718f612004-10-12 21:51:32 +0000421
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000422 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000424 'import sys,os;' + SETBINARY +
425 'sys.stdout.write("line1\\n");'
426 'sys.stdout.flush();'
427 'sys.stdout.write("line2\\r");'
428 'sys.stdout.flush();'
429 'sys.stdout.write("line3\\r\\n");'
430 'sys.stdout.flush();'
431 'sys.stdout.write("line4\\r");'
432 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000434 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435 'sys.stdout.write("\\nline6");'],
436 stdout=subprocess.PIPE,
437 universal_newlines=1)
Brian Curtind117b562010-11-05 04:09:09 +0000438 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000439 stdout = p.stdout.read()
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000440 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000441 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000442 self.assertEqual(stdout,
443 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 else:
445 # Interpreter without universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000446 self.assertEqual(stdout,
447 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000448
449 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000450 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000451 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000452 'import sys,os;' + SETBINARY +
453 'sys.stdout.write("line1\\n");'
454 'sys.stdout.flush();'
455 'sys.stdout.write("line2\\r");'
456 'sys.stdout.flush();'
457 'sys.stdout.write("line3\\r\\n");'
458 'sys.stdout.flush();'
459 'sys.stdout.write("line4\\r");'
460 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000461 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000462 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463 'sys.stdout.write("\\nline6");'],
464 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
465 universal_newlines=1)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000466 self.addCleanup(p.stdout.close)
467 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468 (stdout, stderr) = p.communicate()
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000469 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000471 self.assertEqual(stdout,
472 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000473 else:
474 # Interpreter without universal newline support
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000475 self.assertEqual(stdout,
476 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000477
478 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000479 # Make sure we leak no resources
Antoine Pitroub0b3bff2010-09-18 22:42:30 +0000480 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000481 max_handles = 1026 # too much for most UNIX systems
482 else:
Antoine Pitroub0b3bff2010-09-18 22:42:30 +0000483 max_handles = 2050 # too much for (at least some) Windows setups
484 handles = []
485 try:
486 for i in range(max_handles):
487 try:
488 handles.append(os.open(test_support.TESTFN,
489 os.O_WRONLY | os.O_CREAT))
490 except OSError as e:
491 if e.errno != errno.EMFILE:
492 raise
493 break
494 else:
495 self.skipTest("failed to reach the file descriptor limit "
496 "(tried %d)" % max_handles)
497 # Close a couple of them (should be enough for a subprocess)
498 for i in range(10):
499 os.close(handles.pop())
500 # Loop creating some subprocesses. If one of them leaks some fds,
501 # the next loop iteration will fail by reaching the max fd limit.
502 for i in range(15):
503 p = subprocess.Popen([sys.executable, "-c",
504 "import sys;"
505 "sys.stdout.write(sys.stdin.read())"],
506 stdin=subprocess.PIPE,
507 stdout=subprocess.PIPE,
508 stderr=subprocess.PIPE)
509 data = p.communicate(b"lime")[0]
510 self.assertEqual(data, b"lime")
511 finally:
512 for h in handles:
513 os.close(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514
515 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
517 '"a b c" d e')
518 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
519 'ab\\"c \\ d')
Gregory P. Smithe047e6d2008-01-19 20:49:02 +0000520 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
521 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
523 'a\\\\\\b "de fg" h')
524 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
525 'a\\\\\\"b c d')
526 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
527 '"a\\\\b c" d e')
528 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
529 '"a\\\\b\\ c" d e')
Peter Astrand10514a72007-01-13 22:35:35 +0000530 self.assertEqual(subprocess.list2cmdline(['ab', '']),
531 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532
533
534 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000535 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000536 "-c", "import time; time.sleep(1)"])
537 count = 0
538 while p.poll() is None:
539 time.sleep(0.1)
540 count += 1
541 # We expect that the poll loop probably went around about 10 times,
542 # but, based on system scheduling we can't control, it's possible
543 # poll() never returned None. It "should be" very rare that it
544 # didn't go around at least twice.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000545 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546 # Subsequent invocations should just return the returncode
547 self.assertEqual(p.poll(), 0)
548
549
550 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551 p = subprocess.Popen([sys.executable,
552 "-c", "import time; time.sleep(2)"])
553 self.assertEqual(p.wait(), 0)
554 # Subsequent invocations should just return the returncode
555 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000556
Peter Astrand738131d2004-11-30 21:04:45 +0000557
558 def test_invalid_bufsize(self):
559 # an invalid type of the bufsize argument should raise
560 # TypeError.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000561 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000562 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000563
Georg Brandlf3715d22009-02-14 17:01:36 +0000564 def test_leaking_fds_on_error(self):
565 # see bug #5179: Popen leaks file descriptors to PIPEs if
566 # the child fails to execute; this will eventually exhaust
567 # the maximum number of open fds. 1024 seems a very common
568 # value for that limit, but Windows has 2048, so we loop
569 # 1024 times (each call leaked two fds).
570 for i in range(1024):
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000571 # Windows raises IOError. Others raise OSError.
572 with self.assertRaises(EnvironmentError) as c:
Georg Brandlf3715d22009-02-14 17:01:36 +0000573 subprocess.Popen(['nonexisting_i_hope'],
574 stdout=subprocess.PIPE,
575 stderr=subprocess.PIPE)
Antoine Pitrou767cbc42010-09-18 18:15:33 +0000576 if c.exception.errno != errno.ENOENT: # ignore "no such file"
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000577 raise c.exception
Georg Brandlf3715d22009-02-14 17:01:36 +0000578
Tim Golden90374f52010-08-06 13:14:33 +0000579 def test_handles_closed_on_exception(self):
580 # If CreateProcess exits with an error, ensure the
581 # duplicate output handles are released
582 ifhandle, ifname = mkstemp()
583 ofhandle, ofname = mkstemp()
584 efhandle, efname = mkstemp()
585 try:
586 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
587 stderr=efhandle)
588 except OSError:
589 os.close(ifhandle)
590 os.remove(ifname)
591 os.close(ofhandle)
592 os.remove(ofname)
593 os.close(efhandle)
594 os.remove(efname)
595 self.assertFalse(os.path.exists(ifname))
596 self.assertFalse(os.path.exists(ofname))
597 self.assertFalse(os.path.exists(efname))
598
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000599
600# context manager
601class _SuppressCoreFiles(object):
602 """Try to prevent core files from being created."""
603 old_limit = None
604
605 def __enter__(self):
606 """Try to save previous ulimit, then set it to (0, 0)."""
607 try:
608 import resource
609 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
610 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
611 except (ImportError, ValueError, resource.error):
612 pass
613
Ronald Oussoren21b44e02010-07-23 12:26:30 +0000614 if sys.platform == 'darwin':
615 # Check if the 'Crash Reporter' on OSX was configured
616 # in 'Developer' mode and warn that it will get triggered
617 # when it is.
618 #
619 # This assumes that this context manager is used in tests
620 # that might trigger the next manager.
621 value = subprocess.Popen(['/usr/bin/defaults', 'read',
622 'com.apple.CrashReporter', 'DialogType'],
623 stdout=subprocess.PIPE).communicate()[0]
624 if value.strip() == b'developer':
625 print "this tests triggers the Crash Reporter, that is intentional"
626 sys.stdout.flush()
627
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000628 def __exit__(self, *args):
629 """Return core file behavior to default."""
630 if self.old_limit is None:
631 return
632 try:
633 import resource
634 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
635 except (ImportError, ValueError, resource.error):
636 pass
637
638
Florent Xiclunabab22a72010-03-04 19:40:48 +0000639@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000640class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +0000641
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000642 def test_exceptions(self):
643 # caught & re-raised exceptions
644 with self.assertRaises(OSError) as c:
645 p = subprocess.Popen([sys.executable, "-c", ""],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646 cwd="/this/path/does/not/exist")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000647 # The attribute child_traceback should contain "os.chdir" somewhere.
648 self.assertIn("os.chdir", c.exception.child_traceback)
Tim Peterse718f612004-10-12 21:51:32 +0000649
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000650 def test_run_abort(self):
651 # returncode handles signal termination
652 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000653 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000654 "import os; os.abort()"])
655 p.wait()
656 self.assertEqual(-p.returncode, signal.SIGABRT)
657
658 def test_preexec(self):
659 # preexec function
660 p = subprocess.Popen([sys.executable, "-c",
661 "import sys, os;"
662 "sys.stdout.write(os.getenv('FRUIT'))"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663 stdout=subprocess.PIPE,
664 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtind117b562010-11-05 04:09:09 +0000665 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000666 self.assertEqual(p.stdout.read(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000667
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000668 def test_args_string(self):
669 # args is a string
670 f, fname = mkstemp()
671 os.write(f, "#!/bin/sh\n")
672 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
673 sys.executable)
674 os.close(f)
675 os.chmod(fname, 0o700)
676 p = subprocess.Popen(fname)
677 p.wait()
678 os.remove(fname)
679 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000680
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000681 def test_invalid_args(self):
682 # invalid arguments should raise ValueError
683 self.assertRaises(ValueError, subprocess.call,
684 [sys.executable, "-c",
685 "import sys; sys.exit(47)"],
686 startupinfo=47)
687 self.assertRaises(ValueError, subprocess.call,
688 [sys.executable, "-c",
689 "import sys; sys.exit(47)"],
690 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000691
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000692 def test_shell_sequence(self):
693 # Run command through the shell (sequence)
694 newenv = os.environ.copy()
695 newenv["FRUIT"] = "apple"
696 p = subprocess.Popen(["echo $FRUIT"], shell=1,
697 stdout=subprocess.PIPE,
698 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000699 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000700 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000701
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000702 def test_shell_string(self):
703 # Run command through the shell (string)
704 newenv = os.environ.copy()
705 newenv["FRUIT"] = "apple"
706 p = subprocess.Popen("echo $FRUIT", shell=1,
707 stdout=subprocess.PIPE,
708 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000709 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000710 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000711
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000712 def test_call_string(self):
713 # call() function with string argument on UNIX
714 f, fname = mkstemp()
715 os.write(f, "#!/bin/sh\n")
716 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
717 sys.executable)
718 os.close(f)
719 os.chmod(fname, 0700)
720 rc = subprocess.call(fname)
721 os.remove(fname)
722 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000723
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000724 def test_specific_shell(self):
725 # Issue #9265: Incorrect name passed as arg[0].
726 shells = []
727 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
728 for name in ['bash', 'ksh']:
729 sh = os.path.join(prefix, name)
730 if os.path.isfile(sh):
731 shells.append(sh)
732 if not shells: # Will probably work for any shell but csh.
733 self.skipTest("bash or ksh required for this test")
734 sh = '/bin/sh'
735 if os.path.isfile(sh) and not os.path.islink(sh):
736 # Test will fail if /bin/sh is a symlink to csh.
737 shells.append(sh)
738 for sh in shells:
739 p = subprocess.Popen("echo $0", executable=sh, shell=True,
740 stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000741 self.addCleanup(p.stdout.close)
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000742 self.assertEqual(p.stdout.read().strip(), sh)
743
Florent Xiclunac0838642010-03-07 15:27:39 +0000744 def _kill_process(self, method, *args):
Florent Xiclunacecef392010-03-05 19:31:21 +0000745 # Do not inherit file handles from the parent.
746 # It should fix failures on some platforms.
Antoine Pitroua6166da2010-09-20 11:20:44 +0000747 p = subprocess.Popen([sys.executable, "-c", """if 1:
748 import sys, time
749 sys.stdout.write('x\\n')
750 sys.stdout.flush()
751 time.sleep(30)
752 """],
753 close_fds=True,
754 stdin=subprocess.PIPE,
755 stdout=subprocess.PIPE,
756 stderr=subprocess.PIPE)
757 # Wait for the interpreter to be completely initialized before
758 # sending any signal.
759 p.stdout.read(1)
760 getattr(p, method)(*args)
Florent Xiclunac0838642010-03-07 15:27:39 +0000761 return p
762
763 def test_send_signal(self):
764 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000765 _, stderr = p.communicate()
Florent Xicluna3c919cf2010-03-23 19:19:16 +0000766 self.assertIn('KeyboardInterrupt', stderr)
Florent Xicluna446ff142010-03-23 15:05:30 +0000767 self.assertNotEqual(p.wait(), 0)
Christian Heimese74c8f22008-04-19 02:23:57 +0000768
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000769 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000770 p = self._kill_process('kill')
Florent Xicluna446ff142010-03-23 15:05:30 +0000771 _, stderr = p.communicate()
772 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000773 self.assertEqual(p.wait(), -signal.SIGKILL)
Christian Heimese74c8f22008-04-19 02:23:57 +0000774
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000775 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000776 p = self._kill_process('terminate')
Florent Xicluna446ff142010-03-23 15:05:30 +0000777 _, stderr = p.communicate()
778 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000779 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000780
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000781
Florent Xiclunabab22a72010-03-04 19:40:48 +0000782@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000783class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +0000784
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000785 def test_startupinfo(self):
786 # startupinfo argument
787 # We uses hardcoded constants, because we do not want to
788 # depend on win32all.
789 STARTF_USESHOWWINDOW = 1
790 SW_MAXIMIZE = 3
791 startupinfo = subprocess.STARTUPINFO()
792 startupinfo.dwFlags = STARTF_USESHOWWINDOW
793 startupinfo.wShowWindow = SW_MAXIMIZE
794 # Since Python is a console process, it won't be affected
795 # by wShowWindow, but the argument should be silently
796 # ignored
797 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000798 startupinfo=startupinfo)
799
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000800 def test_creationflags(self):
801 # creationflags argument
802 CREATE_NEW_CONSOLE = 16
803 sys.stderr.write(" a DOS box should flash briefly ...\n")
804 subprocess.call(sys.executable +
805 ' -c "import time; time.sleep(0.25)"',
806 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000807
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000808 def test_invalid_args(self):
809 # invalid arguments should raise ValueError
810 self.assertRaises(ValueError, subprocess.call,
811 [sys.executable, "-c",
812 "import sys; sys.exit(47)"],
813 preexec_fn=lambda: 1)
814 self.assertRaises(ValueError, subprocess.call,
815 [sys.executable, "-c",
816 "import sys; sys.exit(47)"],
817 stdout=subprocess.PIPE,
818 close_fds=True)
819
820 def test_close_fds(self):
821 # close file descriptors
822 rc = subprocess.call([sys.executable, "-c",
823 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000824 close_fds=True)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000825 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000826
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000827 def test_shell_sequence(self):
828 # Run command through the shell (sequence)
829 newenv = os.environ.copy()
830 newenv["FRUIT"] = "physalis"
831 p = subprocess.Popen(["set"], shell=1,
832 stdout=subprocess.PIPE,
833 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000834 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000835 self.assertIn("physalis", p.stdout.read())
Peter Astrand81a191b2007-05-26 22:18:20 +0000836
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000837 def test_shell_string(self):
838 # Run command through the shell (string)
839 newenv = os.environ.copy()
840 newenv["FRUIT"] = "physalis"
841 p = subprocess.Popen("set", shell=1,
842 stdout=subprocess.PIPE,
843 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000844 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000845 self.assertIn("physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000846
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000847 def test_call_string(self):
848 # call() function with string argument on Windows
849 rc = subprocess.call(sys.executable +
850 ' -c "import sys; sys.exit(47)"')
851 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000852
Florent Xiclunac0838642010-03-07 15:27:39 +0000853 def _kill_process(self, method, *args):
Florent Xicluna400efc22010-03-07 17:12:23 +0000854 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroudee00972010-09-24 19:00:29 +0000855 p = subprocess.Popen([sys.executable, "-c", """if 1:
856 import sys, time
857 sys.stdout.write('x\\n')
858 sys.stdout.flush()
859 time.sleep(30)
860 """],
861 stdin=subprocess.PIPE,
862 stdout=subprocess.PIPE,
863 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000864 self.addCleanup(p.stdout.close)
865 self.addCleanup(p.stderr.close)
866 self.addCleanup(p.stdin.close)
Antoine Pitroudee00972010-09-24 19:00:29 +0000867 # Wait for the interpreter to be completely initialized before
868 # sending any signal.
869 p.stdout.read(1)
870 getattr(p, method)(*args)
Florent Xicluna446ff142010-03-23 15:05:30 +0000871 _, stderr = p.communicate()
872 self.assertStderrEqual(stderr, '')
Antoine Pitroudee00972010-09-24 19:00:29 +0000873 returncode = p.wait()
Florent Xiclunafaf17532010-03-08 10:59:33 +0000874 self.assertNotEqual(returncode, 0)
Florent Xiclunac0838642010-03-07 15:27:39 +0000875
876 def test_send_signal(self):
877 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimese74c8f22008-04-19 02:23:57 +0000878
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000879 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000880 self._kill_process('kill')
Christian Heimese74c8f22008-04-19 02:23:57 +0000881
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000882 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000883 self._kill_process('terminate')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000884
Gregory P. Smithdd7ca242009-07-04 01:49:29 +0000885
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000886@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
887 "poll system call not supported")
888class ProcessTestCaseNoPoll(ProcessTestCase):
889 def setUp(self):
890 subprocess._has_poll = False
891 ProcessTestCase.setUp(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +0000892
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000893 def tearDown(self):
894 subprocess._has_poll = True
895 ProcessTestCase.tearDown(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +0000896
897
Gregory P. Smithcce211f2010-03-01 00:05:08 +0000898class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithc1baf4a2010-03-01 02:53:24 +0000899 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smithcce211f2010-03-01 00:05:08 +0000900 def test_eintr_retry_call(self):
901 record_calls = []
902 def fake_os_func(*args):
903 record_calls.append(args)
904 if len(record_calls) == 2:
905 raise OSError(errno.EINTR, "fake interrupted system call")
906 return tuple(reversed(args))
907
908 self.assertEqual((999, 256),
909 subprocess._eintr_retry_call(fake_os_func, 256, 999))
910 self.assertEqual([(256, 999)], record_calls)
911 # This time there will be an EINTR so it will loop once.
912 self.assertEqual((666,),
913 subprocess._eintr_retry_call(fake_os_func, 666))
914 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
915
916
Tim Golden8e4756c2010-08-12 11:00:35 +0000917@unittest.skipUnless(mswindows, "mswindows only")
918class CommandsWithSpaces (BaseTestCase):
919
920 def setUp(self):
921 super(CommandsWithSpaces, self).setUp()
922 f, fname = 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(CommandsWithSpaces, self).tearDown()
932
933 def with_spaces(self, *args, **kwargs):
934 kwargs['stdout'] = subprocess.PIPE
935 p = subprocess.Popen(*args, **kwargs)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000936 self.addCleanup(p.stdout.close)
Tim Golden8e4756c2010-08-12 11:00:35 +0000937 self.assertEqual(
938 p.stdout.read ().decode("mbcs"),
939 "2 [%r, 'ab cd']" % self.fname
940 )
941
942 def test_shell_string_with_spaces(self):
943 # call() function with string argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +0000944 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
945 "ab cd"), shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +0000946
947 def test_shell_sequence_with_spaces(self):
948 # call() function with sequence argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +0000949 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +0000950
951 def test_noshell_string_with_spaces(self):
952 # call() function with string argument with spaces on Windows
953 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
954 "ab cd"))
955
956 def test_noshell_sequence_with_spaces(self):
957 # call() function with sequence argument with spaces on Windows
958 self.with_spaces([sys.executable, self.fname, "ab cd"])
959
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000960def test_main():
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000961 unit_tests = (ProcessTestCase,
962 POSIXProcessTestCase,
963 Win32ProcessTestCase,
Gregory P. Smithcce211f2010-03-01 00:05:08 +0000964 ProcessTestCaseNoPoll,
Tim Golden8e4756c2010-08-12 11:00:35 +0000965 HelperFunctionTests,
966 CommandsWithSpaces)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000967
Gregory P. Smithdd7ca242009-07-04 01:49:29 +0000968 test_support.run_unittest(*unit_tests)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000969 test_support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000970
971if __name__ == "__main__":
972 test_main()