blob: 7c79365f411914152c62ad0c4950ca5d4908dfc9 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00002from unittest import mock
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Hai Shi0c4f0f32020-06-30 21:46:31 +08004from test.support import import_helper
5from test.support import os_helper
6from test.support import warnings_helper
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import subprocess
8import sys
9import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -040010import io
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +030011import itertools
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000012import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000013import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000014import tempfile
15import time
Gregory P. Smith580d2782019-09-11 04:23:05 -050016import traceback
Guido van Rossum48b069a2020-04-07 09:50:06 -070017import types
Charles-François Natali3a4586a2013-11-08 19:56:59 +010018import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000019import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000020import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040021import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020022import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050023import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030024import textwrap
Patrick McLean2b2ead72019-09-12 10:15:44 -070025import json
M. Kocherdb0c5b72021-04-28 01:16:38 -070026import pathlib
Hai Shi0c4f0f32020-06-30 21:46:31 +080027from test.support.os_helper import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050028
29try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020030 import _testcapi
31except ImportError:
32 _testcapi = None
33
Patrick McLean2b2ead72019-09-12 10:15:44 -070034try:
35 import pwd
36except ImportError:
37 pwd = None
38try:
39 import grp
40except ImportError:
41 grp = None
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020042
Ruben Vorderman23c0fb82020-10-20 01:30:02 +020043try:
44 import fcntl
45except:
46 fcntl = None
47
Steve Dower22d06982016-09-06 19:38:15 -070048if support.PGO:
49 raise unittest.SkipTest("test is not helpful for PGO")
50
Victor Stinner937ee9e2018-06-26 02:11:06 +020051mswindows = (sys.platform == "win32")
52
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000053#
54# Depends on the following external programs: Python
55#
56
Victor Stinner937ee9e2018-06-26 02:11:06 +020057if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000058 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
59 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000060else:
61 SETBINARY = ''
62
Victor Stinner9a83f652017-08-21 23:51:31 +020063NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010064# Ignore errors that indicate the command was not found
65NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020066
Gregory P. Smith67b93f82019-10-12 16:35:53 -070067ZERO_RETURN_CMD = (sys.executable, '-c', 'pass')
68
69
70def setUpModule():
71 shell_true = shutil.which('true')
Pablo Galindo46113e02019-10-13 02:40:24 +010072 if shell_true is None:
73 return
Gregory P. Smith67b93f82019-10-12 16:35:53 -070074 if (os.access(shell_true, os.X_OK) and
75 subprocess.run([shell_true]).returncode == 0):
76 global ZERO_RETURN_CMD
77 ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup.
78
Florent Xiclunab1e94e82010-02-27 22:12:37 +000079
Florent Xiclunac049d872010-03-27 22:47:23 +000080class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000081 def setUp(self):
82 # Try to minimize the number of children we have so this test
83 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000084 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000085
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000086 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030087 if not mswindows:
88 # subprocess._active is not used on Windows and is set to None.
89 for inst in subprocess._active:
90 inst.wait()
91 subprocess._cleanup()
92 self.assertFalse(
93 subprocess._active, "subprocess._active not empty"
94 )
Victor Stinnercc42c122017-07-28 18:00:22 +020095 self.doCleanups()
96 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000097
Florent Xiclunac049d872010-03-27 22:47:23 +000098
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080099class PopenTestException(Exception):
100 pass
101
102
103class PopenExecuteChildRaises(subprocess.Popen):
104 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
105 _execute_child fails.
106 """
107 def _execute_child(self, *args, **kwargs):
108 raise PopenTestException("Forced Exception for Test")
109
110
Florent Xiclunac049d872010-03-27 22:47:23 +0000111class ProcessTestCase(BaseTestCase):
112
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700113 def test_io_buffered_by_default(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700114 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700115 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
116 stderr=subprocess.PIPE)
117 try:
118 self.assertIsInstance(p.stdin, io.BufferedIOBase)
119 self.assertIsInstance(p.stdout, io.BufferedIOBase)
120 self.assertIsInstance(p.stderr, io.BufferedIOBase)
121 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700122 p.stdin.close()
123 p.stdout.close()
124 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700125 p.wait()
126
127 def test_io_unbuffered_works(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700128 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700129 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
130 stderr=subprocess.PIPE, bufsize=0)
131 try:
132 self.assertIsInstance(p.stdin, io.RawIOBase)
133 self.assertIsInstance(p.stdout, io.RawIOBase)
134 self.assertIsInstance(p.stderr, io.RawIOBase)
135 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700136 p.stdin.close()
137 p.stdout.close()
138 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700139 p.wait()
140
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000141 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000142 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000143 rc = subprocess.call([sys.executable, "-c",
144 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145 self.assertEqual(rc, 47)
146
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400147 def test_call_timeout(self):
148 # call() function with timeout argument; we want to test that the child
149 # process gets killed when the timeout expires. If the child isn't
150 # killed, this call will deadlock since subprocess.call waits for the
151 # child.
152 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
153 [sys.executable, "-c", "while True: pass"],
154 timeout=0.1)
155
Peter Astrand454f7672005-01-01 09:36:35 +0000156 def test_check_call_zero(self):
157 # check_call() function with zero return code
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700158 rc = subprocess.check_call(ZERO_RETURN_CMD)
Peter Astrand454f7672005-01-01 09:36:35 +0000159 self.assertEqual(rc, 0)
160
161 def test_check_call_nonzero(self):
162 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000163 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000164 subprocess.check_call([sys.executable, "-c",
165 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000166 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000167
Georg Brandlf9734072008-12-07 15:30:06 +0000168 def test_check_output(self):
169 # check_output() function with zero return code
170 output = subprocess.check_output(
171 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000172 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000173
174 def test_check_output_nonzero(self):
175 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000176 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000177 subprocess.check_output(
178 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000179 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000180
181 def test_check_output_stderr(self):
182 # check_output() function stderr redirected to stdout
183 output = subprocess.check_output(
184 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
185 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000186 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000187
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300188 def test_check_output_stdin_arg(self):
189 # check_output() can be called with stdin set to a file
190 tf = tempfile.TemporaryFile()
191 self.addCleanup(tf.close)
192 tf.write(b'pear')
193 tf.seek(0)
194 output = subprocess.check_output(
195 [sys.executable, "-c",
196 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
197 stdin=tf)
198 self.assertIn(b'PEAR', output)
199
200 def test_check_output_input_arg(self):
201 # check_output() can be called with input set to a string
202 output = subprocess.check_output(
203 [sys.executable, "-c",
204 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
205 input=b'pear')
206 self.assertIn(b'PEAR', output)
207
Gregory P. Smith64abf372020-12-24 20:57:21 -0800208 def test_check_output_input_none(self):
209 """input=None has a legacy meaning of input='' on check_output."""
210 output = subprocess.check_output(
211 [sys.executable, "-c",
212 "import sys; print('XX' if sys.stdin.read() else '')"],
213 input=None)
214 self.assertNotIn(b'XX', output)
215
216 def test_check_output_input_none_text(self):
217 output = subprocess.check_output(
218 [sys.executable, "-c",
219 "import sys; print('XX' if sys.stdin.read() else '')"],
220 input=None, text=True)
221 self.assertNotIn('XX', output)
222
223 def test_check_output_input_none_universal_newlines(self):
224 output = subprocess.check_output(
225 [sys.executable, "-c",
226 "import sys; print('XX' if sys.stdin.read() else '')"],
227 input=None, universal_newlines=True)
228 self.assertNotIn('XX', output)
229
Georg Brandlf9734072008-12-07 15:30:06 +0000230 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300231 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000232 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000233 output = subprocess.check_output(
234 [sys.executable, "-c", "print('will not be run')"],
235 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000236 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000237 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000238
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300239 def test_check_output_stdin_with_input_arg(self):
240 # check_output() refuses to accept 'stdin' with 'input'
241 tf = tempfile.TemporaryFile()
242 self.addCleanup(tf.close)
243 tf.write(b'pear')
244 tf.seek(0)
245 with self.assertRaises(ValueError) as c:
246 output = subprocess.check_output(
247 [sys.executable, "-c", "print('will not be run')"],
248 stdin=tf, input=b'hare')
249 self.fail("Expected ValueError when stdin and input args supplied.")
250 self.assertIn('stdin', c.exception.args[0])
251 self.assertIn('input', c.exception.args[0])
252
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400253 def test_check_output_timeout(self):
254 # check_output() function with timeout arg
255 with self.assertRaises(subprocess.TimeoutExpired) as c:
256 output = subprocess.check_output(
257 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200258 "import sys, time\n"
259 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400260 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200261 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400262 # Some heavily loaded buildbots (sparc Debian 3.x) require
263 # this much time to start and print.
264 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400265 self.fail("Expected TimeoutExpired.")
266 self.assertEqual(c.exception.output, b'BDFL')
267
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000269 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270 newenv = os.environ.copy()
271 newenv["FRUIT"] = "banana"
272 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000273 'import sys, os;'
274 'sys.exit(os.getenv("FRUIT")=="banana")'],
275 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276 self.assertEqual(rc, 1)
277
Victor Stinner87b9bc32011-06-01 00:57:47 +0200278 def test_invalid_args(self):
279 # Popen() called with invalid arguments should raise TypeError
280 # but Popen.__del__ should not complain (issue #12085)
281 with support.captured_stderr() as s:
282 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
283 argcount = subprocess.Popen.__init__.__code__.co_argcount
284 too_many_args = [0] * (argcount + 1)
285 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
286 self.assertEqual(s.getvalue(), '')
287
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000288 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000289 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000290 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000292 self.addCleanup(p.stdout.close)
293 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294 p.wait()
295 self.assertEqual(p.stdin, None)
296
297 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200298 # .stdout is None when not redirected, and the child's stdout will
299 # be inherited from the parent. In order to test this we run a
300 # subprocess in a subprocess:
301 # this_test
302 # \-- subprocess created by this test (parent)
303 # \-- subprocess created by the parent subprocess (child)
304 # The parent doesn't specify stdout, so the child will use the
305 # parent's stdout. This test checks that the message printed by the
306 # child goes to the parent stdout. The parent also checks that the
307 # child's stdout is None. See #11963.
308 code = ('import sys; from subprocess import Popen, PIPE;'
309 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
310 ' stdin=PIPE, stderr=PIPE);'
311 'p.wait(); assert p.stdout is None;')
312 p = subprocess.Popen([sys.executable, "-c", code],
313 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
314 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000315 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200316 out, err = p.communicate()
317 self.assertEqual(p.returncode, 0, err)
318 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000319
320 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000321 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000322 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000323 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000324 self.addCleanup(p.stdout.close)
325 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000326 p.wait()
327 self.assertEqual(p.stderr, None)
328
Chris Jerdonek776cb192012-10-08 15:56:43 -0700329 def _assert_python(self, pre_args, **kwargs):
330 # We include sys.exit() to prevent the test runner from hanging
331 # whenever python is found.
332 args = pre_args + ["import sys; sys.exit(47)"]
333 p = subprocess.Popen(args, **kwargs)
334 p.wait()
335 self.assertEqual(47, p.returncode)
336
337 def test_executable(self):
338 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700339 #
340 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
341 # determine where its standard library is, so we need the directory
342 # of args[0] to be valid for the Popen() call to Python to succeed.
343 # See also issue #16170 and issue #7774.
344 doesnotexist = os.path.join(os.path.dirname(sys.executable),
345 "doesnotexist")
346 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700347
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300348 def test_bytes_executable(self):
349 doesnotexist = os.path.join(os.path.dirname(sys.executable),
350 "doesnotexist")
351 self._assert_python([doesnotexist, "-c"],
352 executable=os.fsencode(sys.executable))
353
354 def test_pathlike_executable(self):
355 doesnotexist = os.path.join(os.path.dirname(sys.executable),
356 "doesnotexist")
357 self._assert_python([doesnotexist, "-c"],
358 executable=FakePath(sys.executable))
359
Chris Jerdonek776cb192012-10-08 15:56:43 -0700360 def test_executable_takes_precedence(self):
361 # Check that the executable argument takes precedence over args[0].
362 #
363 # Verify first that the call succeeds without the executable arg.
364 pre_args = [sys.executable, "-c"]
365 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100366 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100367 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100368 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700369
Victor Stinner937ee9e2018-06-26 02:11:06 +0200370 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700371 def test_executable_replaces_shell(self):
372 # Check that the executable argument replaces the default shell
373 # when shell=True.
374 self._assert_python([], executable=sys.executable, shell=True)
375
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300376 @unittest.skipIf(mswindows, "executable argument replaces shell")
377 def test_bytes_executable_replaces_shell(self):
378 self._assert_python([], executable=os.fsencode(sys.executable),
379 shell=True)
380
381 @unittest.skipIf(mswindows, "executable argument replaces shell")
382 def test_pathlike_executable_replaces_shell(self):
383 self._assert_python([], executable=FakePath(sys.executable),
384 shell=True)
385
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700386 # For use in the test_cwd* tests below.
387 def _normalize_cwd(self, cwd):
388 # Normalize an expected cwd (for Tru64 support).
389 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
390 # strings. See bug #1063571.
Hai Shi0c4f0f32020-06-30 21:46:31 +0800391 with os_helper.change_cwd(cwd):
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300392 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700393
394 # For use in the test_cwd* tests below.
395 def _split_python_path(self):
396 # Return normalized (python_dir, python_base).
397 python_path = os.path.realpath(sys.executable)
398 return os.path.split(python_path)
399
400 # For use in the test_cwd* tests below.
401 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
402 # Invoke Python via Popen, and assert that (1) the call succeeds,
403 # and that (2) the current working directory of the child process
404 # matches *expected_cwd*.
405 p = subprocess.Popen([python_arg, "-c",
406 "import os, sys; "
Serhiy Storchakab1a87302020-07-26 10:21:39 +0300407 "buf = sys.stdout.buffer; "
408 "buf.write(os.getcwd().encode()); "
409 "buf.flush(); "
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700410 "sys.exit(47)"],
411 stdout=subprocess.PIPE,
412 **kwargs)
413 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000414 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700415 self.assertEqual(47, p.returncode)
416 normcase = os.path.normcase
417 self.assertEqual(normcase(expected_cwd),
Serhiy Storchakab1a87302020-07-26 10:21:39 +0300418 normcase(p.stdout.read().decode()))
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700419
420 def test_cwd(self):
421 # Check that cwd changes the cwd for the child process.
422 temp_dir = tempfile.gettempdir()
423 temp_dir = self._normalize_cwd(temp_dir)
424 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
425
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300426 def test_cwd_with_bytes(self):
427 temp_dir = tempfile.gettempdir()
428 temp_dir = self._normalize_cwd(temp_dir)
429 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
430
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530431 def test_cwd_with_pathlike(self):
432 temp_dir = tempfile.gettempdir()
433 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200434 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530435
Victor Stinner937ee9e2018-06-26 02:11:06 +0200436 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700437 def test_cwd_with_relative_arg(self):
438 # Check that Popen looks for args[0] relative to cwd if args[0]
439 # is relative.
440 python_dir, python_base = self._split_python_path()
441 rel_python = os.path.join(os.curdir, python_base)
Hai Shi0c4f0f32020-06-30 21:46:31 +0800442 with os_helper.temp_cwd() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700443 # Before calling with the correct cwd, confirm that the call fails
444 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700445 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700446 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700447 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700448 [rel_python], cwd=wrong_dir)
449 python_dir = self._normalize_cwd(python_dir)
450 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
451
Victor Stinner937ee9e2018-06-26 02:11:06 +0200452 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700453 def test_cwd_with_relative_executable(self):
454 # Check that Popen looks for executable relative to cwd if executable
455 # is relative (and that executable takes precedence over args[0]).
456 python_dir, python_base = self._split_python_path()
457 rel_python = os.path.join(os.curdir, python_base)
458 doesntexist = "somethingyoudonthave"
Hai Shi0c4f0f32020-06-30 21:46:31 +0800459 with os_helper.temp_cwd() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700460 # Before calling with the correct cwd, confirm that the call fails
461 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700462 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700463 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700464 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700465 [doesntexist], executable=rel_python,
466 cwd=wrong_dir)
467 python_dir = self._normalize_cwd(python_dir)
468 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
469 cwd=python_dir)
470
471 def test_cwd_with_absolute_arg(self):
472 # Check that Popen can find the executable when the cwd is wrong
473 # if args[0] is an absolute path.
474 python_dir, python_base = self._split_python_path()
475 abs_python = os.path.join(python_dir, python_base)
476 rel_python = os.path.join(os.curdir, python_base)
Hai Shi0c4f0f32020-06-30 21:46:31 +0800477 with os_helper.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700478 # Before calling with an absolute path, confirm that using a
479 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700480 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700481 [rel_python], cwd=wrong_dir)
482 wrong_dir = self._normalize_cwd(wrong_dir)
483 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
484
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100485 @unittest.skipIf(sys.base_prefix != sys.prefix,
486 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000487 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700488 python_dir, python_base = self._split_python_path()
489 python_dir = self._normalize_cwd(python_dir)
490 self._assert_cwd(python_dir, "somethingyoudonthave",
491 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000492
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100493 @unittest.skipIf(sys.base_prefix != sys.prefix,
494 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000495 @unittest.skipIf(sysconfig.is_python_build(),
496 "need an installed Python. See #7774")
497 def test_executable_without_cwd(self):
498 # For a normal installation, it should work without 'cwd'
499 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700500 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
501 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502
503 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000504 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000505 p = subprocess.Popen([sys.executable, "-c",
506 'import sys; sys.exit(sys.stdin.read() == "pear")'],
507 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000508 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000509 p.stdin.close()
510 p.wait()
511 self.assertEqual(p.returncode, 1)
512
513 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000514 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000515 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000516 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000518 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000519 os.lseek(d, 0, 0)
520 p = subprocess.Popen([sys.executable, "-c",
521 'import sys; sys.exit(sys.stdin.read() == "pear")'],
522 stdin=d)
523 p.wait()
524 self.assertEqual(p.returncode, 1)
525
526 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000527 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000529 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000530 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 tf.seek(0)
532 p = subprocess.Popen([sys.executable, "-c",
533 'import sys; sys.exit(sys.stdin.read() == "pear")'],
534 stdin=tf)
535 p.wait()
536 self.assertEqual(p.returncode, 1)
537
538 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000539 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540 p = subprocess.Popen([sys.executable, "-c",
541 'import sys; sys.stdout.write("orange")'],
542 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200543 with p:
544 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545
546 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000547 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000548 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000549 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000550 d = tf.fileno()
551 p = subprocess.Popen([sys.executable, "-c",
552 'import sys; sys.stdout.write("orange")'],
553 stdout=d)
554 p.wait()
555 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000556 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000557
558 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000559 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000560 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000561 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000562 p = subprocess.Popen([sys.executable, "-c",
563 'import sys; sys.stdout.write("orange")'],
564 stdout=tf)
565 p.wait()
566 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000567 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568
569 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000570 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000571 p = subprocess.Popen([sys.executable, "-c",
572 'import sys; sys.stderr.write("strawberry")'],
573 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200574 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100575 self.assertEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000576
577 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000578 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000579 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000580 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000581 d = tf.fileno()
582 p = subprocess.Popen([sys.executable, "-c",
583 'import sys; sys.stderr.write("strawberry")'],
584 stderr=d)
585 p.wait()
586 os.lseek(d, 0, 0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100587 self.assertEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000588
589 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000590 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000591 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000592 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000593 p = subprocess.Popen([sys.executable, "-c",
594 'import sys; sys.stderr.write("strawberry")'],
595 stderr=tf)
596 p.wait()
597 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100598 self.assertEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000599
Martin Panterc7635892016-05-13 01:54:44 +0000600 def test_stderr_redirect_with_no_stdout_redirect(self):
601 # test stderr=STDOUT while stdout=None (not set)
602
603 # - grandchild prints to stderr
604 # - child redirects grandchild's stderr to its stdout
605 # - the parent should get grandchild's stderr in child's stdout
606 p = subprocess.Popen([sys.executable, "-c",
607 'import sys, subprocess;'
608 'rc = subprocess.call([sys.executable, "-c",'
609 ' "import sys;"'
610 ' "sys.stderr.write(\'42\')"],'
611 ' stderr=subprocess.STDOUT);'
612 'sys.exit(rc)'],
613 stdout=subprocess.PIPE,
614 stderr=subprocess.PIPE)
615 stdout, stderr = p.communicate()
616 #NOTE: stdout should get stderr from grandchild
Victor Stinner6cac1132019-12-08 08:38:16 +0100617 self.assertEqual(stdout, b'42')
618 self.assertEqual(stderr, b'') # should be empty
Martin Panterc7635892016-05-13 01:54:44 +0000619 self.assertEqual(p.returncode, 0)
620
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000621 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000622 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000623 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000624 'import sys;'
625 'sys.stdout.write("apple");'
626 'sys.stdout.flush();'
627 'sys.stderr.write("orange")'],
628 stdout=subprocess.PIPE,
629 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200630 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100631 self.assertEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000632
633 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000634 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000635 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000636 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000637 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000638 'import sys;'
639 'sys.stdout.write("apple");'
640 'sys.stdout.flush();'
641 'sys.stderr.write("orange")'],
642 stdout=tf,
643 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000644 p.wait()
645 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100646 self.assertEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647
Thomas Wouters89f507f2006-12-13 04:49:30 +0000648 def test_stdout_filedes_of_stdout(self):
649 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200650 # To avoid printing the text on stdout, we do something similar to
651 # test_stdout_none (see above). The parent subprocess calls the child
652 # subprocess passing stdout=1, and this test uses stdout=PIPE in
653 # order to capture and check the output of the parent. See #11963.
654 code = ('import sys, subprocess; '
655 'rc = subprocess.call([sys.executable, "-c", '
656 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
657 'b\'test with stdout=1\'))"], stdout=1); '
658 'assert rc == 18')
659 p = subprocess.Popen([sys.executable, "-c", code],
660 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
661 self.addCleanup(p.stdout.close)
662 self.addCleanup(p.stderr.close)
663 out, err = p.communicate()
664 self.assertEqual(p.returncode, 0, err)
665 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000666
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200667 def test_stdout_devnull(self):
668 p = subprocess.Popen([sys.executable, "-c",
669 'for i in range(10240):'
670 'print("x" * 1024)'],
671 stdout=subprocess.DEVNULL)
672 p.wait()
673 self.assertEqual(p.stdout, None)
674
675 def test_stderr_devnull(self):
676 p = subprocess.Popen([sys.executable, "-c",
677 'import sys\n'
678 'for i in range(10240):'
679 'sys.stderr.write("x" * 1024)'],
680 stderr=subprocess.DEVNULL)
681 p.wait()
682 self.assertEqual(p.stderr, None)
683
684 def test_stdin_devnull(self):
685 p = subprocess.Popen([sys.executable, "-c",
686 'import sys;'
687 'sys.stdin.read(1)'],
688 stdin=subprocess.DEVNULL)
689 p.wait()
690 self.assertEqual(p.stdin, None)
691
Gregory P. Smith786addd2020-10-20 17:37:20 -0700692 @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'),
693 'fcntl.F_GETPIPE_SZ required for test.')
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200694 def test_pipesizes(self):
Gregory P. Smith786addd2020-10-20 17:37:20 -0700695 test_pipe_r, test_pipe_w = os.pipe()
696 try:
697 # Get the default pipesize with F_GETPIPE_SZ
698 pipesize_default = fcntl.fcntl(test_pipe_w, fcntl.F_GETPIPE_SZ)
699 finally:
700 os.close(test_pipe_r)
701 os.close(test_pipe_w)
702 pipesize = pipesize_default // 2
703 if pipesize < 512: # the POSIX minimum
704 raise unittest.SkitTest(
705 'default pipesize too small to perform test.')
706 p = subprocess.Popen(
707 [sys.executable, "-c",
708 'import sys; sys.stdin.read(); sys.stdout.write("out"); '
709 'sys.stderr.write("error!")'],
710 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
711 stderr=subprocess.PIPE, pipesize=pipesize)
712 try:
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200713 for fifo in [p.stdin, p.stdout, p.stderr]:
714 self.assertEqual(
Gregory P. Smith786addd2020-10-20 17:37:20 -0700715 fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ),
716 pipesize)
717 # Windows pipe size can be acquired via GetNamedPipeInfoFunction
718 # https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-getnamedpipeinfo
719 # However, this function is not yet in _winapi.
720 p.stdin.write(b"pear")
721 p.stdin.close()
722 finally:
723 p.kill()
724 p.wait()
725
726 @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'),
727 'fcntl.F_GETPIPE_SZ required for test.')
728 def test_pipesize_default(self):
729 p = subprocess.Popen(
730 [sys.executable, "-c",
731 'import sys; sys.stdin.read(); sys.stdout.write("out"); '
732 'sys.stderr.write("error!")'],
733 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
734 stderr=subprocess.PIPE, pipesize=-1)
735 try:
736 fp_r, fp_w = os.pipe()
737 try:
738 default_pipesize = fcntl.fcntl(fp_w, fcntl.F_GETPIPE_SZ)
739 for fifo in [p.stdin, p.stdout, p.stderr]:
740 self.assertEqual(
741 fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ),
742 default_pipesize)
743 finally:
744 os.close(fp_r)
745 os.close(fp_w)
746 # On other platforms we cannot test the pipe size (yet). But above
747 # code using pipesize=-1 should not crash.
748 p.stdin.close()
749 finally:
750 p.kill()
751 p.wait()
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200752
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000753 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000754 newenv = os.environ.copy()
755 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200756 with subprocess.Popen([sys.executable, "-c",
757 'import sys,os;'
758 'sys.stdout.write(os.getenv("FRUIT"))'],
759 stdout=subprocess.PIPE,
760 env=newenv) as p:
761 stdout, stderr = p.communicate()
762 self.assertEqual(stdout, b"orange")
763
Victor Stinner62d51182011-06-23 01:02:25 +0200764 # Windows requires at least the SYSTEMROOT environment variable to start
765 # Python
766 @unittest.skipIf(sys.platform == 'win32',
767 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700768 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
769 'The Python shared library cannot be loaded '
770 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200771 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700772 """Verify that env={} is as empty as possible."""
773
Gregory P. Smith85aba232017-05-30 16:21:47 -0700774 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700775 """Determine if an environment variable is under our control."""
776 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
777 # on adding even when the environment in exec is empty.
778 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700779 return ('VERSIONER' in n or '__CF' in n or # MacOS
Nick Coghlan6ea41862017-06-11 13:16:15 +1000780 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
781 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700782
Victor Stinnerf1512a22011-06-21 17:18:38 +0200783 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700784 'import os; print(list(os.environ.keys()))'],
785 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200786 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700787 child_env_names = eval(stdout.strip())
788 self.assertIsInstance(child_env_names, list)
789 child_env_names = [k for k in child_env_names
790 if not is_env_var_to_ignore(k)]
791 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000792
Serhiy Storchakad174d242017-06-23 19:39:27 +0300793 def test_invalid_cmd(self):
794 # null character in the command name
795 cmd = sys.executable + '\0'
796 with self.assertRaises(ValueError):
797 subprocess.Popen([cmd, "-c", "pass"])
798
799 # null character in the command argument
800 with self.assertRaises(ValueError):
801 subprocess.Popen([sys.executable, "-c", "pass#\0"])
802
803 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300804 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300805 newenv = os.environ.copy()
806 newenv["FRUIT\0VEGETABLE"] = "cabbage"
807 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700808 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300809
Ville Skyttä49b27342017-08-03 09:00:59 +0300810 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300811 newenv = os.environ.copy()
812 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
813 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700814 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300815
Ville Skyttä49b27342017-08-03 09:00:59 +0300816 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300817 newenv = os.environ.copy()
818 newenv["FRUIT=ORANGE"] = "lemon"
819 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700820 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300821
Ville Skyttä49b27342017-08-03 09:00:59 +0300822 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300823 newenv = os.environ.copy()
824 newenv["FRUIT"] = "orange=lemon"
825 with subprocess.Popen([sys.executable, "-c",
826 'import sys, os;'
827 'sys.stdout.write(os.getenv("FRUIT"))'],
828 stdout=subprocess.PIPE,
829 env=newenv) as p:
830 stdout, stderr = p.communicate()
831 self.assertEqual(stdout, b"orange=lemon")
832
Peter Astrandcbac93c2005-03-03 20:24:28 +0000833 def test_communicate_stdin(self):
834 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000835 'import sys;'
836 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000837 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000838 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000839 self.assertEqual(p.returncode, 1)
840
841 def test_communicate_stdout(self):
842 p = subprocess.Popen([sys.executable, "-c",
843 'import sys; sys.stdout.write("pineapple")'],
844 stdout=subprocess.PIPE)
845 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000846 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000847 self.assertEqual(stderr, None)
848
849 def test_communicate_stderr(self):
850 p = subprocess.Popen([sys.executable, "-c",
851 'import sys; sys.stderr.write("pineapple")'],
852 stderr=subprocess.PIPE)
853 (stdout, stderr) = p.communicate()
854 self.assertEqual(stdout, None)
Victor Stinner6cac1132019-12-08 08:38:16 +0100855 self.assertEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000856
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000857 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000859 'import sys,os;'
860 'sys.stderr.write("pineapple");'
861 'sys.stdout.write(sys.stdin.read())'],
862 stdin=subprocess.PIPE,
863 stdout=subprocess.PIPE,
864 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000865 self.addCleanup(p.stdout.close)
866 self.addCleanup(p.stderr.close)
867 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000868 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000869 self.assertEqual(stdout, b"banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100870 self.assertEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000871
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400872 def test_communicate_timeout(self):
873 p = subprocess.Popen([sys.executable, "-c",
874 'import sys,os,time;'
875 'sys.stderr.write("pineapple\\n");'
876 'time.sleep(1);'
877 'sys.stderr.write("pear\\n");'
878 'sys.stdout.write(sys.stdin.read())'],
879 universal_newlines=True,
880 stdin=subprocess.PIPE,
881 stdout=subprocess.PIPE,
882 stderr=subprocess.PIPE)
883 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
884 timeout=0.3)
885 # Make sure we can keep waiting for it, and that we get the whole output
886 # after it completes.
887 (stdout, stderr) = p.communicate()
888 self.assertEqual(stdout, "banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100889 self.assertEqual(stderr.encode(), b"pineapple\npear\n")
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400890
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700891 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200892 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400893 p = subprocess.Popen([sys.executable, "-c",
894 'import sys,os,time;'
895 'sys.stdout.write("a" * (64 * 1024));'
896 'time.sleep(0.2);'
897 'sys.stdout.write("a" * (64 * 1024));'
898 'time.sleep(0.2);'
899 'sys.stdout.write("a" * (64 * 1024));'
900 'time.sleep(0.2);'
901 'sys.stdout.write("a" * (64 * 1024));'],
902 stdout=subprocess.PIPE)
903 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
904 (stdout, _) = p.communicate()
905 self.assertEqual(len(stdout), 4 * 64 * 1024)
906
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000907 # Test for the fd leak reported in http://bugs.python.org/issue2791.
908 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000909 for stdin_pipe in (False, True):
910 for stdout_pipe in (False, True):
911 for stderr_pipe in (False, True):
912 options = {}
913 if stdin_pipe:
914 options['stdin'] = subprocess.PIPE
915 if stdout_pipe:
916 options['stdout'] = subprocess.PIPE
917 if stderr_pipe:
918 options['stderr'] = subprocess.PIPE
919 if not options:
920 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700921 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000922 p.communicate()
923 if p.stdin is not None:
924 self.assertTrue(p.stdin.closed)
925 if p.stdout is not None:
926 self.assertTrue(p.stdout.closed)
927 if p.stderr is not None:
928 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000929
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000930 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000931 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000932 p = subprocess.Popen([sys.executable, "-c",
933 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000934 (stdout, stderr) = p.communicate()
935 self.assertEqual(stdout, None)
936 self.assertEqual(stderr, None)
937
938 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000939 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000941 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000942 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000943 os.close(x)
944 os.close(y)
945 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000946 'import sys,os;'
947 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200948 'sys.stderr.write("x" * %d);'
949 'sys.stdout.write(sys.stdin.read())' %
950 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000951 stdin=subprocess.PIPE,
952 stdout=subprocess.PIPE,
953 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000954 self.addCleanup(p.stdout.close)
955 self.addCleanup(p.stderr.close)
956 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200957 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000958 (stdout, stderr) = p.communicate(string_to_write)
959 self.assertEqual(stdout, string_to_write)
960
961 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000962 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000963 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000964 'import sys,os;'
965 'sys.stdout.write(sys.stdin.read())'],
966 stdin=subprocess.PIPE,
967 stdout=subprocess.PIPE,
968 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000969 self.addCleanup(p.stdout.close)
970 self.addCleanup(p.stderr.close)
971 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000972 p.stdin.write(b"banana")
973 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000974 self.assertEqual(stdout, b"bananasplit")
Victor Stinner6cac1132019-12-08 08:38:16 +0100975 self.assertEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000976
andyclegg7fed7bd2017-10-23 03:01:19 +0100977 def test_universal_newlines_and_text(self):
978 args = [
979 sys.executable, "-c",
980 'import sys,os;' + SETBINARY +
981 'buf = sys.stdout.buffer;'
982 'buf.write(sys.stdin.readline().encode());'
983 'buf.flush();'
984 'buf.write(b"line2\\n");'
985 'buf.flush();'
986 'buf.write(sys.stdin.read().encode());'
987 'buf.flush();'
988 'buf.write(b"line4\\n");'
989 'buf.flush();'
990 'buf.write(b"line5\\r\\n");'
991 'buf.flush();'
992 'buf.write(b"line6\\r");'
993 'buf.flush();'
994 'buf.write(b"\\nline7");'
995 'buf.flush();'
996 'buf.write(b"\\nline8");']
997
998 for extra_kwarg in ('universal_newlines', 'text'):
999 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
1000 'stdout': subprocess.PIPE,
1001 extra_kwarg: True})
1002 with p:
1003 p.stdin.write("line1\n")
1004 p.stdin.flush()
1005 self.assertEqual(p.stdout.readline(), "line1\n")
1006 p.stdin.write("line3\n")
1007 p.stdin.close()
1008 self.addCleanup(p.stdout.close)
1009 self.assertEqual(p.stdout.readline(),
1010 "line2\n")
1011 self.assertEqual(p.stdout.read(6),
1012 "line3\n")
1013 self.assertEqual(p.stdout.read(),
1014 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001015
1016 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001017 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001018 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +00001019 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +02001020 'buf = sys.stdout.buffer;'
1021 'buf.write(b"line2\\n");'
1022 'buf.flush();'
1023 'buf.write(b"line4\\n");'
1024 'buf.flush();'
1025 'buf.write(b"line5\\r\\n");'
1026 'buf.flush();'
1027 'buf.write(b"line6\\r");'
1028 'buf.flush();'
1029 'buf.write(b"\\nline7");'
1030 'buf.flush();'
1031 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001032 stderr=subprocess.PIPE,
1033 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +00001034 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +00001035 self.addCleanup(p.stdout.close)
1036 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001037 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001038 self.assertEqual(stdout,
1039 "line2\nline4\nline5\nline6\nline7\nline8")
1040
1041 def test_universal_newlines_communicate_stdin(self):
1042 # universal newlines through communicate(), with only stdin
1043 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001044 'import sys,os;' + SETBINARY + textwrap.dedent('''
1045 s = sys.stdin.readline()
1046 assert s == "line1\\n", repr(s)
1047 s = sys.stdin.read()
1048 assert s == "line3\\n", repr(s)
1049 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001050 stdin=subprocess.PIPE,
1051 universal_newlines=1)
1052 (stdout, stderr) = p.communicate("line1\nline3\n")
1053 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001054
Andrew Svetlovf3765072012-08-14 18:35:17 +03001055 def test_universal_newlines_communicate_input_none(self):
1056 # Test communicate(input=None) with universal newlines.
1057 #
1058 # We set stdout to PIPE because, as of this writing, a different
1059 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001060 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +03001061 stdin=subprocess.PIPE,
1062 stdout=subprocess.PIPE,
1063 universal_newlines=True)
1064 p.communicate()
1065 self.assertEqual(p.returncode, 0)
1066
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001067 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001068 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001069 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001070 'import sys,os;' + SETBINARY + textwrap.dedent('''
1071 s = sys.stdin.buffer.readline()
1072 sys.stdout.buffer.write(s)
1073 sys.stdout.buffer.write(b"line2\\r")
1074 sys.stderr.buffer.write(b"eline2\\n")
1075 s = sys.stdin.buffer.read()
1076 sys.stdout.buffer.write(s)
1077 sys.stdout.buffer.write(b"line4\\n")
1078 sys.stdout.buffer.write(b"line5\\r\\n")
1079 sys.stderr.buffer.write(b"eline6\\r")
1080 sys.stderr.buffer.write(b"eline7\\r\\nz")
1081 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001082 stdin=subprocess.PIPE,
1083 stderr=subprocess.PIPE,
1084 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001085 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001086 self.addCleanup(p.stdout.close)
1087 self.addCleanup(p.stderr.close)
1088 (stdout, stderr) = p.communicate("line1\nline3\n")
1089 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001090 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001091 # Python debug build push something like "[42442 refs]\n"
1092 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001093 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001094
Andrew Svetlov82860712012-08-19 22:13:41 +03001095 def test_universal_newlines_communicate_encodings(self):
1096 # Check that universal newlines mode works for various encodings,
1097 # in particular for encodings in the UTF-16 and UTF-32 families.
1098 # See issue #15595.
1099 #
1100 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1101 # without, and UTF-16 and UTF-32.
1102 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001103 code = ("import sys; "
1104 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1105 encoding)
1106 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001107 # We set stdin to be non-None because, as of this writing,
1108 # a different code path is used when the number of pipes is
1109 # zero or one.
1110 popen = subprocess.Popen(args,
1111 stdin=subprocess.PIPE,
1112 stdout=subprocess.PIPE,
1113 encoding=encoding)
1114 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001115 self.assertEqual(stdout, '1\n2\n3\n4')
1116
Steve Dower050acae2016-09-06 20:16:17 -07001117 def test_communicate_errors(self):
1118 for errors, expected in [
1119 ('ignore', ''),
1120 ('replace', '\ufffd\ufffd'),
1121 ('surrogateescape', '\udc80\udc80'),
1122 ('backslashreplace', '\\x80\\x80'),
1123 ]:
1124 code = ("import sys; "
1125 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1126 args = [sys.executable, '-c', code]
1127 # We set stdin to be non-None because, as of this writing,
1128 # a different code path is used when the number of pipes is
1129 # zero or one.
1130 popen = subprocess.Popen(args,
1131 stdin=subprocess.PIPE,
1132 stdout=subprocess.PIPE,
1133 encoding='utf-8',
1134 errors=errors)
1135 stdout, stderr = popen.communicate(input='')
1136 self.assertEqual(stdout, '[{}]'.format(expected))
1137
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001138 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001139 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001140 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001141 max_handles = 1026 # too much for most UNIX systems
1142 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001143 max_handles = 2050 # too much for (at least some) Windows setups
1144 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001145 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001146 try:
1147 for i in range(max_handles):
1148 try:
Hai Shi0c4f0f32020-06-30 21:46:31 +08001149 tmpfile = os.path.join(tmpdir, os_helper.TESTFN)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001150 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001151 except OSError as e:
1152 if e.errno != errno.EMFILE:
1153 raise
1154 break
1155 else:
1156 self.skipTest("failed to reach the file descriptor limit "
1157 "(tried %d)" % max_handles)
1158 # Close a couple of them (should be enough for a subprocess)
1159 for i in range(10):
1160 os.close(handles.pop())
1161 # Loop creating some subprocesses. If one of them leaks some fds,
1162 # the next loop iteration will fail by reaching the max fd limit.
1163 for i in range(15):
1164 p = subprocess.Popen([sys.executable, "-c",
1165 "import sys;"
1166 "sys.stdout.write(sys.stdin.read())"],
1167 stdin=subprocess.PIPE,
1168 stdout=subprocess.PIPE,
1169 stderr=subprocess.PIPE)
1170 data = p.communicate(b"lime")[0]
1171 self.assertEqual(data, b"lime")
1172 finally:
1173 for h in handles:
1174 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001175 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001176
1177 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001178 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1179 '"a b c" d e')
1180 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1181 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001182 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1183 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001184 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1185 'a\\\\\\b "de fg" h')
1186 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1187 'a\\\\\\"b c d')
1188 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1189 '"a\\\\b c" d e')
1190 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1191 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001192 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1193 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001194
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001195 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001196 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001197 "import os; os.read(0, 1)"],
1198 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001199 self.addCleanup(p.stdin.close)
1200 self.assertIsNone(p.poll())
1201 os.write(p.stdin.fileno(), b'A')
1202 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001203 # Subsequent invocations should just return the returncode
1204 self.assertEqual(p.poll(), 0)
1205
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001206 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001207 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001208 self.assertEqual(p.wait(), 0)
1209 # Subsequent invocations should just return the returncode
1210 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001211
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001212 def test_wait_timeout(self):
1213 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001214 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001215 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001216 p.wait(timeout=0.0001)
1217 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001218 self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001219
Peter Astrand738131d2004-11-30 21:04:45 +00001220 def test_invalid_bufsize(self):
1221 # an invalid type of the bufsize argument should raise
1222 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001223 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001224 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001225
Guido van Rossum46a05a72007-06-07 21:56:45 +00001226 def test_bufsize_is_none(self):
1227 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001228 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001229 self.assertEqual(p.wait(), 0)
1230 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001231 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001232 self.assertEqual(p.wait(), 0)
1233
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001234 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1235 # subprocess may deadlock with bufsize=1, see issue #21332
1236 with subprocess.Popen([sys.executable, "-c", "import sys;"
1237 "sys.stdout.write(sys.stdin.readline());"
1238 "sys.stdout.flush()"],
1239 stdin=subprocess.PIPE,
1240 stdout=subprocess.PIPE,
1241 stderr=subprocess.DEVNULL,
1242 bufsize=1,
1243 universal_newlines=universal_newlines) as p:
1244 p.stdin.write(line) # expect that it flushes the line in text mode
1245 os.close(p.stdin.fileno()) # close it without flushing the buffer
1246 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001247 with support.SuppressCrashReport():
1248 try:
1249 p.stdin.close()
1250 except OSError:
1251 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001252 p.stdin = None
1253 self.assertEqual(p.returncode, 0)
1254 self.assertEqual(read_line, expected)
1255
1256 def test_bufsize_equal_one_text_mode(self):
1257 # line is flushed in text mode with bufsize=1.
1258 # we should get the full line in return
1259 line = "line\n"
1260 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1261
1262 def test_bufsize_equal_one_binary_mode(self):
1263 # line is not flushed in binary mode with bufsize=1.
1264 # we should get empty response
1265 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001266 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1267 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001268
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001269 def test_leaking_fds_on_error(self):
1270 # see bug #5179: Popen leaks file descriptors to PIPEs if
1271 # the child fails to execute; this will eventually exhaust
1272 # the maximum number of open fds. 1024 seems a very common
1273 # value for that limit, but Windows has 2048, so we loop
1274 # 1024 times (each call leaked two fds).
1275 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001276 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001277 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001278 stdout=subprocess.PIPE,
1279 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001280
Victor Stinner9a83f652017-08-21 23:51:31 +02001281 def test_nonexisting_with_pipes(self):
1282 # bpo-30121: Popen with pipes must close properly pipes on error.
1283 # Previously, os.close() was called with a Windows handle which is not
1284 # a valid file descriptor.
1285 #
1286 # Run the test in a subprocess to control how the CRT reports errors
1287 # and to get stderr content.
1288 try:
1289 import msvcrt
1290 msvcrt.CrtSetReportMode
1291 except (AttributeError, ImportError):
1292 self.skipTest("need msvcrt.CrtSetReportMode")
1293
1294 code = textwrap.dedent(f"""
1295 import msvcrt
1296 import subprocess
1297
1298 cmd = {NONEXISTING_CMD!r}
1299
1300 for report_type in [msvcrt.CRT_WARN,
1301 msvcrt.CRT_ERROR,
1302 msvcrt.CRT_ASSERT]:
1303 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1304 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1305
1306 try:
Zachary Ware55376462018-02-19 14:02:38 -06001307 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001308 stdout=subprocess.PIPE,
1309 stderr=subprocess.PIPE)
1310 except OSError:
1311 pass
1312 """)
1313 cmd = [sys.executable, "-c", code]
1314 proc = subprocess.Popen(cmd,
1315 stderr=subprocess.PIPE,
1316 universal_newlines=True)
1317 with proc:
1318 stderr = proc.communicate()[1]
1319 self.assertEqual(stderr, "")
1320 self.assertEqual(proc.returncode, 0)
1321
Antoine Pitroua8392712013-08-30 23:38:13 +02001322 def test_double_close_on_error(self):
1323 # Issue #18851
1324 fds = []
1325 def open_fds():
1326 for i in range(20):
1327 fds.extend(os.pipe())
1328 time.sleep(0.001)
1329 t = threading.Thread(target=open_fds)
1330 t.start()
1331 try:
1332 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001333 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001334 stdin=subprocess.PIPE,
1335 stdout=subprocess.PIPE,
1336 stderr=subprocess.PIPE)
1337 finally:
1338 t.join()
1339 exc = None
1340 for fd in fds:
1341 # If a double close occurred, some of those fds will
1342 # already have been closed by mistake, and os.close()
1343 # here will raise.
1344 try:
1345 os.close(fd)
1346 except OSError as e:
1347 exc = e
1348 if exc is not None:
1349 raise exc
1350
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001351 def test_threadsafe_wait(self):
1352 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1353 proc = subprocess.Popen([sys.executable, '-c',
1354 'import time; time.sleep(12)'])
1355 self.assertEqual(proc.returncode, None)
1356 results = []
1357
1358 def kill_proc_timer_thread():
1359 results.append(('thread-start-poll-result', proc.poll()))
1360 # terminate it from the thread and wait for the result.
1361 proc.kill()
1362 proc.wait()
1363 results.append(('thread-after-kill-and-wait', proc.returncode))
1364 # this wait should be a no-op given the above.
1365 proc.wait()
1366 results.append(('thread-after-second-wait', proc.returncode))
1367
1368 # This is a timing sensitive test, the failure mode is
1369 # triggered when both the main thread and this thread are in
1370 # the wait() call at once. The delay here is to allow the
1371 # main thread to most likely be blocked in its wait() call.
1372 t = threading.Timer(0.2, kill_proc_timer_thread)
1373 t.start()
1374
Victor Stinner937ee9e2018-06-26 02:11:06 +02001375 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001376 expected_errorcode = 1
1377 else:
1378 # Should be -9 because of the proc.kill() from the thread.
1379 expected_errorcode = -9
1380
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001381 # Wait for the process to finish; the thread should kill it
1382 # long before it finishes on its own. Supplying a timeout
1383 # triggers a different code path for better coverage.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001384 proc.wait(timeout=support.SHORT_TIMEOUT)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001385 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001386 msg="unexpected result in wait from main thread")
1387
1388 # This should be a no-op with no change in returncode.
1389 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001390 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001391 msg="unexpected result in second main wait.")
1392
1393 t.join()
1394 # Ensure that all of the thread results are as expected.
1395 # When a race condition occurs in wait(), the returncode could
1396 # be set by the wrong thread that doesn't actually have it
1397 # leading to an incorrect value.
1398 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001399 ('thread-after-kill-and-wait', expected_errorcode),
1400 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001401 results)
1402
Victor Stinnerb3693582010-05-21 20:13:12 +00001403 def test_issue8780(self):
1404 # Ensure that stdout is inherited from the parent
1405 # if stdout=PIPE is not used
1406 code = ';'.join((
1407 'import subprocess, sys',
1408 'retcode = subprocess.call('
1409 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1410 'assert retcode == 0'))
1411 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001412 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001413
Tim Goldenaf5ac392010-08-06 13:03:56 +00001414 def test_handles_closed_on_exception(self):
1415 # If CreateProcess exits with an error, ensure the
1416 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001417 ifhandle, ifname = tempfile.mkstemp()
1418 ofhandle, ofname = tempfile.mkstemp()
1419 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001420 try:
1421 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1422 stderr=efhandle)
1423 except OSError:
1424 os.close(ifhandle)
1425 os.remove(ifname)
1426 os.close(ofhandle)
1427 os.remove(ofname)
1428 os.close(efhandle)
1429 os.remove(efname)
1430 self.assertFalse(os.path.exists(ifname))
1431 self.assertFalse(os.path.exists(ofname))
1432 self.assertFalse(os.path.exists(efname))
1433
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001434 def test_communicate_epipe(self):
1435 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001436 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001437 stdin=subprocess.PIPE,
1438 stdout=subprocess.PIPE,
1439 stderr=subprocess.PIPE)
1440 self.addCleanup(p.stdout.close)
1441 self.addCleanup(p.stderr.close)
1442 self.addCleanup(p.stdin.close)
1443 p.communicate(b"x" * 2**20)
1444
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001445 def test_repr(self):
M. Kocherdb0c5b72021-04-28 01:16:38 -07001446 path_cmd = pathlib.Path("my-tool.py")
1447 pathlib_cls = path_cmd.__class__.__name__
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001448
M. Kocherdb0c5b72021-04-28 01:16:38 -07001449 cases = [
1450 ("ls", True, 123, "<Popen: returncode: 123 args: 'ls'>"),
1451 ('a' * 100, True, 0,
1452 "<Popen: returncode: 0 args: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...>"),
1453 (["ls"], False, None, "<Popen: returncode: None args: ['ls']>"),
1454 (["ls", '--my-opts', 'a' * 100], False, None,
1455 "<Popen: returncode: None args: ['ls', '--my-opts', 'aaaaaaaaaaaaaaaaaaaaaaaa...>"),
1456 (path_cmd, False, 7, f"<Popen: returncode: 7 args: {pathlib_cls}('my-tool.py')>")
1457 ]
1458 with unittest.mock.patch.object(subprocess.Popen, '_execute_child'):
1459 for cmd, shell, code, sx in cases:
1460 p = subprocess.Popen(cmd, shell=shell)
1461 p.returncode = code
1462 self.assertEqual(repr(p), sx)
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001463
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001464 def test_communicate_epipe_only_stdin(self):
1465 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001466 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001467 stdin=subprocess.PIPE)
1468 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001469 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001470 p.communicate(b"x" * 2**20)
1471
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001472 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1473 "Requires signal.SIGUSR1")
1474 @unittest.skipUnless(hasattr(os, 'kill'),
1475 "Requires os.kill")
1476 @unittest.skipUnless(hasattr(os, 'getppid'),
1477 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001478 def test_communicate_eintr(self):
1479 # Issue #12493: communicate() should handle EINTR
1480 def handler(signum, frame):
1481 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001482 old_handler = signal.signal(signal.SIGUSR1, handler)
1483 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001484
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001485 args = [sys.executable, "-c",
1486 'import os, signal;'
1487 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001488 for stream in ('stdout', 'stderr'):
1489 kw = {stream: subprocess.PIPE}
1490 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001491 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001492 process.communicate()
1493
Tim Peterse718f612004-10-12 21:51:32 +00001494
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001495 # This test is Linux-ish specific for simplicity to at least have
1496 # some coverage. It is not a platform specific bug.
1497 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1498 "Linux specific")
1499 def test_failed_child_execute_fd_leak(self):
1500 """Test for the fork() failure fd leak reported in issue16327."""
1501 fd_directory = '/proc/%d/fd' % os.getpid()
1502 fds_before_popen = os.listdir(fd_directory)
1503 with self.assertRaises(PopenTestException):
1504 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001505 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001506 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1507
1508 # NOTE: This test doesn't verify that the real _execute_child
1509 # does not close the file descriptors itself on the way out
1510 # during an exception. Code inspection has confirmed that.
1511
1512 fds_after_exception = os.listdir(fd_directory)
1513 self.assertEqual(fds_before_popen, fds_after_exception)
1514
Victor Stinner937ee9e2018-06-26 02:11:06 +02001515 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001516 def test_file_not_found_includes_filename(self):
1517 with self.assertRaises(FileNotFoundError) as c:
1518 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1519 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1520
Victor Stinner937ee9e2018-06-26 02:11:06 +02001521 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001522 def test_file_not_found_with_bad_cwd(self):
1523 with self.assertRaises(FileNotFoundError) as c:
1524 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1525 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1526
Batuhan Taşkaya4dc5a9d2019-12-30 19:02:04 +03001527 def test_class_getitems(self):
Guido van Rossum48b069a2020-04-07 09:50:06 -07001528 self.assertIsInstance(subprocess.Popen[bytes], types.GenericAlias)
1529 self.assertIsInstance(subprocess.CompletedProcess[str], types.GenericAlias)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001530
1531class RunFuncTestCase(BaseTestCase):
1532 def run_python(self, code, **kwargs):
1533 """Run Python code in a subprocess using subprocess.run"""
1534 argv = [sys.executable, "-c", code]
1535 return subprocess.run(argv, **kwargs)
1536
1537 def test_returncode(self):
1538 # call() function with sequence argument
1539 cp = self.run_python("import sys; sys.exit(47)")
1540 self.assertEqual(cp.returncode, 47)
1541 with self.assertRaises(subprocess.CalledProcessError):
1542 cp.check_returncode()
1543
1544 def test_check(self):
1545 with self.assertRaises(subprocess.CalledProcessError) as c:
1546 self.run_python("import sys; sys.exit(47)", check=True)
1547 self.assertEqual(c.exception.returncode, 47)
1548
1549 def test_check_zero(self):
1550 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001551 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001552 self.assertEqual(cp.returncode, 0)
1553
1554 def test_timeout(self):
1555 # run() function with timeout argument; we want to test that the child
1556 # process gets killed when the timeout expires. If the child isn't
1557 # killed, this call will deadlock since subprocess.run waits for the
1558 # child.
1559 with self.assertRaises(subprocess.TimeoutExpired):
1560 self.run_python("while True: pass", timeout=0.0001)
1561
1562 def test_capture_stdout(self):
1563 # capture stdout with zero return code
1564 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1565 self.assertIn(b'BDFL', cp.stdout)
1566
1567 def test_capture_stderr(self):
1568 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1569 stderr=subprocess.PIPE)
1570 self.assertIn(b'BDFL', cp.stderr)
1571
1572 def test_check_output_stdin_arg(self):
1573 # run() can be called with stdin set to a file
1574 tf = tempfile.TemporaryFile()
1575 self.addCleanup(tf.close)
1576 tf.write(b'pear')
1577 tf.seek(0)
1578 cp = self.run_python(
1579 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1580 stdin=tf, stdout=subprocess.PIPE)
1581 self.assertIn(b'PEAR', cp.stdout)
1582
1583 def test_check_output_input_arg(self):
1584 # check_output() can be called with input set to a string
1585 cp = self.run_python(
1586 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1587 input=b'pear', stdout=subprocess.PIPE)
1588 self.assertIn(b'PEAR', cp.stdout)
1589
1590 def test_check_output_stdin_with_input_arg(self):
1591 # run() refuses to accept 'stdin' with 'input'
1592 tf = tempfile.TemporaryFile()
1593 self.addCleanup(tf.close)
1594 tf.write(b'pear')
1595 tf.seek(0)
1596 with self.assertRaises(ValueError,
1597 msg="Expected ValueError when stdin and input args supplied.") as c:
1598 output = self.run_python("print('will not be run')",
1599 stdin=tf, input=b'hare')
1600 self.assertIn('stdin', c.exception.args[0])
1601 self.assertIn('input', c.exception.args[0])
1602
1603 def test_check_output_timeout(self):
1604 with self.assertRaises(subprocess.TimeoutExpired) as c:
1605 cp = self.run_python((
1606 "import sys, time\n"
1607 "sys.stdout.write('BDFL')\n"
1608 "sys.stdout.flush()\n"
1609 "time.sleep(3600)"),
1610 # Some heavily loaded buildbots (sparc Debian 3.x) require
1611 # this much time to start and print.
1612 timeout=3, stdout=subprocess.PIPE)
1613 self.assertEqual(c.exception.output, b'BDFL')
1614 # output is aliased to stdout
1615 self.assertEqual(c.exception.stdout, b'BDFL')
1616
1617 def test_run_kwargs(self):
1618 newenv = os.environ.copy()
1619 newenv["FRUIT"] = "banana"
1620 cp = self.run_python(('import sys, os;'
1621 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1622 env=newenv)
1623 self.assertEqual(cp.returncode, 33)
1624
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001625 def test_run_with_pathlike_path(self):
1626 # bpo-31961: test run(pathlike_object)
1627 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001628 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001629 prog = 'tree.com' if mswindows else 'ls'
1630 path = shutil.which(prog)
1631 if path is None:
1632 self.skipTest(f'{prog} required for this test')
1633 path = FakePath(path)
1634 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1635 self.assertEqual(res.returncode, 0)
1636 with self.assertRaises(TypeError):
1637 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1638
1639 def test_run_with_bytes_path_and_arguments(self):
1640 # bpo-31961: test run([bytes_object, b'additional arguments'])
1641 path = os.fsencode(sys.executable)
1642 args = [path, '-c', b'import sys; sys.exit(57)']
1643 res = subprocess.run(args)
1644 self.assertEqual(res.returncode, 57)
1645
1646 def test_run_with_pathlike_path_and_arguments(self):
1647 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1648 path = FakePath(sys.executable)
1649 args = [path, '-c', 'import sys; sys.exit(57)']
1650 res = subprocess.run(args)
1651 self.assertEqual(res.returncode, 57)
1652
Bo Baylesce0f33d2018-01-30 00:40:39 -06001653 def test_capture_output(self):
1654 cp = self.run_python(("import sys;"
1655 "sys.stdout.write('BDFL'); "
1656 "sys.stderr.write('FLUFL')"),
1657 capture_output=True)
1658 self.assertIn(b'BDFL', cp.stdout)
1659 self.assertIn(b'FLUFL', cp.stderr)
1660
1661 def test_stdout_with_capture_output_arg(self):
1662 # run() refuses to accept 'stdout' with 'capture_output'
1663 tf = tempfile.TemporaryFile()
1664 self.addCleanup(tf.close)
1665 with self.assertRaises(ValueError,
1666 msg=("Expected ValueError when stdout and capture_output "
1667 "args supplied.")) as c:
1668 output = self.run_python("print('will not be run')",
1669 capture_output=True, stdout=tf)
1670 self.assertIn('stdout', c.exception.args[0])
1671 self.assertIn('capture_output', c.exception.args[0])
1672
1673 def test_stderr_with_capture_output_arg(self):
1674 # run() refuses to accept 'stderr' with 'capture_output'
1675 tf = tempfile.TemporaryFile()
1676 self.addCleanup(tf.close)
1677 with self.assertRaises(ValueError,
1678 msg=("Expected ValueError when stderr and capture_output "
1679 "args supplied.")) as c:
1680 output = self.run_python("print('will not be run')",
1681 capture_output=True, stderr=tf)
1682 self.assertIn('stderr', c.exception.args[0])
1683 self.assertIn('capture_output', c.exception.args[0])
1684
Gregory P. Smith580d2782019-09-11 04:23:05 -05001685 # This test _might_ wind up a bit fragile on loaded build+test machines
1686 # as it depends on the timing with wide enough margins for normal situations
1687 # but does assert that it happened "soon enough" to believe the right thing
1688 # happened.
1689 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1690 def test_run_with_shell_timeout_and_capture_output(self):
1691 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1692 before_secs = time.monotonic()
1693 try:
1694 subprocess.run('sleep 3', shell=True, timeout=0.1,
1695 capture_output=True) # New session unspecified.
1696 except subprocess.TimeoutExpired as exc:
1697 after_secs = time.monotonic()
1698 stacks = traceback.format_exc() # assertRaises doesn't give this.
1699 else:
1700 self.fail("TimeoutExpired not raised.")
1701 self.assertLess(after_secs - before_secs, 1.5,
1702 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1703 f"{stacks}```")
1704
Gregory P. Smith6e730002015-04-14 16:14:25 -07001705
Gregory P. Smith693aa802019-09-13 14:43:35 +01001706def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001707 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001708 if grp:
1709 try:
1710 grp.getgrnam(name_group)
1711 except KeyError:
1712 continue
1713 return name_group
1714 else:
1715 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1716
1717
Victor Stinner937ee9e2018-06-26 02:11:06 +02001718@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001719class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001720
Gregory P. Smith5591b022012-10-10 03:34:47 -07001721 def setUp(self):
1722 super().setUp()
1723 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1724
1725 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001726 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001727 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001728 except OSError as e:
1729 # This avoids hard coding the errno value or the OS perror()
1730 # string and instead capture the exception that we want to see
1731 # below for comparison.
1732 desired_exception = e
1733 else:
Martin Pantereb995702016-07-28 01:11:04 +00001734 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001735 self._nonexistent_dir)
1736 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001737
Gregory P. Smith5591b022012-10-10 03:34:47 -07001738 def test_exception_cwd(self):
1739 """Test error in the child raised in the parent for a bad cwd."""
1740 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001741 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001742 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001743 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001744 except OSError as e:
1745 # Test that the child process chdir failure actually makes
1746 # it up to the parent process as the correct exception.
1747 self.assertEqual(desired_exception.errno, e.errno)
1748 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001749 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001750 else:
1751 self.fail("Expected OSError: %s" % desired_exception)
1752
Gregory P. Smith5591b022012-10-10 03:34:47 -07001753 def test_exception_bad_executable(self):
1754 """Test error in the child raised in the parent for a bad executable."""
1755 desired_exception = self._get_chdir_exception()
1756 try:
1757 p = subprocess.Popen([sys.executable, "-c", ""],
1758 executable=self._nonexistent_dir)
1759 except OSError as e:
1760 # Test that the child process exec failure actually makes
1761 # it up to the parent process as the correct exception.
1762 self.assertEqual(desired_exception.errno, e.errno)
1763 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001764 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001765 else:
1766 self.fail("Expected OSError: %s" % desired_exception)
1767
1768 def test_exception_bad_args_0(self):
1769 """Test error in the child raised in the parent for a bad args[0]."""
1770 desired_exception = self._get_chdir_exception()
1771 try:
1772 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1773 except OSError as e:
1774 # Test that the child process exec failure actually makes
1775 # it up to the parent process as the correct exception.
1776 self.assertEqual(desired_exception.errno, e.errno)
1777 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001778 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001779 else:
1780 self.fail("Expected OSError: %s" % desired_exception)
1781
Ammar Askar3fc499b2017-09-06 02:41:30 -04001782 # We mock the __del__ method for Popen in the next two tests
1783 # because it does cleanup based on the pid returned by fork_exec
1784 # along with issuing a resource warning if it still exists. Since
1785 # we don't actually spawn a process in these tests we can forego
1786 # the destructor. An alternative would be to set _child_created to
1787 # False before the destructor is called but there is no easy way
1788 # to do that
1789 class PopenNoDestructor(subprocess.Popen):
1790 def __del__(self):
1791 pass
1792
1793 @mock.patch("subprocess._posixsubprocess.fork_exec")
1794 def test_exception_errpipe_normal(self, fork_exec):
1795 """Test error passing done through errpipe_write in the good case"""
1796 def proper_error(*args):
1797 errpipe_write = args[13]
1798 # Write the hex for the error code EISDIR: 'is a directory'
1799 err_code = '{:x}'.format(errno.EISDIR).encode()
1800 os.write(errpipe_write, b"OSError:" + err_code + b":")
1801 return 0
1802
1803 fork_exec.side_effect = proper_error
1804
Victor Stinner11045c92017-10-05 06:32:53 -07001805 with mock.patch("subprocess.os.waitpid",
1806 side_effect=ChildProcessError):
1807 with self.assertRaises(IsADirectoryError):
1808 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001809
1810 @mock.patch("subprocess._posixsubprocess.fork_exec")
1811 def test_exception_errpipe_bad_data(self, fork_exec):
1812 """Test error passing done through errpipe_write where its not
1813 in the expected format"""
1814 error_data = b"\xFF\x00\xDE\xAD"
1815 def bad_error(*args):
1816 errpipe_write = args[13]
1817 # Anything can be in the pipe, no assumptions should
1818 # be made about its encoding, so we'll write some
1819 # arbitrary hex bytes to test it out
1820 os.write(errpipe_write, error_data)
1821 return 0
1822
1823 fork_exec.side_effect = bad_error
1824
Victor Stinner11045c92017-10-05 06:32:53 -07001825 with mock.patch("subprocess.os.waitpid",
1826 side_effect=ChildProcessError):
1827 with self.assertRaises(subprocess.SubprocessError) as e:
1828 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001829
1830 self.assertIn(repr(error_data), str(e.exception))
1831
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001832 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1833 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001834 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001835 # Blindly assume that cat exists on systems with /proc/self/status...
1836 default_proc_status = subprocess.check_output(
1837 ['cat', '/proc/self/status'],
1838 restore_signals=False)
1839 for line in default_proc_status.splitlines():
1840 if line.startswith(b'SigIgn'):
1841 default_sig_ign_mask = line
1842 break
1843 else:
1844 self.skipTest("SigIgn not found in /proc/self/status.")
1845 restored_proc_status = subprocess.check_output(
1846 ['cat', '/proc/self/status'],
1847 restore_signals=True)
1848 for line in restored_proc_status.splitlines():
1849 if line.startswith(b'SigIgn'):
1850 restored_sig_ign_mask = line
1851 break
1852 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1853 msg="restore_signals=True should've unblocked "
1854 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001855
1856 def test_start_new_session(self):
1857 # For code coverage of calling setsid(). We don't care if we get an
1858 # EPERM error from it depending on the test execution environment, that
1859 # still indicates that it was called.
1860 try:
1861 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001862 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001863 start_new_session=True)
1864 except OSError as e:
1865 if e.errno != errno.EPERM:
1866 raise
1867 else:
Victor Stinner58840432019-06-14 19:31:43 +02001868 parent_sid = os.getsid(0)
1869 child_sid = int(output)
1870 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001871
Patrick McLean2b2ead72019-09-12 10:15:44 -07001872 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1873 def test_user(self):
1874 # For code coverage of the user parameter. We don't care if we get an
1875 # EPERM error from it depending on the test execution environment, that
1876 # still indicates that it was called.
1877
1878 uid = os.geteuid()
1879 test_users = [65534 if uid != 65534 else 65533, uid]
1880 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1881
1882 if pwd is not None:
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001883 try:
1884 pwd.getpwnam(name_uid)
1885 test_users.append(name_uid)
1886 except KeyError:
1887 # unknown user name
1888 name_uid = None
Patrick McLean2b2ead72019-09-12 10:15:44 -07001889
1890 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001891 # posix_spawn() may be used with close_fds=False
1892 for close_fds in (False, True):
1893 with self.subTest(user=user, close_fds=close_fds):
1894 try:
1895 output = subprocess.check_output(
1896 [sys.executable, "-c",
1897 "import os; print(os.getuid())"],
1898 user=user,
1899 close_fds=close_fds)
1900 except PermissionError: # (EACCES, EPERM)
1901 pass
1902 except OSError as e:
1903 if e.errno not in (errno.EACCES, errno.EPERM):
1904 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001905 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001906 if isinstance(user, str):
1907 user_uid = pwd.getpwnam(user).pw_uid
1908 else:
1909 user_uid = user
1910 child_user = int(output)
1911 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001912
1913 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001914 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001915
Alexey Izbyshevc0590c02020-10-26 03:09:32 +03001916 with self.assertRaises(OverflowError):
1917 subprocess.check_call(ZERO_RETURN_CMD,
1918 cwd=os.curdir, env=os.environ, user=2**64)
1919
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001920 if pwd is None and name_uid is not None:
Patrick McLean2b2ead72019-09-12 10:15:44 -07001921 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001922 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001923
1924 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1925 def test_user_error(self):
1926 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001927 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001928
1929 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1930 def test_group(self):
1931 gid = os.getegid()
1932 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001933 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001934
1935 if grp is not None:
1936 group_list.append(name_group)
1937
1938 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001939 # posix_spawn() may be used with close_fds=False
1940 for close_fds in (False, True):
1941 with self.subTest(group=group, close_fds=close_fds):
1942 try:
1943 output = subprocess.check_output(
1944 [sys.executable, "-c",
1945 "import os; print(os.getgid())"],
1946 group=group,
1947 close_fds=close_fds)
1948 except PermissionError: # (EACCES, EPERM)
1949 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001950 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001951 if isinstance(group, str):
1952 group_gid = grp.getgrnam(group).gr_gid
1953 else:
1954 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001955
Victor Stinnerfaca8552019-09-25 15:52:49 +02001956 child_group = int(output)
1957 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001958
1959 # make sure we bomb on negative values
1960 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001961 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001962
Alexey Izbyshevc0590c02020-10-26 03:09:32 +03001963 with self.assertRaises(OverflowError):
1964 subprocess.check_call(ZERO_RETURN_CMD,
1965 cwd=os.curdir, env=os.environ, group=2**64)
1966
Patrick McLean2b2ead72019-09-12 10:15:44 -07001967 if grp is None:
1968 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001969 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001970
1971 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1972 def test_group_error(self):
1973 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001974 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001975
1976 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1977 def test_extra_groups(self):
1978 gid = os.getegid()
1979 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001980 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001981 perm_error = False
1982
1983 if grp is not None:
1984 group_list.append(name_group)
1985
1986 try:
1987 output = subprocess.check_output(
1988 [sys.executable, "-c",
1989 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1990 extra_groups=group_list)
1991 except OSError as ex:
1992 if ex.errno != errno.EPERM:
1993 raise
1994 perm_error = True
1995
1996 else:
1997 parent_groups = os.getgroups()
1998 child_groups = json.loads(output)
1999
2000 if grp is not None:
2001 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
2002 for g in group_list]
2003 else:
2004 desired_gids = group_list
2005
2006 if perm_error:
2007 self.assertEqual(set(child_groups), set(parent_groups))
2008 else:
2009 self.assertEqual(set(desired_gids), set(child_groups))
2010
2011 # make sure we bomb on negative values
2012 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002013 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07002014
Alexey Izbyshevc0590c02020-10-26 03:09:32 +03002015 with self.assertRaises(ValueError):
2016 subprocess.check_call(ZERO_RETURN_CMD,
2017 cwd=os.curdir, env=os.environ,
2018 extra_groups=[2**64])
2019
Patrick McLean2b2ead72019-09-12 10:15:44 -07002020 if grp is None:
2021 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002022 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07002023 extra_groups=[name_group])
2024
2025 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
2026 def test_extra_groups_error(self):
2027 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002028 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07002029
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07002030 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
2031 'POSIX umask() is not available.')
2032 def test_umask(self):
2033 tmpdir = None
2034 try:
2035 tmpdir = tempfile.mkdtemp()
2036 name = os.path.join(tmpdir, "beans")
2037 # We set an unusual umask in the child so as a unique mode
2038 # for us to test the child's touched file for.
2039 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002040 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07002041 umask=0o053)
2042 # Ignore execute permissions entirely in our test,
2043 # filesystems could be mounted to ignore or force that.
2044 st_mode = os.stat(name).st_mode & 0o666
2045 expected_mode = 0o624
2046 self.assertEqual(expected_mode, st_mode,
2047 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
2048 finally:
2049 if tmpdir is not None:
2050 shutil.rmtree(tmpdir)
2051
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002052 def test_run_abort(self):
2053 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02002054 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002055 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002056 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002057 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002058 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002059
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00002060 def test_CalledProcessError_str_signal(self):
2061 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
2062 error_string = str(err)
2063 # We're relying on the repr() of the signal.Signals intenum to provide
2064 # the word signal, the signal name and the numeric value.
2065 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00002066 # We're not being specific about the signal name as some signals have
2067 # multiple names and which name is revealed can vary.
2068 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00002069 self.assertIn(str(signal.SIGABRT), error_string)
2070
2071 def test_CalledProcessError_str_unknown_signal(self):
2072 err = subprocess.CalledProcessError(-9876543, "fake cmd")
2073 error_string = str(err)
2074 self.assertIn("unknown signal 9876543.", error_string)
2075
2076 def test_CalledProcessError_str_non_zero(self):
2077 err = subprocess.CalledProcessError(2, "fake cmd")
2078 error_string = str(err)
2079 self.assertIn("non-zero exit status 2.", error_string)
2080
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002081 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002082 # DISCLAIMER: Setting environment variables is *not* a good use
2083 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002084 p = subprocess.Popen([sys.executable, "-c",
2085 'import sys,os;'
2086 'sys.stdout.write(os.getenv("FRUIT"))'],
2087 stdout=subprocess.PIPE,
2088 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02002089 with p:
2090 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002091
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002092 def test_preexec_exception(self):
2093 def raise_it():
2094 raise ValueError("What if two swallows carried a coconut?")
2095 try:
2096 p = subprocess.Popen([sys.executable, "-c", ""],
2097 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002098 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002099 self.assertTrue(
2100 subprocess._posixsubprocess,
2101 "Expected a ValueError from the preexec_fn")
2102 except ValueError as e:
2103 self.assertIn("coconut", e.args[0])
2104 else:
2105 self.fail("Exception raised by preexec_fn did not make it "
2106 "to the parent process.")
2107
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002108 class _TestExecuteChildPopen(subprocess.Popen):
2109 """Used to test behavior at the end of _execute_child."""
2110 def __init__(self, testcase, *args, **kwargs):
2111 self._testcase = testcase
2112 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002113
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002114 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08002115 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002116 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002117 finally:
2118 # Open a bunch of file descriptors and verify that
2119 # none of them are the same as the ones the Popen
2120 # instance is using for stdin/stdout/stderr.
2121 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2122 for _ in range(8)]
2123 try:
2124 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002125 self._testcase.assertNotIn(
2126 fd, (self.stdin.fileno(), self.stdout.fileno(),
2127 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002128 msg="At least one fd was closed early.")
2129 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002130 for fd in devzero_fds:
2131 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002132
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002133 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2134 def test_preexec_errpipe_does_not_double_close_pipes(self):
2135 """Issue16140: Don't double close pipes on preexec error."""
2136
2137 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002138 raise subprocess.SubprocessError(
2139 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002140
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002141 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002142 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002143 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002144 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2145 stderr=subprocess.PIPE, preexec_fn=raise_it)
2146
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002147 def test_preexec_gc_module_failure(self):
2148 # This tests the code that disables garbage collection if the child
2149 # process will execute any Python.
2150 def raise_runtime_error():
2151 raise RuntimeError("this shouldn't escape")
2152 enabled = gc.isenabled()
2153 orig_gc_disable = gc.disable
2154 orig_gc_isenabled = gc.isenabled
2155 try:
2156 gc.disable()
2157 self.assertFalse(gc.isenabled())
2158 subprocess.call([sys.executable, '-c', ''],
2159 preexec_fn=lambda: None)
2160 self.assertFalse(gc.isenabled(),
2161 "Popen enabled gc when it shouldn't.")
2162
2163 gc.enable()
2164 self.assertTrue(gc.isenabled())
2165 subprocess.call([sys.executable, '-c', ''],
2166 preexec_fn=lambda: None)
2167 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2168
2169 gc.disable = raise_runtime_error
2170 self.assertRaises(RuntimeError, subprocess.Popen,
2171 [sys.executable, '-c', ''],
2172 preexec_fn=lambda: None)
2173
2174 del gc.isenabled # force an AttributeError
2175 self.assertRaises(AttributeError, subprocess.Popen,
2176 [sys.executable, '-c', ''],
2177 preexec_fn=lambda: None)
2178 finally:
2179 gc.disable = orig_gc_disable
2180 gc.isenabled = orig_gc_isenabled
2181 if not enabled:
2182 gc.disable()
2183
Martin Panterf7fdbda2015-12-05 09:51:52 +00002184 @unittest.skipIf(
2185 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002186 def test_preexec_fork_failure(self):
2187 # The internal code did not preserve the previous exception when
2188 # re-enabling garbage collection
2189 try:
2190 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2191 except ImportError as err:
2192 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2193 limits = getrlimit(RLIMIT_NPROC)
2194 [_, hard] = limits
2195 setrlimit(RLIMIT_NPROC, (0, hard))
2196 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002197 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002198 subprocess.call([sys.executable, '-c', ''],
2199 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002200 except BlockingIOError:
2201 # Forking should raise EAGAIN, translated to BlockingIOError
2202 pass
2203 else:
2204 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002205
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002206 def test_args_string(self):
2207 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002208 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002209 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002210 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002211 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002212 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2213 sys.executable)
2214 os.chmod(fname, 0o700)
2215 p = subprocess.Popen(fname)
2216 p.wait()
2217 os.remove(fname)
2218 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002219
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002220 def test_invalid_args(self):
2221 # invalid arguments should raise ValueError
2222 self.assertRaises(ValueError, subprocess.call,
2223 [sys.executable, "-c",
2224 "import sys; sys.exit(47)"],
2225 startupinfo=47)
2226 self.assertRaises(ValueError, subprocess.call,
2227 [sys.executable, "-c",
2228 "import sys; sys.exit(47)"],
2229 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002230
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002231 def test_shell_sequence(self):
2232 # Run command through the shell (sequence)
2233 newenv = os.environ.copy()
2234 newenv["FRUIT"] = "apple"
2235 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2236 stdout=subprocess.PIPE,
2237 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002238 with p:
2239 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002240
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002241 def test_shell_string(self):
2242 # Run command through the shell (string)
2243 newenv = os.environ.copy()
2244 newenv["FRUIT"] = "apple"
2245 p = subprocess.Popen("echo $FRUIT", shell=1,
2246 stdout=subprocess.PIPE,
2247 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002248 with p:
2249 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002250
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002251 def test_call_string(self):
2252 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002253 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002254 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002255 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002256 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002257 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2258 sys.executable)
2259 os.chmod(fname, 0o700)
2260 rc = subprocess.call(fname)
2261 os.remove(fname)
2262 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002263
Stefan Krah9542cc62010-07-19 14:20:53 +00002264 def test_specific_shell(self):
2265 # Issue #9265: Incorrect name passed as arg[0].
2266 shells = []
2267 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2268 for name in ['bash', 'ksh']:
2269 sh = os.path.join(prefix, name)
2270 if os.path.isfile(sh):
2271 shells.append(sh)
2272 if not shells: # Will probably work for any shell but csh.
2273 self.skipTest("bash or ksh required for this test")
2274 sh = '/bin/sh'
2275 if os.path.isfile(sh) and not os.path.islink(sh):
2276 # Test will fail if /bin/sh is a symlink to csh.
2277 shells.append(sh)
2278 for sh in shells:
2279 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2280 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002281 with p:
2282 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002283
Florent Xicluna4886d242010-03-08 13:27:26 +00002284 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002285 # Do not inherit file handles from the parent.
2286 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002287 # Also set the SIGINT handler to the default to make sure it's not
2288 # being ignored (some tests rely on that.)
2289 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2290 try:
2291 p = subprocess.Popen([sys.executable, "-c", """if 1:
2292 import sys, time
2293 sys.stdout.write('x\\n')
2294 sys.stdout.flush()
2295 time.sleep(30)
2296 """],
2297 close_fds=True,
2298 stdin=subprocess.PIPE,
2299 stdout=subprocess.PIPE,
2300 stderr=subprocess.PIPE)
2301 finally:
2302 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002303 # Wait for the interpreter to be completely initialized before
2304 # sending any signal.
2305 p.stdout.read(1)
2306 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002307 return p
2308
Charles-François Natali53221e32013-01-12 16:52:20 +01002309 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2310 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002311 def _kill_dead_process(self, method, *args):
2312 # Do not inherit file handles from the parent.
2313 # It should fix failures on some platforms.
2314 p = subprocess.Popen([sys.executable, "-c", """if 1:
2315 import sys, time
2316 sys.stdout.write('x\\n')
2317 sys.stdout.flush()
2318 """],
2319 close_fds=True,
2320 stdin=subprocess.PIPE,
2321 stdout=subprocess.PIPE,
2322 stderr=subprocess.PIPE)
2323 # Wait for the interpreter to be completely initialized before
2324 # sending any signal.
2325 p.stdout.read(1)
2326 # The process should end after this
2327 time.sleep(1)
2328 # This shouldn't raise even though the child is now dead
2329 getattr(p, method)(*args)
2330 p.communicate()
2331
Florent Xicluna4886d242010-03-08 13:27:26 +00002332 def test_send_signal(self):
2333 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002334 _, stderr = p.communicate()
2335 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002336 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002337
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002338 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002339 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002340 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002341 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002342 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002343
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002344 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002345 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002346 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002347 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002348 self.assertEqual(p.wait(), -signal.SIGTERM)
2349
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002350 def test_send_signal_dead(self):
2351 # Sending a signal to a dead process
2352 self._kill_dead_process('send_signal', signal.SIGINT)
2353
2354 def test_kill_dead(self):
2355 # Killing a dead process
2356 self._kill_dead_process('kill')
2357
2358 def test_terminate_dead(self):
2359 # Terminating a dead process
2360 self._kill_dead_process('terminate')
2361
Victor Stinnerdaf45552013-08-28 00:53:59 +02002362 def _save_fds(self, save_fds):
2363 fds = []
2364 for fd in save_fds:
2365 inheritable = os.get_inheritable(fd)
2366 saved = os.dup(fd)
2367 fds.append((fd, saved, inheritable))
2368 return fds
2369
2370 def _restore_fds(self, fds):
2371 for fd, saved, inheritable in fds:
2372 os.dup2(saved, fd, inheritable=inheritable)
2373 os.close(saved)
2374
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002375 def check_close_std_fds(self, fds):
2376 # Issue #9905: test that subprocess pipes still work properly with
2377 # some standard fds closed
2378 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002379 saved_fds = self._save_fds(fds)
2380 for fd, saved, inheritable in saved_fds:
2381 if fd == 0:
2382 stdin = saved
2383 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002384 try:
2385 for fd in fds:
2386 os.close(fd)
2387 out, err = subprocess.Popen([sys.executable, "-c",
2388 'import sys;'
2389 'sys.stdout.write("apple");'
2390 'sys.stdout.flush();'
2391 'sys.stderr.write("orange")'],
2392 stdin=stdin,
2393 stdout=subprocess.PIPE,
2394 stderr=subprocess.PIPE).communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002395 self.assertEqual(out, b'apple')
2396 self.assertEqual(err, b'orange')
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002397 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002398 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002399
2400 def test_close_fd_0(self):
2401 self.check_close_std_fds([0])
2402
2403 def test_close_fd_1(self):
2404 self.check_close_std_fds([1])
2405
2406 def test_close_fd_2(self):
2407 self.check_close_std_fds([2])
2408
2409 def test_close_fds_0_1(self):
2410 self.check_close_std_fds([0, 1])
2411
2412 def test_close_fds_0_2(self):
2413 self.check_close_std_fds([0, 2])
2414
2415 def test_close_fds_1_2(self):
2416 self.check_close_std_fds([1, 2])
2417
2418 def test_close_fds_0_1_2(self):
2419 # Issue #10806: test that subprocess pipes still work properly with
2420 # all standard fds closed.
2421 self.check_close_std_fds([0, 1, 2])
2422
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002423 def test_small_errpipe_write_fd(self):
2424 """Issue #15798: Popen should work when stdio fds are available."""
2425 new_stdin = os.dup(0)
2426 new_stdout = os.dup(1)
2427 try:
2428 os.close(0)
2429 os.close(1)
2430
2431 # Side test: if errpipe_write fails to have its CLOEXEC
2432 # flag set this should cause the parent to think the exec
2433 # failed. Extremely unlikely: everyone supports CLOEXEC.
2434 subprocess.Popen([
2435 sys.executable, "-c",
2436 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2437 finally:
2438 # Restore original stdin and stdout
2439 os.dup2(new_stdin, 0)
2440 os.dup2(new_stdout, 1)
2441 os.close(new_stdin)
2442 os.close(new_stdout)
2443
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002444 def test_remapping_std_fds(self):
2445 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002446 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002447 try:
2448 temp_fds = [fd for fd, fname in temps]
2449
2450 # unlink the files -- we won't need to reopen them
2451 for fd, fname in temps:
2452 os.unlink(fname)
2453
2454 # write some data to what will become stdin, and rewind
2455 os.write(temp_fds[1], b"STDIN")
2456 os.lseek(temp_fds[1], 0, 0)
2457
2458 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002459 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002460 try:
2461 # duplicate the file objects over the standard fd's
2462 for fd, temp_fd in enumerate(temp_fds):
2463 os.dup2(temp_fd, fd)
2464
2465 # now use those files in the "wrong" order, so that subprocess
2466 # has to rearrange them in the child
2467 p = subprocess.Popen([sys.executable, "-c",
2468 'import sys; got = sys.stdin.read();'
2469 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2470 stdin=temp_fds[1],
2471 stdout=temp_fds[2],
2472 stderr=temp_fds[0])
2473 p.wait()
2474 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002475 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002476
2477 for fd in temp_fds:
2478 os.lseek(fd, 0, 0)
2479
2480 out = os.read(temp_fds[2], 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002481 err = os.read(temp_fds[0], 1024).strip()
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002482 self.assertEqual(out, b"got STDIN")
2483 self.assertEqual(err, b"err")
2484
2485 finally:
2486 for fd in temp_fds:
2487 os.close(fd)
2488
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002489 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2490 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002491 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002492 temp_fds = [fd for fd, fname in temps]
2493 try:
2494 # unlink the files -- we won't need to reopen them
2495 for fd, fname in temps:
2496 os.unlink(fname)
2497
2498 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002499 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002500 try:
2501 # duplicate the temp files over the standard fd's 0, 1, 2
2502 for fd, temp_fd in enumerate(temp_fds):
2503 os.dup2(temp_fd, fd)
2504
2505 # write some data to what will become stdin, and rewind
2506 os.write(stdin_no, b"STDIN")
2507 os.lseek(stdin_no, 0, 0)
2508
2509 # now use those files in the given order, so that subprocess
2510 # has to rearrange them in the child
2511 p = subprocess.Popen([sys.executable, "-c",
2512 'import sys; got = sys.stdin.read();'
2513 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2514 stdin=stdin_no,
2515 stdout=stdout_no,
2516 stderr=stderr_no)
2517 p.wait()
2518
2519 for fd in temp_fds:
2520 os.lseek(fd, 0, 0)
2521
2522 out = os.read(stdout_no, 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002523 err = os.read(stderr_no, 1024).strip()
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002524 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002525 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002526
2527 self.assertEqual(out, b"got STDIN")
2528 self.assertEqual(err, b"err")
2529
2530 finally:
2531 for fd in temp_fds:
2532 os.close(fd)
2533
2534 # When duping fds, if there arises a situation where one of the fds is
2535 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2536 # This tests all combinations of this.
2537 def test_swap_fds(self):
2538 self.check_swap_fds(0, 1, 2)
2539 self.check_swap_fds(0, 2, 1)
2540 self.check_swap_fds(1, 0, 2)
2541 self.check_swap_fds(1, 2, 0)
2542 self.check_swap_fds(2, 0, 1)
2543 self.check_swap_fds(2, 1, 0)
2544
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002545 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2546 saved_fds = self._save_fds(range(3))
2547 try:
2548 for from_fd in from_fds:
2549 with tempfile.TemporaryFile() as f:
2550 os.dup2(f.fileno(), from_fd)
2551
2552 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2553 os.close(fd_to_close)
2554
2555 arg_names = ['stdin', 'stdout', 'stderr']
2556 kwargs = {}
2557 for from_fd, to_fd in zip(from_fds, to_fds):
2558 kwargs[arg_names[to_fd]] = from_fd
2559
2560 code = textwrap.dedent(r'''
2561 import os, sys
2562 skipped_fd = int(sys.argv[1])
2563 for fd in range(3):
2564 if fd != skipped_fd:
2565 os.write(fd, str(fd).encode('ascii'))
2566 ''')
2567
2568 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2569
2570 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2571 **kwargs)
2572 self.assertEqual(rc, 0)
2573
2574 for from_fd, to_fd in zip(from_fds, to_fds):
2575 os.lseek(from_fd, 0, os.SEEK_SET)
2576 read_bytes = os.read(from_fd, 1024)
2577 read_fds = list(map(int, read_bytes.decode('ascii')))
2578 msg = textwrap.dedent(f"""
2579 When testing {from_fds} to {to_fds} redirection,
2580 parent descriptor {from_fd} got redirected
2581 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2582 """)
2583 self.assertEqual([to_fd], read_fds, msg)
2584 finally:
2585 self._restore_fds(saved_fds)
2586
2587 # Check that subprocess can remap std fds correctly even
2588 # if one of them is closed (#32844).
2589 def test_swap_std_fds_with_one_closed(self):
2590 for from_fds in itertools.combinations(range(3), 2):
2591 for to_fds in itertools.permutations(range(3), 2):
2592 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2593
Victor Stinner13bb71c2010-04-23 21:41:56 +00002594 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002595 def prepare():
2596 raise ValueError("surrogate:\uDCff")
2597
2598 try:
2599 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002600 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002601 preexec_fn=prepare)
2602 except ValueError as err:
2603 # Pure Python implementations keeps the message
2604 self.assertIsNone(subprocess._posixsubprocess)
2605 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002606 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002607 # _posixsubprocess uses a default message
2608 self.assertIsNotNone(subprocess._posixsubprocess)
2609 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2610 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002611 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002612
Victor Stinner13bb71c2010-04-23 21:41:56 +00002613 def test_undecodable_env(self):
2614 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002615 encoded_value = value.encode("ascii", "surrogateescape")
2616
Victor Stinner13bb71c2010-04-23 21:41:56 +00002617 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002618 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002619 env = os.environ.copy()
2620 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002621 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002622 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002623 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002624 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002625 stdout = subprocess.check_output(
2626 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002627 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002628 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002629 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002630
2631 # test bytes
2632 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002633 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002634 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002635 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002636 stdout = subprocess.check_output(
2637 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002638 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002639 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002640 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002641
Victor Stinnerb745a742010-05-18 17:17:23 +00002642 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002643 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2644 args = list(ZERO_RETURN_CMD[1:])
2645 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002646 program = os.fsencode(program)
2647
2648 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002649 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002650 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002651
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002652 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002653 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002654 exitcode = subprocess.call(cmd, shell=True)
2655 self.assertEqual(exitcode, 0)
2656
Victor Stinnerb745a742010-05-18 17:17:23 +00002657 # bytes program, unicode PATH
2658 env = os.environ.copy()
2659 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002660 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002661 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002662
2663 # bytes program, bytes PATH
2664 envb = os.environb.copy()
2665 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002666 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002667 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002668
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002669 def test_pipe_cloexec(self):
2670 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2671 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2672
2673 p1 = subprocess.Popen([sys.executable, sleeper],
2674 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2675 stderr=subprocess.PIPE, close_fds=False)
2676
2677 self.addCleanup(p1.communicate, b'')
2678
2679 p2 = subprocess.Popen([sys.executable, fd_status],
2680 stdout=subprocess.PIPE, close_fds=False)
2681
2682 output, error = p2.communicate()
2683 result_fds = set(map(int, output.split(b',')))
2684 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2685 p1.stderr.fileno()])
2686
2687 self.assertFalse(result_fds & unwanted_fds,
2688 "Expected no fds from %r to be open in child, "
2689 "found %r" %
2690 (unwanted_fds, result_fds & unwanted_fds))
2691
2692 def test_pipe_cloexec_real_tools(self):
2693 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2694 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2695
2696 subdata = b'zxcvbn'
2697 data = subdata * 4 + b'\n'
2698
2699 p1 = subprocess.Popen([sys.executable, qcat],
2700 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2701 close_fds=False)
2702
2703 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2704 stdin=p1.stdout, stdout=subprocess.PIPE,
2705 close_fds=False)
2706
2707 self.addCleanup(p1.wait)
2708 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002709 def kill_p1():
2710 try:
2711 p1.terminate()
2712 except ProcessLookupError:
2713 pass
2714 def kill_p2():
2715 try:
2716 p2.terminate()
2717 except ProcessLookupError:
2718 pass
2719 self.addCleanup(kill_p1)
2720 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002721
2722 p1.stdin.write(data)
2723 p1.stdin.close()
2724
2725 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2726
2727 self.assertTrue(readfiles, "The child hung")
2728 self.assertEqual(p2.stdout.read(), data)
2729
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002730 p1.stdout.close()
2731 p2.stdout.close()
2732
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002733 def test_close_fds(self):
2734 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2735
2736 fds = os.pipe()
2737 self.addCleanup(os.close, fds[0])
2738 self.addCleanup(os.close, fds[1])
2739
2740 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002741 # add a bunch more fds
2742 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002743 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002744 self.addCleanup(os.close, fd)
2745 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002746
Victor Stinnerdaf45552013-08-28 00:53:59 +02002747 for fd in open_fds:
2748 os.set_inheritable(fd, True)
2749
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002750 p = subprocess.Popen([sys.executable, fd_status],
2751 stdout=subprocess.PIPE, close_fds=False)
2752 output, ignored = p.communicate()
2753 remaining_fds = set(map(int, output.split(b',')))
2754
2755 self.assertEqual(remaining_fds & open_fds, open_fds,
2756 "Some fds were closed")
2757
2758 p = subprocess.Popen([sys.executable, fd_status],
2759 stdout=subprocess.PIPE, close_fds=True)
2760 output, ignored = p.communicate()
2761 remaining_fds = set(map(int, output.split(b',')))
2762
2763 self.assertFalse(remaining_fds & open_fds,
2764 "Some fds were left open")
2765 self.assertIn(1, remaining_fds, "Subprocess failed")
2766
Gregory P. Smith8facece2012-01-21 14:01:08 -08002767 # Keep some of the fd's we opened open in the subprocess.
2768 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2769 fds_to_keep = set(open_fds.pop() for _ in range(8))
2770 p = subprocess.Popen([sys.executable, fd_status],
2771 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002772 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002773 output, ignored = p.communicate()
2774 remaining_fds = set(map(int, output.split(b',')))
2775
izbyshev2d8f0632017-12-19 03:26:49 +07002776 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002777 "Some fds not in pass_fds were left open")
2778 self.assertIn(1, remaining_fds, "Subprocess failed")
2779
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002780
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002781 @unittest.skipIf(sys.platform.startswith("freebsd") and
2782 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2783 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002784 def test_close_fds_when_max_fd_is_lowered(self):
2785 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2786 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2787
Gregory P. Smith634aa682014-06-15 17:51:04 -07002788 # This launches the meat of the test in a child process to
2789 # avoid messing with the larger unittest processes maximum
2790 # number of file descriptors.
2791 # This process launches:
2792 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2793 # a bunch of high open fds above the new lower rlimit.
2794 # Those are reported via stdout before launching a new
2795 # process with close_fds=False to run the actual test:
2796 # +--> The TEST: This one launches a fd_status.py
2797 # subprocess with close_fds=True so we can find out if
2798 # any of the fds above the lowered rlimit are still open.
2799 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2800 '''
2801 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002802 open_fds = set()
2803 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002804 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002805 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002806 open_fds.add(fd)
2807
2808 # Leave a two pairs of low ones available for use by the
2809 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002810 # We also leave 10 more open as some Python buildbots run into
2811 # "too many open files" errors during the test if we do not.
2812 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002813 os.close(fd)
2814 open_fds.remove(fd)
2815
2816 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002817 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002818 os.set_inheritable(fd, True)
2819
2820 max_fd_open = max(open_fds)
2821
Gregory P. Smith634aa682014-06-15 17:51:04 -07002822 # Communicate the open_fds to the parent unittest.TestCase process.
2823 print(','.join(map(str, sorted(open_fds))))
2824 sys.stdout.flush()
2825
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002826 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2827 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002828 # 29 is lower than the highest fds we are leaving open.
2829 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002830 # Launch a new Python interpreter with our low fd rlim_cur that
2831 # inherits open fds above that limit. It then uses subprocess
2832 # with close_fds=True to get a report of open fds in the child.
2833 # An explicit list of fds to check is passed to fd_status.py as
2834 # letting fd_status rely on its default logic would miss the
2835 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002836 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002837 [sys.executable, '-c',
2838 textwrap.dedent("""
2839 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002840 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002841 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002842 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002843 """.format(max_fd=max_fd_open+1))],
2844 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002845 finally:
2846 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002847 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002848
2849 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002850 output_lines = output.splitlines()
2851 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002852 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002853 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2854 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002855
Gregory P. Smith634aa682014-06-15 17:51:04 -07002856 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002857 msg="Some fds were left open.")
2858
2859
Victor Stinner88701e22011-06-01 13:13:04 +02002860 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2861 # descriptor of a pipe closed in the parent process is valid in the
2862 # child process according to fstat(), but the mode of the file
2863 # descriptor is invalid, and read or write raise an error.
2864 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002865 def test_pass_fds(self):
2866 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2867
2868 open_fds = set()
2869
2870 for x in range(5):
2871 fds = os.pipe()
2872 self.addCleanup(os.close, fds[0])
2873 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002874 os.set_inheritable(fds[0], True)
2875 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002876 open_fds.update(fds)
2877
2878 for fd in open_fds:
2879 p = subprocess.Popen([sys.executable, fd_status],
2880 stdout=subprocess.PIPE, close_fds=True,
2881 pass_fds=(fd, ))
2882 output, ignored = p.communicate()
2883
2884 remaining_fds = set(map(int, output.split(b',')))
2885 to_be_closed = open_fds - {fd}
2886
2887 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2888 self.assertFalse(remaining_fds & to_be_closed,
2889 "fd to be closed passed")
2890
2891 # pass_fds overrides close_fds with a warning.
2892 with self.assertWarns(RuntimeWarning) as context:
2893 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002894 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002895 close_fds=False, pass_fds=(fd, )))
2896 self.assertIn('overriding close_fds', str(context.warning))
2897
Victor Stinnerdaf45552013-08-28 00:53:59 +02002898 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002899 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002900
2901 inheritable, non_inheritable = os.pipe()
2902 self.addCleanup(os.close, inheritable)
2903 self.addCleanup(os.close, non_inheritable)
2904 os.set_inheritable(inheritable, True)
2905 os.set_inheritable(non_inheritable, False)
2906 pass_fds = (inheritable, non_inheritable)
2907 args = [sys.executable, script]
2908 args += list(map(str, pass_fds))
2909
2910 p = subprocess.Popen(args,
2911 stdout=subprocess.PIPE, close_fds=True,
2912 pass_fds=pass_fds)
2913 output, ignored = p.communicate()
2914 fds = set(map(int, output.split(b',')))
2915
2916 # the inheritable file descriptor must be inherited, so its inheritable
2917 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002918 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002919
2920 # inheritable flag must not be changed in the parent process
2921 self.assertEqual(os.get_inheritable(inheritable), True)
2922 self.assertEqual(os.get_inheritable(non_inheritable), False)
2923
Gregory P. Smithce344102018-09-10 17:46:22 -07002924
2925 # bpo-32270: Ensure that descriptors specified in pass_fds
2926 # are inherited even if they are used in redirections.
2927 # Contributed by @izbyshev.
2928 def test_pass_fds_redirected(self):
2929 """Regression test for https://bugs.python.org/issue32270."""
2930 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2931 pass_fds = []
2932 for _ in range(2):
2933 fd = os.open(os.devnull, os.O_RDWR)
2934 self.addCleanup(os.close, fd)
2935 pass_fds.append(fd)
2936
2937 stdout_r, stdout_w = os.pipe()
2938 self.addCleanup(os.close, stdout_r)
2939 self.addCleanup(os.close, stdout_w)
2940 pass_fds.insert(1, stdout_w)
2941
2942 with subprocess.Popen([sys.executable, fd_status],
2943 stdin=pass_fds[0],
2944 stdout=pass_fds[1],
2945 stderr=pass_fds[2],
2946 close_fds=True,
2947 pass_fds=pass_fds):
2948 output = os.read(stdout_r, 1024)
2949 fds = {int(num) for num in output.split(b',')}
2950
2951 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2952
2953
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002954 def test_stdout_stdin_are_single_inout_fd(self):
2955 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002956 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002957 stdout=inout, stdin=inout)
2958 p.wait()
2959
2960 def test_stdout_stderr_are_single_inout_fd(self):
2961 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002962 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002963 stdout=inout, stderr=inout)
2964 p.wait()
2965
2966 def test_stderr_stdin_are_single_inout_fd(self):
2967 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002968 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002969 stderr=inout, stdin=inout)
2970 p.wait()
2971
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002972 def test_wait_when_sigchild_ignored(self):
2973 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2974 sigchild_ignore = support.findfile("sigchild_ignore.py",
2975 subdir="subprocessdata")
2976 p = subprocess.Popen([sys.executable, sigchild_ignore],
2977 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2978 stdout, stderr = p.communicate()
2979 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002980 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002981 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002982
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002983 def test_select_unbuffered(self):
2984 # Issue #11459: bufsize=0 should really set the pipes as
2985 # unbuffered (and therefore let select() work properly).
Hai Shi0c4f0f32020-06-30 21:46:31 +08002986 select = import_helper.import_module("select")
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002987 p = subprocess.Popen([sys.executable, "-c",
2988 'import sys;'
2989 'sys.stdout.write("apple")'],
2990 stdout=subprocess.PIPE,
2991 bufsize=0)
2992 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002993 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002994 try:
2995 self.assertEqual(f.read(4), b"appl")
2996 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2997 finally:
2998 p.wait()
2999
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003000 def test_zombie_fast_process_del(self):
3001 # Issue #12650: on Unix, if Popen.__del__() was called before the
3002 # process exited, it wouldn't be added to subprocess._active, and would
3003 # remain a zombie.
3004 # spawn a Popen, and delete its reference before it exits
3005 p = subprocess.Popen([sys.executable, "-c",
3006 'import sys, time;'
3007 'time.sleep(0.2)'],
3008 stdout=subprocess.PIPE,
3009 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02003010 self.addCleanup(p.stdout.close)
3011 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003012 ident = id(p)
3013 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08003014 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02003015 p = None
3016
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03003017 if mswindows:
3018 # subprocess._active is not used on Windows and is set to None.
3019 self.assertIsNone(subprocess._active)
3020 else:
3021 # check that p is in the active processes list
3022 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003023
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003024 def test_leak_fast_process_del_killed(self):
3025 # Issue #12650: on Unix, if Popen.__del__() was called before the
3026 # process exited, and the process got killed by a signal, it would never
3027 # be removed from subprocess._active, which triggered a FD and memory
3028 # leak.
3029 # spawn a Popen, delete its reference and kill it
3030 p = subprocess.Popen([sys.executable, "-c",
3031 'import time;'
3032 'time.sleep(3)'],
3033 stdout=subprocess.PIPE,
3034 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02003035 self.addCleanup(p.stdout.close)
3036 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003037 ident = id(p)
3038 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08003039 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02003040 p = None
3041
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003042 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03003043 if mswindows:
3044 # subprocess._active is not used on Windows and is set to None.
3045 self.assertIsNone(subprocess._active)
3046 else:
3047 # check that p is in the active processes list
3048 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003049
3050 # let some time for the process to exit, and create a new Popen: this
3051 # should trigger the wait() of p
3052 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01003053 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02003054 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003055 stdout=subprocess.PIPE,
3056 stderr=subprocess.PIPE) as proc:
3057 pass
3058 # p should have been wait()ed on, and removed from the _active list
3059 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03003060 if mswindows:
3061 # subprocess._active is not used on Windows and is set to None.
3062 self.assertIsNone(subprocess._active)
3063 else:
3064 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003065
Charles-François Natali249cdc32013-08-25 18:24:45 +02003066 def test_close_fds_after_preexec(self):
3067 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
3068
3069 # this FD is used as dup2() target by preexec_fn, and should be closed
3070 # in the child process
3071 fd = os.dup(1)
3072 self.addCleanup(os.close, fd)
3073
3074 p = subprocess.Popen([sys.executable, fd_status],
3075 stdout=subprocess.PIPE, close_fds=True,
3076 preexec_fn=lambda: os.dup2(1, fd))
3077 output, ignored = p.communicate()
3078
3079 remaining_fds = set(map(int, output.split(b',')))
3080
3081 self.assertNotIn(fd, remaining_fds)
3082
Victor Stinner8f437aa2014-10-05 17:25:19 +02003083 @support.cpython_only
3084 def test_fork_exec(self):
3085 # Issue #22290: fork_exec() must not crash on memory allocation failure
3086 # or other errors
3087 import _posixsubprocess
3088 gc_enabled = gc.isenabled()
3089 try:
3090 # Use a preexec function and enable the garbage collector
3091 # to force fork_exec() to re-enable the garbage collector
3092 # on error.
3093 func = lambda: None
3094 gc.enable()
3095
Victor Stinner8f437aa2014-10-05 17:25:19 +02003096 for args, exe_list, cwd, env_list in (
3097 (123, [b"exe"], None, [b"env"]),
3098 ([b"arg"], 123, None, [b"env"]),
3099 ([b"arg"], [b"exe"], 123, [b"env"]),
3100 ([b"arg"], [b"exe"], None, 123),
3101 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07003102 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02003103 _posixsubprocess.fork_exec(
3104 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003105 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02003106 -1, -1, -1, -1,
3107 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003108 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003109 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003110 func)
3111 # Attempt to prevent
3112 # "TypeError: fork_exec() takes exactly N arguments (M given)"
3113 # from passing the test. More refactoring to have us start
3114 # with a valid *args list, confirm a good call with that works
3115 # before mutating it in various ways to ensure that bad calls
3116 # with individual arg type errors raise a typeerror would be
3117 # ideal. Saving that for a future PR...
3118 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02003119 finally:
3120 if not gc_enabled:
3121 gc.disable()
3122
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003123 @support.cpython_only
3124 def test_fork_exec_sorted_fd_sanity_check(self):
3125 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3126 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003127 class BadInt:
3128 first = True
3129 def __init__(self, value):
3130 self.value = value
3131 def __int__(self):
3132 if self.first:
3133 self.first = False
3134 return self.value
3135 raise ValueError
3136
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003137 gc_enabled = gc.isenabled()
3138 try:
3139 gc.enable()
3140
3141 for fds_to_keep in (
3142 (-1, 2, 3, 4, 5), # Negative number.
3143 ('str', 4), # Not an int.
3144 (18, 23, 42, 2**63), # Out of range.
3145 (5, 4), # Not sorted.
3146 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003147 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003148 ):
3149 with self.assertRaises(
3150 ValueError,
3151 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3152 _posixsubprocess.fork_exec(
3153 [b"false"], [b"false"],
3154 True, fds_to_keep, None, [b"env"],
3155 -1, -1, -1, -1,
3156 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003157 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003158 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003159 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003160 self.assertIn('fds_to_keep', str(c.exception))
3161 finally:
3162 if not gc_enabled:
3163 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003164
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003165 def test_communicate_BrokenPipeError_stdin_close(self):
3166 # By not setting stdout or stderr or a timeout we force the fast path
3167 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003168 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003169 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3170 mock_proc_stdin.close.side_effect = BrokenPipeError
3171 proc.communicate() # Should swallow BrokenPipeError from close.
3172 mock_proc_stdin.close.assert_called_with()
3173
3174 def test_communicate_BrokenPipeError_stdin_write(self):
3175 # By not setting stdout or stderr or a timeout we force the fast path
3176 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003177 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003178 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3179 mock_proc_stdin.write.side_effect = BrokenPipeError
3180 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3181 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3182 mock_proc_stdin.close.assert_called_once_with()
3183
3184 def test_communicate_BrokenPipeError_stdin_flush(self):
3185 # Setting stdin and stdout forces the ._communicate() code path.
3186 # python -h exits faster than python -c pass (but spams stdout).
3187 proc = subprocess.Popen([sys.executable, '-h'],
3188 stdin=subprocess.PIPE,
3189 stdout=subprocess.PIPE)
3190 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3191 open(os.devnull, 'wb') as dev_null:
3192 mock_proc_stdin.flush.side_effect = BrokenPipeError
3193 # because _communicate registers a selector using proc.stdin...
3194 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3195 # _communicate() should swallow BrokenPipeError from flush.
3196 proc.communicate(b'stuff')
3197 mock_proc_stdin.flush.assert_called_once_with()
3198
3199 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3200 # Setting stdin and stdout forces the ._communicate() code path.
3201 # python -h exits faster than python -c pass (but spams stdout).
3202 proc = subprocess.Popen([sys.executable, '-h'],
3203 stdin=subprocess.PIPE,
3204 stdout=subprocess.PIPE)
3205 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3206 mock_proc_stdin.close.side_effect = BrokenPipeError
3207 # _communicate() should swallow BrokenPipeError from close.
3208 proc.communicate(timeout=999)
3209 mock_proc_stdin.close.assert_called_once_with()
3210
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003211 @unittest.skipUnless(_testcapi is not None
3212 and hasattr(_testcapi, 'W_STOPCODE'),
3213 'need _testcapi.W_STOPCODE')
3214 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003215 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003216 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003217 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003218
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003219 # Wait until the real process completes to avoid zombie process
Victor Stinner278c1e12020-03-31 20:08:12 +02003220 support.wait_process(proc.pid, exitcode=0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003221
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003222 status = _testcapi.W_STOPCODE(3)
Victor Stinner278c1e12020-03-31 20:08:12 +02003223 with mock.patch('subprocess.os.waitpid', return_value=(proc.pid, status)):
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003224 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003225
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003226 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003227
Victor Stinnere85a3052020-01-15 17:38:55 +01003228 def test_send_signal_race(self):
3229 # bpo-38630: send_signal() must poll the process exit status to reduce
3230 # the risk of sending the signal to the wrong process.
3231 proc = subprocess.Popen(ZERO_RETURN_CMD)
3232
3233 # wait until the process completes without using the Popen APIs.
Victor Stinner278c1e12020-03-31 20:08:12 +02003234 support.wait_process(proc.pid, exitcode=0)
Victor Stinnere85a3052020-01-15 17:38:55 +01003235
3236 # returncode is still None but the process completed.
3237 self.assertIsNone(proc.returncode)
3238
3239 with mock.patch("os.kill") as mock_kill:
3240 proc.send_signal(signal.SIGTERM)
3241
3242 # send_signal() didn't call os.kill() since the process already
3243 # completed.
3244 mock_kill.assert_not_called()
3245
3246 # Don't check the returncode value: the test reads the exit status,
3247 # so Popen failed to read it and uses a default returncode instead.
3248 self.assertIsNotNone(proc.returncode)
3249
Filipe Laíns01a202a2020-11-21 09:22:08 +00003250 def test_send_signal_race2(self):
3251 # bpo-40550: the process might exist between the returncode check and
3252 # the kill operation
3253 p = subprocess.Popen([sys.executable, '-c', 'exit(1)'])
3254
3255 # wait for process to exit
3256 while not p.returncode:
3257 p.poll()
3258
3259 with mock.patch.object(p, 'poll', new=lambda: None):
3260 p.returncode = None
3261 p.send_signal(signal.SIGTERM)
3262
Alex Rebertd3ae95e2020-01-22 18:28:31 -05003263 def test_communicate_repeated_call_after_stdout_close(self):
3264 proc = subprocess.Popen([sys.executable, '-c',
3265 'import os, time; os.close(1), time.sleep(2)'],
3266 stdout=subprocess.PIPE)
3267 while True:
3268 try:
3269 proc.communicate(timeout=0.1)
3270 return
3271 except subprocess.TimeoutExpired:
3272 pass
3273
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003274
Victor Stinner937ee9e2018-06-26 02:11:06 +02003275@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003276class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003277
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003278 def test_startupinfo(self):
3279 # startupinfo argument
3280 # We uses hardcoded constants, because we do not want to
3281 # depend on win32all.
3282 STARTF_USESHOWWINDOW = 1
3283 SW_MAXIMIZE = 3
3284 startupinfo = subprocess.STARTUPINFO()
3285 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3286 startupinfo.wShowWindow = SW_MAXIMIZE
3287 # Since Python is a console process, it won't be affected
3288 # by wShowWindow, but the argument should be silently
3289 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003290 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003291 startupinfo=startupinfo)
3292
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303293 def test_startupinfo_keywords(self):
3294 # startupinfo argument
3295 # We use hardcoded constants, because we do not want to
3296 # depend on win32all.
3297 STARTF_USERSHOWWINDOW = 1
3298 SW_MAXIMIZE = 3
3299 startupinfo = subprocess.STARTUPINFO(
3300 dwFlags=STARTF_USERSHOWWINDOW,
3301 wShowWindow=SW_MAXIMIZE
3302 )
3303 # Since Python is a console process, it won't be affected
3304 # by wShowWindow, but the argument should be silently
3305 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003306 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303307 startupinfo=startupinfo)
3308
Victor Stinner483422f2018-07-05 22:54:17 +02003309 def test_startupinfo_copy(self):
3310 # bpo-34044: Popen must not modify input STARTUPINFO structure
3311 startupinfo = subprocess.STARTUPINFO()
3312 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3313 startupinfo.wShowWindow = subprocess.SW_HIDE
3314
3315 # Call Popen() twice with the same startupinfo object to make sure
3316 # that it's not modified
3317 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003318 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003319 with open(os.devnull, 'w') as null:
3320 proc = subprocess.Popen(cmd,
3321 stdout=null,
3322 stderr=subprocess.STDOUT,
3323 startupinfo=startupinfo)
3324 with proc:
3325 proc.communicate()
3326 self.assertEqual(proc.returncode, 0)
3327
3328 self.assertEqual(startupinfo.dwFlags,
3329 subprocess.STARTF_USESHOWWINDOW)
3330 self.assertIsNone(startupinfo.hStdInput)
3331 self.assertIsNone(startupinfo.hStdOutput)
3332 self.assertIsNone(startupinfo.hStdError)
3333 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3334 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3335
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003336 def test_creationflags(self):
3337 # creationflags argument
3338 CREATE_NEW_CONSOLE = 16
3339 sys.stderr.write(" a DOS box should flash briefly ...\n")
3340 subprocess.call(sys.executable +
3341 ' -c "import time; time.sleep(0.25)"',
3342 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003343
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003344 def test_invalid_args(self):
3345 # invalid arguments should raise ValueError
3346 self.assertRaises(ValueError, subprocess.call,
3347 [sys.executable, "-c",
3348 "import sys; sys.exit(47)"],
3349 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003350
Oren Milman0b3a87e2017-09-14 22:30:28 +03003351 @support.cpython_only
3352 def test_issue31471(self):
3353 # There shouldn't be an assertion failure in Popen() in case the env
3354 # argument has a bad keys() method.
3355 class BadEnv(dict):
3356 keys = None
3357 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003358 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003359
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003360 def test_close_fds(self):
3361 # close file descriptors
3362 rc = subprocess.call([sys.executable, "-c",
3363 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003364 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003365 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003366
Segev Finerb2a60832017-12-18 11:28:19 +02003367 def test_close_fds_with_stdio(self):
3368 import msvcrt
3369
3370 fds = os.pipe()
3371 self.addCleanup(os.close, fds[0])
3372 self.addCleanup(os.close, fds[1])
3373
3374 handles = []
3375 for fd in fds:
3376 os.set_inheritable(fd, True)
3377 handles.append(msvcrt.get_osfhandle(fd))
3378
3379 p = subprocess.Popen([sys.executable, "-c",
3380 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3381 stdout=subprocess.PIPE, close_fds=False)
3382 stdout, stderr = p.communicate()
3383 self.assertEqual(p.returncode, 0)
3384 int(stdout.strip()) # Check that stdout is an integer
3385
3386 p = subprocess.Popen([sys.executable, "-c",
3387 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3388 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3389 stdout, stderr = p.communicate()
3390 self.assertEqual(p.returncode, 1)
3391 self.assertIn(b"OSError", stderr)
3392
3393 # The same as the previous call, but with an empty handle_list
3394 handle_list = []
3395 startupinfo = subprocess.STARTUPINFO()
3396 startupinfo.lpAttributeList = {"handle_list": handle_list}
3397 p = subprocess.Popen([sys.executable, "-c",
3398 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3399 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3400 startupinfo=startupinfo, close_fds=True)
3401 stdout, stderr = p.communicate()
3402 self.assertEqual(p.returncode, 1)
3403 self.assertIn(b"OSError", stderr)
3404
3405 # Check for a warning due to using handle_list and close_fds=False
Hai Shi0c4f0f32020-06-30 21:46:31 +08003406 with warnings_helper.check_warnings((".*overriding close_fds",
3407 RuntimeWarning)):
Segev Finerb2a60832017-12-18 11:28:19 +02003408 startupinfo = subprocess.STARTUPINFO()
3409 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3410 p = subprocess.Popen([sys.executable, "-c",
3411 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3412 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3413 startupinfo=startupinfo, close_fds=False)
3414 stdout, stderr = p.communicate()
3415 self.assertEqual(p.returncode, 0)
3416
3417 def test_empty_attribute_list(self):
3418 startupinfo = subprocess.STARTUPINFO()
3419 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003420 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003421 startupinfo=startupinfo)
3422
3423 def test_empty_handle_list(self):
3424 startupinfo = subprocess.STARTUPINFO()
3425 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003426 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003427 startupinfo=startupinfo)
3428
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003429 def test_shell_sequence(self):
3430 # Run command through the shell (sequence)
3431 newenv = os.environ.copy()
3432 newenv["FRUIT"] = "physalis"
3433 p = subprocess.Popen(["set"], shell=1,
3434 stdout=subprocess.PIPE,
3435 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003436 with p:
3437 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003438
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003439 def test_shell_string(self):
3440 # Run command through the shell (string)
3441 newenv = os.environ.copy()
3442 newenv["FRUIT"] = "physalis"
3443 p = subprocess.Popen("set", shell=1,
3444 stdout=subprocess.PIPE,
3445 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003446 with p:
3447 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003448
Steve Dower050acae2016-09-06 20:16:17 -07003449 def test_shell_encodings(self):
3450 # Run command through the shell (string)
3451 for enc in ['ansi', 'oem']:
3452 newenv = os.environ.copy()
3453 newenv["FRUIT"] = "physalis"
3454 p = subprocess.Popen("set", shell=1,
3455 stdout=subprocess.PIPE,
3456 env=newenv,
3457 encoding=enc)
3458 with p:
3459 self.assertIn("physalis", p.stdout.read(), enc)
3460
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003461 def test_call_string(self):
3462 # call() function with string argument on Windows
3463 rc = subprocess.call(sys.executable +
3464 ' -c "import sys; sys.exit(47)"')
3465 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003466
Florent Xicluna4886d242010-03-08 13:27:26 +00003467 def _kill_process(self, method, *args):
3468 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003469 p = subprocess.Popen([sys.executable, "-c", """if 1:
3470 import sys, time
3471 sys.stdout.write('x\\n')
3472 sys.stdout.flush()
3473 time.sleep(30)
3474 """],
3475 stdin=subprocess.PIPE,
3476 stdout=subprocess.PIPE,
3477 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003478 with p:
3479 # Wait for the interpreter to be completely initialized before
3480 # sending any signal.
3481 p.stdout.read(1)
3482 getattr(p, method)(*args)
3483 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003484 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003485 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003486 self.assertNotEqual(returncode, 0)
3487
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003488 def _kill_dead_process(self, method, *args):
3489 p = subprocess.Popen([sys.executable, "-c", """if 1:
3490 import sys, time
3491 sys.stdout.write('x\\n')
3492 sys.stdout.flush()
3493 sys.exit(42)
3494 """],
3495 stdin=subprocess.PIPE,
3496 stdout=subprocess.PIPE,
3497 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003498 with p:
3499 # Wait for the interpreter to be completely initialized before
3500 # sending any signal.
3501 p.stdout.read(1)
3502 # The process should end after this
3503 time.sleep(1)
3504 # This shouldn't raise even though the child is now dead
3505 getattr(p, method)(*args)
3506 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003507 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003508 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003509 self.assertEqual(rc, 42)
3510
Florent Xicluna4886d242010-03-08 13:27:26 +00003511 def test_send_signal(self):
3512 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003513
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003514 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003515 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003516
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003517 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003518 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003519
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003520 def test_send_signal_dead(self):
3521 self._kill_dead_process('send_signal', signal.SIGTERM)
3522
3523 def test_kill_dead(self):
3524 self._kill_dead_process('kill')
3525
3526 def test_terminate_dead(self):
3527 self._kill_dead_process('terminate')
3528
Martin Panter23172bd2016-04-16 11:28:10 +00003529class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003530
3531 class RecordingPopen(subprocess.Popen):
3532 """A Popen that saves a reference to each instance for testing."""
3533 instances_created = []
3534
3535 def __init__(self, *args, **kwargs):
3536 super().__init__(*args, **kwargs)
3537 self.instances_created.append(self)
3538
3539 @mock.patch.object(subprocess.Popen, "_communicate")
3540 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3541 **kwargs):
3542 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3543
3544 This avoids the need to actually try and get test environments to send
3545 and receive signals reliably across platforms. The net effect of a ^C
3546 happening during a blocking subprocess execution which we want to clean
3547 up from is a KeyboardInterrupt coming out of communicate() or wait().
3548 """
3549
3550 mock__communicate.side_effect = KeyboardInterrupt
3551 try:
3552 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3553 # We patch out _wait() as no signal was involved so the
3554 # child process isn't actually going to exit rapidly.
3555 mock__wait.side_effect = KeyboardInterrupt
3556 with mock.patch.object(subprocess, "Popen",
3557 self.RecordingPopen):
3558 with self.assertRaises(KeyboardInterrupt):
3559 popener([sys.executable, "-c",
3560 "import time\ntime.sleep(9)\nimport sys\n"
3561 "sys.stderr.write('\\n!runaway child!\\n')"],
3562 stdout=subprocess.DEVNULL, **kwargs)
3563 for call in mock__wait.call_args_list[1:]:
3564 self.assertNotEqual(
3565 call, mock.call(timeout=None),
3566 "no open-ended wait() after the first allowed: "
3567 f"{mock__wait.call_args_list}")
3568 sigint_calls = []
3569 for call in mock__wait.call_args_list:
3570 if call == mock.call(timeout=0.25): # from Popen.__init__
3571 sigint_calls.append(call)
3572 self.assertLessEqual(mock__wait.call_count, 2,
3573 msg=mock__wait.call_args_list)
3574 self.assertEqual(len(sigint_calls), 1,
3575 msg=mock__wait.call_args_list)
3576 finally:
3577 # cleanup the forgotten (due to our mocks) child process
3578 process = self.RecordingPopen.instances_created.pop()
3579 process.kill()
3580 process.wait()
3581 self.assertEqual([], self.RecordingPopen.instances_created)
3582
3583 def test_call_keyboardinterrupt_no_kill(self):
3584 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3585
3586 def test_run_keyboardinterrupt_no_kill(self):
3587 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3588
3589 def test_context_manager_keyboardinterrupt_no_kill(self):
3590 def popen_via_context_manager(*args, **kwargs):
3591 with subprocess.Popen(*args, **kwargs) as unused_process:
3592 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3593 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3594
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003595 def test_getoutput(self):
3596 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3597 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3598 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003599
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003600 # we use mkdtemp in the next line to create an empty directory
3601 # under our exclusive control; from that, we can invent a pathname
3602 # that we _know_ won't exist. This is guaranteed to fail.
3603 dir = None
3604 try:
3605 dir = tempfile.mkdtemp()
3606 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003607 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003608 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003609 self.assertNotEqual(status, 0)
3610 finally:
3611 if dir is not None:
3612 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003613
Gregory P. Smithace55862015-04-07 15:57:54 -07003614 def test__all__(self):
3615 """Ensure that __all__ is populated properly."""
Ruben Vorderman23c0fb82020-10-20 01:30:02 +02003616 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp", "fcntl"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003617 exported = set(subprocess.__all__)
3618 possible_exports = set()
3619 import types
3620 for name, value in subprocess.__dict__.items():
3621 if name.startswith('_'):
3622 continue
3623 if isinstance(value, (types.ModuleType,)):
3624 continue
3625 possible_exports.add(name)
3626 self.assertEqual(exported, possible_exports - intentionally_excluded)
3627
3628
Martin Panter23172bd2016-04-16 11:28:10 +00003629@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3630 "Test needs selectors.PollSelector")
3631class ProcessTestCaseNoPoll(ProcessTestCase):
3632 def setUp(self):
3633 self.orig_selector = subprocess._PopenSelector
3634 subprocess._PopenSelector = selectors.SelectSelector
3635 ProcessTestCase.setUp(self)
3636
3637 def tearDown(self):
3638 subprocess._PopenSelector = self.orig_selector
3639 ProcessTestCase.tearDown(self)
3640
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003641
Victor Stinner937ee9e2018-06-26 02:11:06 +02003642@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003643class CommandsWithSpaces (BaseTestCase):
3644
3645 def setUp(self):
3646 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003647 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003648 self.fname = fname.lower ()
3649 os.write(f, b"import sys;"
3650 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3651 )
3652 os.close(f)
3653
3654 def tearDown(self):
3655 os.remove(self.fname)
3656 super().tearDown()
3657
3658 def with_spaces(self, *args, **kwargs):
3659 kwargs['stdout'] = subprocess.PIPE
3660 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003661 with p:
3662 self.assertEqual(
3663 p.stdout.read ().decode("mbcs"),
3664 "2 [%r, 'ab cd']" % self.fname
3665 )
Tim Golden126c2962010-08-11 14:20:40 +00003666
3667 def test_shell_string_with_spaces(self):
3668 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003669 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3670 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003671
3672 def test_shell_sequence_with_spaces(self):
3673 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003674 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003675
3676 def test_noshell_string_with_spaces(self):
3677 # call() function with string argument with spaces on Windows
3678 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3679 "ab cd"))
3680
3681 def test_noshell_sequence_with_spaces(self):
3682 # call() function with sequence argument with spaces on Windows
3683 self.with_spaces([sys.executable, self.fname, "ab cd"])
3684
Brian Curtin79cdb662010-12-03 02:46:02 +00003685
Georg Brandla86b2622012-02-20 21:34:57 +01003686class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003687
3688 def test_pipe(self):
3689 with subprocess.Popen([sys.executable, "-c",
3690 "import sys;"
3691 "sys.stdout.write('stdout');"
3692 "sys.stderr.write('stderr');"],
3693 stdout=subprocess.PIPE,
3694 stderr=subprocess.PIPE) as proc:
3695 self.assertEqual(proc.stdout.read(), b"stdout")
Victor Stinner6cac1132019-12-08 08:38:16 +01003696 self.assertEqual(proc.stderr.read(), b"stderr")
Brian Curtin79cdb662010-12-03 02:46:02 +00003697
3698 self.assertTrue(proc.stdout.closed)
3699 self.assertTrue(proc.stderr.closed)
3700
3701 def test_returncode(self):
3702 with subprocess.Popen([sys.executable, "-c",
3703 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003704 pass
3705 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003706 self.assertEqual(proc.returncode, 100)
3707
3708 def test_communicate_stdin(self):
3709 with subprocess.Popen([sys.executable, "-c",
3710 "import sys;"
3711 "sys.exit(sys.stdin.read() == 'context')"],
3712 stdin=subprocess.PIPE) as proc:
3713 proc.communicate(b"context")
3714 self.assertEqual(proc.returncode, 1)
3715
3716 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003717 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003718 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003719 stdout=subprocess.PIPE,
3720 stderr=subprocess.PIPE) as proc:
3721 pass
3722
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003723 def test_broken_pipe_cleanup(self):
3724 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003725 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003726 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003727 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003728 proc = proc.__enter__()
3729 # Prepare to send enough data to overflow any OS pipe buffering and
3730 # guarantee a broken pipe error. Data is held in BufferedWriter
3731 # buffer until closed.
3732 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003733 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003734 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003735 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003736 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003737 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003738
Brian Curtin79cdb662010-12-03 02:46:02 +00003739
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003740if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003741 unittest.main()