Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1 | import unittest |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1ef8c7e | 2016-06-04 00:22:17 +0000 | [diff] [blame] | 2 | from unittest import mock |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 3 | from test import support |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 4 | from test.support import import_helper |
| 5 | from test.support import os_helper |
| 6 | from test.support import warnings_helper |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 7 | import subprocess |
| 8 | import sys |
| 9 | import signal |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 10 | import io |
Alexey Izbyshev | 0e7144b | 2018-03-26 22:49:35 +0300 | [diff] [blame] | 11 | import itertools |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 12 | import os |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 13 | import errno |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 14 | import tempfile |
| 15 | import time |
Gregory P. Smith | 580d278 | 2019-09-11 04:23:05 -0500 | [diff] [blame] | 16 | import traceback |
Guido van Rossum | 48b069a | 2020-04-07 09:50:06 -0700 | [diff] [blame] | 17 | import types |
Charles-François Natali | 3a4586a | 2013-11-08 19:56:59 +0100 | [diff] [blame] | 18 | import selectors |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 19 | import sysconfig |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 20 | import select |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 21 | import shutil |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 22 | import threading |
Benjamin Peterson | b870aa1 | 2011-12-10 12:44:25 -0500 | [diff] [blame] | 23 | import gc |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 24 | import textwrap |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 25 | import json |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 26 | from test.support.os_helper import FakePath |
Benjamin Peterson | 964561b | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 27 | |
| 28 | try: |
Victor Stinner | 7b7c6dc | 2017-08-10 12:37:39 +0200 | [diff] [blame] | 29 | import _testcapi |
| 30 | except ImportError: |
| 31 | _testcapi = None |
| 32 | |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 33 | try: |
| 34 | import pwd |
| 35 | except ImportError: |
| 36 | pwd = None |
| 37 | try: |
| 38 | import grp |
| 39 | except ImportError: |
| 40 | grp = None |
Victor Stinner | 8f4ef3b | 2019-07-01 18:28:25 +0200 | [diff] [blame] | 41 | |
Ruben Vorderman | 23c0fb8 | 2020-10-20 01:30:02 +0200 | [diff] [blame] | 42 | try: |
| 43 | import fcntl |
| 44 | except: |
| 45 | fcntl = None |
| 46 | |
Steve Dower | 22d0698 | 2016-09-06 19:38:15 -0700 | [diff] [blame] | 47 | if support.PGO: |
| 48 | raise unittest.SkipTest("test is not helpful for PGO") |
| 49 | |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 50 | mswindows = (sys.platform == "win32") |
| 51 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 52 | # |
| 53 | # Depends on the following external programs: Python |
| 54 | # |
| 55 | |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 56 | if mswindows: |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 57 | SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), ' |
| 58 | 'os.O_BINARY);') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 59 | else: |
| 60 | SETBINARY = '' |
| 61 | |
Victor Stinner | 9a83f65 | 2017-08-21 23:51:31 +0200 | [diff] [blame] | 62 | NONEXISTING_CMD = ('nonexisting_i_hope',) |
Victor Stinner | b31206a | 2018-01-25 19:06:05 +0100 | [diff] [blame] | 63 | # Ignore errors that indicate the command was not found |
| 64 | NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError) |
Victor Stinner | 9a83f65 | 2017-08-21 23:51:31 +0200 | [diff] [blame] | 65 | |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 66 | ZERO_RETURN_CMD = (sys.executable, '-c', 'pass') |
| 67 | |
| 68 | |
| 69 | def setUpModule(): |
| 70 | shell_true = shutil.which('true') |
Pablo Galindo | 46113e0 | 2019-10-13 02:40:24 +0100 | [diff] [blame] | 71 | if shell_true is None: |
| 72 | return |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 73 | if (os.access(shell_true, os.X_OK) and |
| 74 | subprocess.run([shell_true]).returncode == 0): |
| 75 | global ZERO_RETURN_CMD |
| 76 | ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup. |
| 77 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 78 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 79 | class BaseTestCase(unittest.TestCase): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 80 | def setUp(self): |
| 81 | # Try to minimize the number of children we have so this test |
| 82 | # doesn't crash on some buildbots (Alphas in particular). |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 83 | support.reap_children() |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 84 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 85 | def tearDown(self): |
Ruslan Kuprieiev | 042821a | 2019-06-28 19:12:16 +0300 | [diff] [blame] | 86 | if not mswindows: |
| 87 | # subprocess._active is not used on Windows and is set to None. |
| 88 | for inst in subprocess._active: |
| 89 | inst.wait() |
| 90 | subprocess._cleanup() |
| 91 | self.assertFalse( |
| 92 | subprocess._active, "subprocess._active not empty" |
| 93 | ) |
Victor Stinner | cc42c12 | 2017-07-28 18:00:22 +0200 | [diff] [blame] | 94 | self.doCleanups() |
| 95 | support.reap_children() |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 96 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 97 | |
Gregory P. Smith | 3d8e776 | 2012-11-10 22:32:22 -0800 | [diff] [blame] | 98 | class PopenTestException(Exception): |
| 99 | pass |
| 100 | |
| 101 | |
| 102 | class PopenExecuteChildRaises(subprocess.Popen): |
| 103 | """Popen subclass for testing cleanup of subprocess.PIPE filehandles when |
| 104 | _execute_child fails. |
| 105 | """ |
| 106 | def _execute_child(self, *args, **kwargs): |
| 107 | raise PopenTestException("Forced Exception for Test") |
| 108 | |
| 109 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 110 | class ProcessTestCase(BaseTestCase): |
| 111 | |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 112 | def test_io_buffered_by_default(self): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 113 | p = subprocess.Popen(ZERO_RETURN_CMD, |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 114 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 115 | stderr=subprocess.PIPE) |
| 116 | try: |
| 117 | self.assertIsInstance(p.stdin, io.BufferedIOBase) |
| 118 | self.assertIsInstance(p.stdout, io.BufferedIOBase) |
| 119 | self.assertIsInstance(p.stderr, io.BufferedIOBase) |
| 120 | finally: |
Gregory P. Smith | a1b9ed3 | 2013-03-23 11:54:22 -0700 | [diff] [blame] | 121 | p.stdin.close() |
| 122 | p.stdout.close() |
| 123 | p.stderr.close() |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 124 | p.wait() |
| 125 | |
| 126 | def test_io_unbuffered_works(self): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 127 | p = subprocess.Popen(ZERO_RETURN_CMD, |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 128 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 129 | stderr=subprocess.PIPE, bufsize=0) |
| 130 | try: |
| 131 | self.assertIsInstance(p.stdin, io.RawIOBase) |
| 132 | self.assertIsInstance(p.stdout, io.RawIOBase) |
| 133 | self.assertIsInstance(p.stderr, io.RawIOBase) |
| 134 | finally: |
Gregory P. Smith | a1b9ed3 | 2013-03-23 11:54:22 -0700 | [diff] [blame] | 135 | p.stdin.close() |
| 136 | p.stdout.close() |
| 137 | p.stderr.close() |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 138 | p.wait() |
| 139 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 140 | def test_call_seq(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 141 | # call() function with sequence argument |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 142 | rc = subprocess.call([sys.executable, "-c", |
| 143 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 144 | self.assertEqual(rc, 47) |
| 145 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 146 | def test_call_timeout(self): |
| 147 | # call() function with timeout argument; we want to test that the child |
| 148 | # process gets killed when the timeout expires. If the child isn't |
| 149 | # killed, this call will deadlock since subprocess.call waits for the |
| 150 | # child. |
| 151 | self.assertRaises(subprocess.TimeoutExpired, subprocess.call, |
| 152 | [sys.executable, "-c", "while True: pass"], |
| 153 | timeout=0.1) |
| 154 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 155 | def test_check_call_zero(self): |
| 156 | # check_call() function with zero return code |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 157 | rc = subprocess.check_call(ZERO_RETURN_CMD) |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 158 | self.assertEqual(rc, 0) |
| 159 | |
| 160 | def test_check_call_nonzero(self): |
| 161 | # check_call() function with non-zero return code |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 162 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 163 | subprocess.check_call([sys.executable, "-c", |
| 164 | "import sys; sys.exit(47)"]) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 165 | self.assertEqual(c.exception.returncode, 47) |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 166 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 167 | def test_check_output(self): |
| 168 | # check_output() function with zero return code |
| 169 | output = subprocess.check_output( |
| 170 | [sys.executable, "-c", "print('BDFL')"]) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 171 | self.assertIn(b'BDFL', output) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 172 | |
| 173 | def test_check_output_nonzero(self): |
| 174 | # check_call() function with non-zero return code |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 175 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 176 | subprocess.check_output( |
| 177 | [sys.executable, "-c", "import sys; sys.exit(5)"]) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 178 | self.assertEqual(c.exception.returncode, 5) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 179 | |
| 180 | def test_check_output_stderr(self): |
| 181 | # check_output() function stderr redirected to stdout |
| 182 | output = subprocess.check_output( |
| 183 | [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"], |
| 184 | stderr=subprocess.STDOUT) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 185 | self.assertIn(b'BDFL', output) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 186 | |
Serhiy Storchaka | fcd9f22 | 2013-04-22 20:20:54 +0300 | [diff] [blame] | 187 | def test_check_output_stdin_arg(self): |
| 188 | # check_output() can be called with stdin set to a file |
| 189 | tf = tempfile.TemporaryFile() |
| 190 | self.addCleanup(tf.close) |
| 191 | tf.write(b'pear') |
| 192 | tf.seek(0) |
| 193 | output = subprocess.check_output( |
| 194 | [sys.executable, "-c", |
| 195 | "import sys; sys.stdout.write(sys.stdin.read().upper())"], |
| 196 | stdin=tf) |
| 197 | self.assertIn(b'PEAR', output) |
| 198 | |
| 199 | def test_check_output_input_arg(self): |
| 200 | # check_output() can be called with input set to a string |
| 201 | output = subprocess.check_output( |
| 202 | [sys.executable, "-c", |
| 203 | "import sys; sys.stdout.write(sys.stdin.read().upper())"], |
| 204 | input=b'pear') |
| 205 | self.assertIn(b'PEAR', output) |
| 206 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 207 | def test_check_output_stdout_arg(self): |
Serhiy Storchaka | fcd9f22 | 2013-04-22 20:20:54 +0300 | [diff] [blame] | 208 | # check_output() refuses to accept 'stdout' argument |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 209 | with self.assertRaises(ValueError) as c: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 210 | output = subprocess.check_output( |
| 211 | [sys.executable, "-c", "print('will not be run')"], |
| 212 | stdout=sys.stdout) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 213 | self.fail("Expected ValueError when stdout arg supplied.") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 214 | self.assertIn('stdout', c.exception.args[0]) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 215 | |
Serhiy Storchaka | fcd9f22 | 2013-04-22 20:20:54 +0300 | [diff] [blame] | 216 | def test_check_output_stdin_with_input_arg(self): |
| 217 | # check_output() refuses to accept 'stdin' with 'input' |
| 218 | tf = tempfile.TemporaryFile() |
| 219 | self.addCleanup(tf.close) |
| 220 | tf.write(b'pear') |
| 221 | tf.seek(0) |
| 222 | with self.assertRaises(ValueError) as c: |
| 223 | output = subprocess.check_output( |
| 224 | [sys.executable, "-c", "print('will not be run')"], |
| 225 | stdin=tf, input=b'hare') |
| 226 | self.fail("Expected ValueError when stdin and input args supplied.") |
| 227 | self.assertIn('stdin', c.exception.args[0]) |
| 228 | self.assertIn('input', c.exception.args[0]) |
| 229 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 230 | def test_check_output_timeout(self): |
| 231 | # check_output() function with timeout arg |
| 232 | with self.assertRaises(subprocess.TimeoutExpired) as c: |
| 233 | output = subprocess.check_output( |
| 234 | [sys.executable, "-c", |
Victor Stinner | 149b1c7 | 2011-06-06 23:43:02 +0200 | [diff] [blame] | 235 | "import sys, time\n" |
| 236 | "sys.stdout.write('BDFL')\n" |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 237 | "sys.stdout.flush()\n" |
Victor Stinner | 149b1c7 | 2011-06-06 23:43:02 +0200 | [diff] [blame] | 238 | "time.sleep(3600)"], |
Reid Kleckner | da9ac72 | 2011-03-16 17:08:21 -0400 | [diff] [blame] | 239 | # Some heavily loaded buildbots (sparc Debian 3.x) require |
| 240 | # this much time to start and print. |
| 241 | timeout=3) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 242 | self.fail("Expected TimeoutExpired.") |
| 243 | self.assertEqual(c.exception.output, b'BDFL') |
| 244 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 245 | def test_call_kwargs(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 246 | # call() function with keyword args |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 247 | newenv = os.environ.copy() |
| 248 | newenv["FRUIT"] = "banana" |
| 249 | rc = subprocess.call([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 250 | 'import sys, os;' |
| 251 | 'sys.exit(os.getenv("FRUIT")=="banana")'], |
| 252 | env=newenv) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 253 | self.assertEqual(rc, 1) |
| 254 | |
Victor Stinner | 87b9bc3 | 2011-06-01 00:57:47 +0200 | [diff] [blame] | 255 | def test_invalid_args(self): |
| 256 | # Popen() called with invalid arguments should raise TypeError |
| 257 | # but Popen.__del__ should not complain (issue #12085) |
| 258 | with support.captured_stderr() as s: |
| 259 | self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1) |
| 260 | argcount = subprocess.Popen.__init__.__code__.co_argcount |
| 261 | too_many_args = [0] * (argcount + 1) |
| 262 | self.assertRaises(TypeError, subprocess.Popen, *too_many_args) |
| 263 | self.assertEqual(s.getvalue(), '') |
| 264 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 265 | def test_stdin_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 266 | # .stdin is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 267 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 268 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 269 | self.addCleanup(p.stdout.close) |
| 270 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 271 | p.wait() |
| 272 | self.assertEqual(p.stdin, None) |
| 273 | |
| 274 | def test_stdout_none(self): |
Ezio Melotti | 42a541b | 2013-03-11 05:53:34 +0200 | [diff] [blame] | 275 | # .stdout is None when not redirected, and the child's stdout will |
| 276 | # be inherited from the parent. In order to test this we run a |
| 277 | # subprocess in a subprocess: |
| 278 | # this_test |
| 279 | # \-- subprocess created by this test (parent) |
| 280 | # \-- subprocess created by the parent subprocess (child) |
| 281 | # The parent doesn't specify stdout, so the child will use the |
| 282 | # parent's stdout. This test checks that the message printed by the |
| 283 | # child goes to the parent stdout. The parent also checks that the |
| 284 | # child's stdout is None. See #11963. |
| 285 | code = ('import sys; from subprocess import Popen, PIPE;' |
| 286 | 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],' |
| 287 | ' stdin=PIPE, stderr=PIPE);' |
| 288 | 'p.wait(); assert p.stdout is None;') |
| 289 | p = subprocess.Popen([sys.executable, "-c", code], |
| 290 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 291 | self.addCleanup(p.stdout.close) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 292 | self.addCleanup(p.stderr.close) |
Ezio Melotti | 42a541b | 2013-03-11 05:53:34 +0200 | [diff] [blame] | 293 | out, err = p.communicate() |
| 294 | self.assertEqual(p.returncode, 0, err) |
| 295 | self.assertEqual(out.rstrip(), b'test_stdout_none') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 296 | |
| 297 | def test_stderr_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 298 | # .stderr is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 299 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 300 | stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 301 | self.addCleanup(p.stdout.close) |
| 302 | self.addCleanup(p.stdin.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 303 | p.wait() |
| 304 | self.assertEqual(p.stderr, None) |
| 305 | |
Chris Jerdonek | 776cb19 | 2012-10-08 15:56:43 -0700 | [diff] [blame] | 306 | def _assert_python(self, pre_args, **kwargs): |
| 307 | # We include sys.exit() to prevent the test runner from hanging |
| 308 | # whenever python is found. |
| 309 | args = pre_args + ["import sys; sys.exit(47)"] |
| 310 | p = subprocess.Popen(args, **kwargs) |
| 311 | p.wait() |
| 312 | self.assertEqual(47, p.returncode) |
| 313 | |
| 314 | def test_executable(self): |
| 315 | # Check that the executable argument works. |
Chris Jerdonek | 86b0fb2 | 2012-10-09 13:17:49 -0700 | [diff] [blame] | 316 | # |
| 317 | # On Unix (non-Mac and non-Windows), Python looks at args[0] to |
| 318 | # determine where its standard library is, so we need the directory |
| 319 | # of args[0] to be valid for the Popen() call to Python to succeed. |
| 320 | # See also issue #16170 and issue #7774. |
| 321 | doesnotexist = os.path.join(os.path.dirname(sys.executable), |
| 322 | "doesnotexist") |
| 323 | self._assert_python([doesnotexist, "-c"], executable=sys.executable) |
Chris Jerdonek | 776cb19 | 2012-10-08 15:56:43 -0700 | [diff] [blame] | 324 | |
Serhiy Storchaka | 9e3c452 | 2019-05-28 22:49:35 +0300 | [diff] [blame] | 325 | def test_bytes_executable(self): |
| 326 | doesnotexist = os.path.join(os.path.dirname(sys.executable), |
| 327 | "doesnotexist") |
| 328 | self._assert_python([doesnotexist, "-c"], |
| 329 | executable=os.fsencode(sys.executable)) |
| 330 | |
| 331 | def test_pathlike_executable(self): |
| 332 | doesnotexist = os.path.join(os.path.dirname(sys.executable), |
| 333 | "doesnotexist") |
| 334 | self._assert_python([doesnotexist, "-c"], |
| 335 | executable=FakePath(sys.executable)) |
| 336 | |
Chris Jerdonek | 776cb19 | 2012-10-08 15:56:43 -0700 | [diff] [blame] | 337 | def test_executable_takes_precedence(self): |
| 338 | # Check that the executable argument takes precedence over args[0]. |
| 339 | # |
| 340 | # Verify first that the call succeeds without the executable arg. |
| 341 | pre_args = [sys.executable, "-c"] |
| 342 | self._assert_python(pre_args) |
Victor Stinner | b31206a | 2018-01-25 19:06:05 +0100 | [diff] [blame] | 343 | self.assertRaises(NONEXISTING_ERRORS, |
Xavier de Gaye | 38c8b7d | 2016-11-14 17:14:42 +0100 | [diff] [blame] | 344 | self._assert_python, pre_args, |
Victor Stinner | b31206a | 2018-01-25 19:06:05 +0100 | [diff] [blame] | 345 | executable=NONEXISTING_CMD[0]) |
Chris Jerdonek | 776cb19 | 2012-10-08 15:56:43 -0700 | [diff] [blame] | 346 | |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 347 | @unittest.skipIf(mswindows, "executable argument replaces shell") |
Chris Jerdonek | 776cb19 | 2012-10-08 15:56:43 -0700 | [diff] [blame] | 348 | def test_executable_replaces_shell(self): |
| 349 | # Check that the executable argument replaces the default shell |
| 350 | # when shell=True. |
| 351 | self._assert_python([], executable=sys.executable, shell=True) |
| 352 | |
Serhiy Storchaka | 9e3c452 | 2019-05-28 22:49:35 +0300 | [diff] [blame] | 353 | @unittest.skipIf(mswindows, "executable argument replaces shell") |
| 354 | def test_bytes_executable_replaces_shell(self): |
| 355 | self._assert_python([], executable=os.fsencode(sys.executable), |
| 356 | shell=True) |
| 357 | |
| 358 | @unittest.skipIf(mswindows, "executable argument replaces shell") |
| 359 | def test_pathlike_executable_replaces_shell(self): |
| 360 | self._assert_python([], executable=FakePath(sys.executable), |
| 361 | shell=True) |
| 362 | |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 363 | # For use in the test_cwd* tests below. |
| 364 | def _normalize_cwd(self, cwd): |
| 365 | # Normalize an expected cwd (for Tru64 support). |
| 366 | # We can't use os.path.realpath since it doesn't expand Tru64 {memb} |
| 367 | # strings. See bug #1063571. |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 368 | with os_helper.change_cwd(cwd): |
Serhiy Storchaka | 2a23adf | 2015-09-06 14:13:25 +0300 | [diff] [blame] | 369 | return os.getcwd() |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 370 | |
| 371 | # For use in the test_cwd* tests below. |
| 372 | def _split_python_path(self): |
| 373 | # Return normalized (python_dir, python_base). |
| 374 | python_path = os.path.realpath(sys.executable) |
| 375 | return os.path.split(python_path) |
| 376 | |
| 377 | # For use in the test_cwd* tests below. |
| 378 | def _assert_cwd(self, expected_cwd, python_arg, **kwargs): |
| 379 | # Invoke Python via Popen, and assert that (1) the call succeeds, |
| 380 | # and that (2) the current working directory of the child process |
| 381 | # matches *expected_cwd*. |
| 382 | p = subprocess.Popen([python_arg, "-c", |
| 383 | "import os, sys; " |
Serhiy Storchaka | b1a8730 | 2020-07-26 10:21:39 +0300 | [diff] [blame] | 384 | "buf = sys.stdout.buffer; " |
| 385 | "buf.write(os.getcwd().encode()); " |
| 386 | "buf.flush(); " |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 387 | "sys.exit(47)"], |
| 388 | stdout=subprocess.PIPE, |
| 389 | **kwargs) |
| 390 | self.addCleanup(p.stdout.close) |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 391 | p.wait() |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 392 | self.assertEqual(47, p.returncode) |
| 393 | normcase = os.path.normcase |
| 394 | self.assertEqual(normcase(expected_cwd), |
Serhiy Storchaka | b1a8730 | 2020-07-26 10:21:39 +0300 | [diff] [blame] | 395 | normcase(p.stdout.read().decode())) |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 396 | |
| 397 | def test_cwd(self): |
| 398 | # Check that cwd changes the cwd for the child process. |
| 399 | temp_dir = tempfile.gettempdir() |
| 400 | temp_dir = self._normalize_cwd(temp_dir) |
| 401 | self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir) |
| 402 | |
Serhiy Storchaka | 9e3c452 | 2019-05-28 22:49:35 +0300 | [diff] [blame] | 403 | def test_cwd_with_bytes(self): |
| 404 | temp_dir = tempfile.gettempdir() |
| 405 | temp_dir = self._normalize_cwd(temp_dir) |
| 406 | self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir)) |
| 407 | |
Sayan Chowdhury | d5c11f7 | 2017-02-26 22:36:10 +0530 | [diff] [blame] | 408 | def test_cwd_with_pathlike(self): |
| 409 | temp_dir = tempfile.gettempdir() |
| 410 | temp_dir = self._normalize_cwd(temp_dir) |
Serhiy Storchaka | b21d155 | 2018-03-02 11:53:51 +0200 | [diff] [blame] | 411 | self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir)) |
Sayan Chowdhury | d5c11f7 | 2017-02-26 22:36:10 +0530 | [diff] [blame] | 412 | |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 413 | @unittest.skipIf(mswindows, "pending resolution of issue #15533") |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 414 | def test_cwd_with_relative_arg(self): |
| 415 | # Check that Popen looks for args[0] relative to cwd if args[0] |
| 416 | # is relative. |
| 417 | python_dir, python_base = self._split_python_path() |
| 418 | rel_python = os.path.join(os.curdir, python_base) |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 419 | with os_helper.temp_cwd() as wrong_dir: |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 420 | # Before calling with the correct cwd, confirm that the call fails |
| 421 | # without cwd and with the wrong cwd. |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 422 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 423 | [rel_python]) |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 424 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 425 | [rel_python], cwd=wrong_dir) |
| 426 | python_dir = self._normalize_cwd(python_dir) |
| 427 | self._assert_cwd(python_dir, rel_python, cwd=python_dir) |
| 428 | |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 429 | @unittest.skipIf(mswindows, "pending resolution of issue #15533") |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 430 | def test_cwd_with_relative_executable(self): |
| 431 | # Check that Popen looks for executable relative to cwd if executable |
| 432 | # is relative (and that executable takes precedence over args[0]). |
| 433 | python_dir, python_base = self._split_python_path() |
| 434 | rel_python = os.path.join(os.curdir, python_base) |
| 435 | doesntexist = "somethingyoudonthave" |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 436 | with os_helper.temp_cwd() as wrong_dir: |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 437 | # Before calling with the correct cwd, confirm that the call fails |
| 438 | # without cwd and with the wrong cwd. |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 439 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 440 | [doesntexist], executable=rel_python) |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 441 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 442 | [doesntexist], executable=rel_python, |
| 443 | cwd=wrong_dir) |
| 444 | python_dir = self._normalize_cwd(python_dir) |
| 445 | self._assert_cwd(python_dir, doesntexist, executable=rel_python, |
| 446 | cwd=python_dir) |
| 447 | |
| 448 | def test_cwd_with_absolute_arg(self): |
| 449 | # Check that Popen can find the executable when the cwd is wrong |
| 450 | # if args[0] is an absolute path. |
| 451 | python_dir, python_base = self._split_python_path() |
| 452 | abs_python = os.path.join(python_dir, python_base) |
| 453 | rel_python = os.path.join(os.curdir, python_base) |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 454 | with os_helper.temp_dir() as wrong_dir: |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 455 | # Before calling with an absolute path, confirm that using a |
| 456 | # relative path fails. |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 457 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 458 | [rel_python], cwd=wrong_dir) |
| 459 | wrong_dir = self._normalize_cwd(wrong_dir) |
| 460 | self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir) |
| 461 | |
Vinay Sajip | 7ded1f0 | 2012-05-26 03:45:29 +0100 | [diff] [blame] | 462 | @unittest.skipIf(sys.base_prefix != sys.prefix, |
| 463 | 'Test is not venv-compatible') |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 464 | def test_executable_with_cwd(self): |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 465 | python_dir, python_base = self._split_python_path() |
| 466 | python_dir = self._normalize_cwd(python_dir) |
| 467 | self._assert_cwd(python_dir, "somethingyoudonthave", |
| 468 | executable=sys.executable, cwd=python_dir) |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 469 | |
Vinay Sajip | 7ded1f0 | 2012-05-26 03:45:29 +0100 | [diff] [blame] | 470 | @unittest.skipIf(sys.base_prefix != sys.prefix, |
| 471 | 'Test is not venv-compatible') |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 472 | @unittest.skipIf(sysconfig.is_python_build(), |
| 473 | "need an installed Python. See #7774") |
| 474 | def test_executable_without_cwd(self): |
| 475 | # For a normal installation, it should work without 'cwd' |
| 476 | # argument. For test runs in the build directory, see #7774. |
Ned Deily | e92dfbf | 2013-08-02 18:02:21 -0700 | [diff] [blame] | 477 | self._assert_cwd(os.getcwd(), "somethingyoudonthave", |
| 478 | executable=sys.executable) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 479 | |
| 480 | def test_stdin_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 481 | # stdin redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 482 | p = subprocess.Popen([sys.executable, "-c", |
| 483 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 484 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 485 | p.stdin.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 486 | p.stdin.close() |
| 487 | p.wait() |
| 488 | self.assertEqual(p.returncode, 1) |
| 489 | |
| 490 | def test_stdin_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 491 | # stdin is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 492 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 493 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 494 | d = tf.fileno() |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 495 | os.write(d, b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 496 | os.lseek(d, 0, 0) |
| 497 | p = subprocess.Popen([sys.executable, "-c", |
| 498 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 499 | stdin=d) |
| 500 | p.wait() |
| 501 | self.assertEqual(p.returncode, 1) |
| 502 | |
| 503 | def test_stdin_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 504 | # stdin is set to open file object |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 505 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 506 | self.addCleanup(tf.close) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 507 | tf.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 508 | tf.seek(0) |
| 509 | p = subprocess.Popen([sys.executable, "-c", |
| 510 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 511 | stdin=tf) |
| 512 | p.wait() |
| 513 | self.assertEqual(p.returncode, 1) |
| 514 | |
| 515 | def test_stdout_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 516 | # stdout redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 517 | p = subprocess.Popen([sys.executable, "-c", |
| 518 | 'import sys; sys.stdout.write("orange")'], |
| 519 | stdout=subprocess.PIPE) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 520 | with p: |
| 521 | self.assertEqual(p.stdout.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 522 | |
| 523 | def test_stdout_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 524 | # stdout is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 525 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 526 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 527 | d = tf.fileno() |
| 528 | p = subprocess.Popen([sys.executable, "-c", |
| 529 | 'import sys; sys.stdout.write("orange")'], |
| 530 | stdout=d) |
| 531 | p.wait() |
| 532 | os.lseek(d, 0, 0) |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 533 | self.assertEqual(os.read(d, 1024), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 534 | |
| 535 | def test_stdout_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 536 | # stdout is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 537 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 538 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 539 | p = subprocess.Popen([sys.executable, "-c", |
| 540 | 'import sys; sys.stdout.write("orange")'], |
| 541 | stdout=tf) |
| 542 | p.wait() |
| 543 | tf.seek(0) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 544 | self.assertEqual(tf.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 545 | |
| 546 | def test_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 547 | # stderr redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 548 | p = subprocess.Popen([sys.executable, "-c", |
| 549 | 'import sys; sys.stderr.write("strawberry")'], |
| 550 | stderr=subprocess.PIPE) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 551 | with p: |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 552 | self.assertEqual(p.stderr.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 553 | |
| 554 | def test_stderr_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 555 | # stderr is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 556 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 557 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 558 | d = tf.fileno() |
| 559 | p = subprocess.Popen([sys.executable, "-c", |
| 560 | 'import sys; sys.stderr.write("strawberry")'], |
| 561 | stderr=d) |
| 562 | p.wait() |
| 563 | os.lseek(d, 0, 0) |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 564 | self.assertEqual(os.read(d, 1024), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 565 | |
| 566 | def test_stderr_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 567 | # stderr is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 568 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 569 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 570 | p = subprocess.Popen([sys.executable, "-c", |
| 571 | 'import sys; sys.stderr.write("strawberry")'], |
| 572 | stderr=tf) |
| 573 | p.wait() |
| 574 | tf.seek(0) |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 575 | self.assertEqual(tf.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 576 | |
Martin Panter | c763589 | 2016-05-13 01:54:44 +0000 | [diff] [blame] | 577 | def test_stderr_redirect_with_no_stdout_redirect(self): |
| 578 | # test stderr=STDOUT while stdout=None (not set) |
| 579 | |
| 580 | # - grandchild prints to stderr |
| 581 | # - child redirects grandchild's stderr to its stdout |
| 582 | # - the parent should get grandchild's stderr in child's stdout |
| 583 | p = subprocess.Popen([sys.executable, "-c", |
| 584 | 'import sys, subprocess;' |
| 585 | 'rc = subprocess.call([sys.executable, "-c",' |
| 586 | ' "import sys;"' |
| 587 | ' "sys.stderr.write(\'42\')"],' |
| 588 | ' stderr=subprocess.STDOUT);' |
| 589 | 'sys.exit(rc)'], |
| 590 | stdout=subprocess.PIPE, |
| 591 | stderr=subprocess.PIPE) |
| 592 | stdout, stderr = p.communicate() |
| 593 | #NOTE: stdout should get stderr from grandchild |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 594 | self.assertEqual(stdout, b'42') |
| 595 | self.assertEqual(stderr, b'') # should be empty |
Martin Panter | c763589 | 2016-05-13 01:54:44 +0000 | [diff] [blame] | 596 | self.assertEqual(p.returncode, 0) |
| 597 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 598 | def test_stdout_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 599 | # capture stdout and stderr to the same pipe |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 600 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 601 | 'import sys;' |
| 602 | 'sys.stdout.write("apple");' |
| 603 | 'sys.stdout.flush();' |
| 604 | 'sys.stderr.write("orange")'], |
| 605 | stdout=subprocess.PIPE, |
| 606 | stderr=subprocess.STDOUT) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 607 | with p: |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 608 | self.assertEqual(p.stdout.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 609 | |
| 610 | def test_stdout_stderr_file(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 611 | # capture stdout and stderr to the same open file |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 612 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 613 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 614 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 615 | 'import sys;' |
| 616 | 'sys.stdout.write("apple");' |
| 617 | 'sys.stdout.flush();' |
| 618 | 'sys.stderr.write("orange")'], |
| 619 | stdout=tf, |
| 620 | stderr=tf) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 621 | p.wait() |
| 622 | tf.seek(0) |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 623 | self.assertEqual(tf.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 624 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 625 | def test_stdout_filedes_of_stdout(self): |
| 626 | # stdout is set to 1 (#1531862). |
Ezio Melotti | 42a541b | 2013-03-11 05:53:34 +0200 | [diff] [blame] | 627 | # To avoid printing the text on stdout, we do something similar to |
| 628 | # test_stdout_none (see above). The parent subprocess calls the child |
| 629 | # subprocess passing stdout=1, and this test uses stdout=PIPE in |
| 630 | # order to capture and check the output of the parent. See #11963. |
| 631 | code = ('import sys, subprocess; ' |
| 632 | 'rc = subprocess.call([sys.executable, "-c", ' |
| 633 | ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), ' |
| 634 | 'b\'test with stdout=1\'))"], stdout=1); ' |
| 635 | 'assert rc == 18') |
| 636 | p = subprocess.Popen([sys.executable, "-c", code], |
| 637 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 638 | self.addCleanup(p.stdout.close) |
| 639 | self.addCleanup(p.stderr.close) |
| 640 | out, err = p.communicate() |
| 641 | self.assertEqual(p.returncode, 0, err) |
| 642 | self.assertEqual(out.rstrip(), b'test with stdout=1') |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 643 | |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 644 | def test_stdout_devnull(self): |
| 645 | p = subprocess.Popen([sys.executable, "-c", |
| 646 | 'for i in range(10240):' |
| 647 | 'print("x" * 1024)'], |
| 648 | stdout=subprocess.DEVNULL) |
| 649 | p.wait() |
| 650 | self.assertEqual(p.stdout, None) |
| 651 | |
| 652 | def test_stderr_devnull(self): |
| 653 | p = subprocess.Popen([sys.executable, "-c", |
| 654 | 'import sys\n' |
| 655 | 'for i in range(10240):' |
| 656 | 'sys.stderr.write("x" * 1024)'], |
| 657 | stderr=subprocess.DEVNULL) |
| 658 | p.wait() |
| 659 | self.assertEqual(p.stderr, None) |
| 660 | |
| 661 | def test_stdin_devnull(self): |
| 662 | p = subprocess.Popen([sys.executable, "-c", |
| 663 | 'import sys;' |
| 664 | 'sys.stdin.read(1)'], |
| 665 | stdin=subprocess.DEVNULL) |
| 666 | p.wait() |
| 667 | self.assertEqual(p.stdin, None) |
| 668 | |
Gregory P. Smith | 786addd | 2020-10-20 17:37:20 -0700 | [diff] [blame] | 669 | @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'), |
| 670 | 'fcntl.F_GETPIPE_SZ required for test.') |
Ruben Vorderman | 23c0fb8 | 2020-10-20 01:30:02 +0200 | [diff] [blame] | 671 | def test_pipesizes(self): |
Gregory P. Smith | 786addd | 2020-10-20 17:37:20 -0700 | [diff] [blame] | 672 | test_pipe_r, test_pipe_w = os.pipe() |
| 673 | try: |
| 674 | # Get the default pipesize with F_GETPIPE_SZ |
| 675 | pipesize_default = fcntl.fcntl(test_pipe_w, fcntl.F_GETPIPE_SZ) |
| 676 | finally: |
| 677 | os.close(test_pipe_r) |
| 678 | os.close(test_pipe_w) |
| 679 | pipesize = pipesize_default // 2 |
| 680 | if pipesize < 512: # the POSIX minimum |
| 681 | raise unittest.SkitTest( |
| 682 | 'default pipesize too small to perform test.') |
| 683 | p = subprocess.Popen( |
| 684 | [sys.executable, "-c", |
| 685 | 'import sys; sys.stdin.read(); sys.stdout.write("out"); ' |
| 686 | 'sys.stderr.write("error!")'], |
| 687 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 688 | stderr=subprocess.PIPE, pipesize=pipesize) |
| 689 | try: |
Ruben Vorderman | 23c0fb8 | 2020-10-20 01:30:02 +0200 | [diff] [blame] | 690 | for fifo in [p.stdin, p.stdout, p.stderr]: |
| 691 | self.assertEqual( |
Gregory P. Smith | 786addd | 2020-10-20 17:37:20 -0700 | [diff] [blame] | 692 | fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ), |
| 693 | pipesize) |
| 694 | # Windows pipe size can be acquired via GetNamedPipeInfoFunction |
| 695 | # https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-getnamedpipeinfo |
| 696 | # However, this function is not yet in _winapi. |
| 697 | p.stdin.write(b"pear") |
| 698 | p.stdin.close() |
| 699 | finally: |
| 700 | p.kill() |
| 701 | p.wait() |
| 702 | |
| 703 | @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'), |
| 704 | 'fcntl.F_GETPIPE_SZ required for test.') |
| 705 | def test_pipesize_default(self): |
| 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=-1) |
| 712 | try: |
| 713 | fp_r, fp_w = os.pipe() |
| 714 | try: |
| 715 | default_pipesize = fcntl.fcntl(fp_w, fcntl.F_GETPIPE_SZ) |
| 716 | for fifo in [p.stdin, p.stdout, p.stderr]: |
| 717 | self.assertEqual( |
| 718 | fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ), |
| 719 | default_pipesize) |
| 720 | finally: |
| 721 | os.close(fp_r) |
| 722 | os.close(fp_w) |
| 723 | # On other platforms we cannot test the pipe size (yet). But above |
| 724 | # code using pipesize=-1 should not crash. |
| 725 | p.stdin.close() |
| 726 | finally: |
| 727 | p.kill() |
| 728 | p.wait() |
Ruben Vorderman | 23c0fb8 | 2020-10-20 01:30:02 +0200 | [diff] [blame] | 729 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 730 | def test_env(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 731 | newenv = os.environ.copy() |
| 732 | newenv["FRUIT"] = "orange" |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 733 | with subprocess.Popen([sys.executable, "-c", |
| 734 | 'import sys,os;' |
| 735 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 736 | stdout=subprocess.PIPE, |
| 737 | env=newenv) as p: |
| 738 | stdout, stderr = p.communicate() |
| 739 | self.assertEqual(stdout, b"orange") |
| 740 | |
Victor Stinner | 62d5118 | 2011-06-23 01:02:25 +0200 | [diff] [blame] | 741 | # Windows requires at least the SYSTEMROOT environment variable to start |
| 742 | # Python |
| 743 | @unittest.skipIf(sys.platform == 'win32', |
| 744 | 'cannot test an empty env on Windows') |
Gregory P. Smith | b351248 | 2017-05-30 14:40:37 -0700 | [diff] [blame] | 745 | @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1, |
| 746 | 'The Python shared library cannot be loaded ' |
| 747 | 'with an empty environment.') |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 748 | def test_empty_env(self): |
Gregory P. Smith | b351248 | 2017-05-30 14:40:37 -0700 | [diff] [blame] | 749 | """Verify that env={} is as empty as possible.""" |
| 750 | |
Gregory P. Smith | 85aba23 | 2017-05-30 16:21:47 -0700 | [diff] [blame] | 751 | def is_env_var_to_ignore(n): |
Gregory P. Smith | b351248 | 2017-05-30 14:40:37 -0700 | [diff] [blame] | 752 | """Determine if an environment variable is under our control.""" |
| 753 | # This excludes some __CF_* and VERSIONER_* keys MacOS insists |
| 754 | # on adding even when the environment in exec is empty. |
| 755 | # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist. |
Gregory P. Smith | 85aba23 | 2017-05-30 16:21:47 -0700 | [diff] [blame] | 756 | return ('VERSIONER' in n or '__CF' in n or # MacOS |
Nick Coghlan | 6ea4186 | 2017-06-11 13:16:15 +1000 | [diff] [blame] | 757 | n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo |
| 758 | n == 'LC_CTYPE') # Locale coercion triggered |
Gregory P. Smith | b351248 | 2017-05-30 14:40:37 -0700 | [diff] [blame] | 759 | |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 760 | with subprocess.Popen([sys.executable, "-c", |
Gregory P. Smith | b351248 | 2017-05-30 14:40:37 -0700 | [diff] [blame] | 761 | 'import os; print(list(os.environ.keys()))'], |
| 762 | stdout=subprocess.PIPE, env={}) as p: |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 763 | stdout, stderr = p.communicate() |
Gregory P. Smith | b351248 | 2017-05-30 14:40:37 -0700 | [diff] [blame] | 764 | child_env_names = eval(stdout.strip()) |
| 765 | self.assertIsInstance(child_env_names, list) |
| 766 | child_env_names = [k for k in child_env_names |
| 767 | if not is_env_var_to_ignore(k)] |
| 768 | self.assertEqual(child_env_names, []) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 769 | |
Serhiy Storchaka | d174d24 | 2017-06-23 19:39:27 +0300 | [diff] [blame] | 770 | def test_invalid_cmd(self): |
| 771 | # null character in the command name |
| 772 | cmd = sys.executable + '\0' |
| 773 | with self.assertRaises(ValueError): |
| 774 | subprocess.Popen([cmd, "-c", "pass"]) |
| 775 | |
| 776 | # null character in the command argument |
| 777 | with self.assertRaises(ValueError): |
| 778 | subprocess.Popen([sys.executable, "-c", "pass#\0"]) |
| 779 | |
| 780 | def test_invalid_env(self): |
Ville Skyttä | 49b2734 | 2017-08-03 09:00:59 +0300 | [diff] [blame] | 781 | # null character in the environment variable name |
Serhiy Storchaka | d174d24 | 2017-06-23 19:39:27 +0300 | [diff] [blame] | 782 | newenv = os.environ.copy() |
| 783 | newenv["FRUIT\0VEGETABLE"] = "cabbage" |
| 784 | with self.assertRaises(ValueError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 785 | subprocess.Popen(ZERO_RETURN_CMD, env=newenv) |
Serhiy Storchaka | d174d24 | 2017-06-23 19:39:27 +0300 | [diff] [blame] | 786 | |
Ville Skyttä | 49b2734 | 2017-08-03 09:00:59 +0300 | [diff] [blame] | 787 | # null character in the environment variable value |
Serhiy Storchaka | d174d24 | 2017-06-23 19:39:27 +0300 | [diff] [blame] | 788 | newenv = os.environ.copy() |
| 789 | newenv["FRUIT"] = "orange\0VEGETABLE=cabbage" |
| 790 | with self.assertRaises(ValueError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 791 | subprocess.Popen(ZERO_RETURN_CMD, env=newenv) |
Serhiy Storchaka | d174d24 | 2017-06-23 19:39:27 +0300 | [diff] [blame] | 792 | |
Ville Skyttä | 49b2734 | 2017-08-03 09:00:59 +0300 | [diff] [blame] | 793 | # equal character in the environment variable name |
Serhiy Storchaka | d174d24 | 2017-06-23 19:39:27 +0300 | [diff] [blame] | 794 | newenv = os.environ.copy() |
| 795 | newenv["FRUIT=ORANGE"] = "lemon" |
| 796 | with self.assertRaises(ValueError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 797 | subprocess.Popen(ZERO_RETURN_CMD, env=newenv) |
Serhiy Storchaka | d174d24 | 2017-06-23 19:39:27 +0300 | [diff] [blame] | 798 | |
Ville Skyttä | 49b2734 | 2017-08-03 09:00:59 +0300 | [diff] [blame] | 799 | # equal character in the environment variable value |
Serhiy Storchaka | d174d24 | 2017-06-23 19:39:27 +0300 | [diff] [blame] | 800 | newenv = os.environ.copy() |
| 801 | newenv["FRUIT"] = "orange=lemon" |
| 802 | with subprocess.Popen([sys.executable, "-c", |
| 803 | 'import sys, os;' |
| 804 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 805 | stdout=subprocess.PIPE, |
| 806 | env=newenv) as p: |
| 807 | stdout, stderr = p.communicate() |
| 808 | self.assertEqual(stdout, b"orange=lemon") |
| 809 | |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 810 | def test_communicate_stdin(self): |
| 811 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 812 | 'import sys;' |
| 813 | 'sys.exit(sys.stdin.read() == "pear")'], |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 814 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 815 | p.communicate(b"pear") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 816 | self.assertEqual(p.returncode, 1) |
| 817 | |
| 818 | def test_communicate_stdout(self): |
| 819 | p = subprocess.Popen([sys.executable, "-c", |
| 820 | 'import sys; sys.stdout.write("pineapple")'], |
| 821 | stdout=subprocess.PIPE) |
| 822 | (stdout, stderr) = p.communicate() |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 823 | self.assertEqual(stdout, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 824 | self.assertEqual(stderr, None) |
| 825 | |
| 826 | def test_communicate_stderr(self): |
| 827 | p = subprocess.Popen([sys.executable, "-c", |
| 828 | 'import sys; sys.stderr.write("pineapple")'], |
| 829 | stderr=subprocess.PIPE) |
| 830 | (stdout, stderr) = p.communicate() |
| 831 | self.assertEqual(stdout, None) |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 832 | self.assertEqual(stderr, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 833 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 834 | def test_communicate(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 835 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 836 | 'import sys,os;' |
| 837 | 'sys.stderr.write("pineapple");' |
| 838 | 'sys.stdout.write(sys.stdin.read())'], |
| 839 | stdin=subprocess.PIPE, |
| 840 | stdout=subprocess.PIPE, |
| 841 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 842 | self.addCleanup(p.stdout.close) |
| 843 | self.addCleanup(p.stderr.close) |
| 844 | self.addCleanup(p.stdin.close) |
Georg Brandl | 1abcbf8 | 2008-07-01 19:28:43 +0000 | [diff] [blame] | 845 | (stdout, stderr) = p.communicate(b"banana") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 846 | self.assertEqual(stdout, b"banana") |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 847 | self.assertEqual(stderr, b"pineapple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 848 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 849 | def test_communicate_timeout(self): |
| 850 | p = subprocess.Popen([sys.executable, "-c", |
| 851 | 'import sys,os,time;' |
| 852 | 'sys.stderr.write("pineapple\\n");' |
| 853 | 'time.sleep(1);' |
| 854 | 'sys.stderr.write("pear\\n");' |
| 855 | 'sys.stdout.write(sys.stdin.read())'], |
| 856 | universal_newlines=True, |
| 857 | stdin=subprocess.PIPE, |
| 858 | stdout=subprocess.PIPE, |
| 859 | stderr=subprocess.PIPE) |
| 860 | self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana", |
| 861 | timeout=0.3) |
| 862 | # Make sure we can keep waiting for it, and that we get the whole output |
| 863 | # after it completes. |
| 864 | (stdout, stderr) = p.communicate() |
| 865 | self.assertEqual(stdout, "banana") |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 866 | self.assertEqual(stderr.encode(), b"pineapple\npear\n") |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 867 | |
Raymond Hettinger | 15f44ab | 2016-08-30 10:47:49 -0700 | [diff] [blame] | 868 | def test_communicate_timeout_large_output(self): |
Ross Lagerwall | 003c7a3 | 2012-02-12 09:02:01 +0200 | [diff] [blame] | 869 | # Test an expiring timeout while the child is outputting lots of data. |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 870 | p = subprocess.Popen([sys.executable, "-c", |
| 871 | 'import sys,os,time;' |
| 872 | 'sys.stdout.write("a" * (64 * 1024));' |
| 873 | 'time.sleep(0.2);' |
| 874 | 'sys.stdout.write("a" * (64 * 1024));' |
| 875 | 'time.sleep(0.2);' |
| 876 | 'sys.stdout.write("a" * (64 * 1024));' |
| 877 | 'time.sleep(0.2);' |
| 878 | 'sys.stdout.write("a" * (64 * 1024));'], |
| 879 | stdout=subprocess.PIPE) |
| 880 | self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4) |
| 881 | (stdout, _) = p.communicate() |
| 882 | self.assertEqual(len(stdout), 4 * 64 * 1024) |
| 883 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 884 | # Test for the fd leak reported in http://bugs.python.org/issue2791. |
| 885 | def test_communicate_pipe_fd_leak(self): |
Victor Stinner | 667d4b5 | 2010-12-25 22:40:32 +0000 | [diff] [blame] | 886 | for stdin_pipe in (False, True): |
| 887 | for stdout_pipe in (False, True): |
| 888 | for stderr_pipe in (False, True): |
| 889 | options = {} |
| 890 | if stdin_pipe: |
| 891 | options['stdin'] = subprocess.PIPE |
| 892 | if stdout_pipe: |
| 893 | options['stdout'] = subprocess.PIPE |
| 894 | if stderr_pipe: |
| 895 | options['stderr'] = subprocess.PIPE |
| 896 | if not options: |
| 897 | continue |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 898 | p = subprocess.Popen(ZERO_RETURN_CMD, **options) |
Victor Stinner | 667d4b5 | 2010-12-25 22:40:32 +0000 | [diff] [blame] | 899 | p.communicate() |
| 900 | if p.stdin is not None: |
| 901 | self.assertTrue(p.stdin.closed) |
| 902 | if p.stdout is not None: |
| 903 | self.assertTrue(p.stdout.closed) |
| 904 | if p.stderr is not None: |
| 905 | self.assertTrue(p.stderr.closed) |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 906 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 907 | def test_communicate_returns(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 908 | # communicate() should return None if no redirection is active |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 909 | p = subprocess.Popen([sys.executable, "-c", |
| 910 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 911 | (stdout, stderr) = p.communicate() |
| 912 | self.assertEqual(stdout, None) |
| 913 | self.assertEqual(stderr, None) |
| 914 | |
| 915 | def test_communicate_pipe_buf(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 916 | # communicate() with writes larger than pipe_buf |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 917 | # This test will probably deadlock rather than fail, if |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 918 | # communicate() does not work properly. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 919 | x, y = os.pipe() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 920 | os.close(x) |
| 921 | os.close(y) |
| 922 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 923 | 'import sys,os;' |
| 924 | 'sys.stdout.write(sys.stdin.read(47));' |
Charles-François Natali | 2d51721 | 2011-05-29 16:36:44 +0200 | [diff] [blame] | 925 | 'sys.stderr.write("x" * %d);' |
| 926 | 'sys.stdout.write(sys.stdin.read())' % |
| 927 | support.PIPE_MAX_SIZE], |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 928 | stdin=subprocess.PIPE, |
| 929 | stdout=subprocess.PIPE, |
| 930 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 931 | self.addCleanup(p.stdout.close) |
| 932 | self.addCleanup(p.stderr.close) |
| 933 | self.addCleanup(p.stdin.close) |
Charles-François Natali | 2d51721 | 2011-05-29 16:36:44 +0200 | [diff] [blame] | 934 | string_to_write = b"a" * support.PIPE_MAX_SIZE |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 935 | (stdout, stderr) = p.communicate(string_to_write) |
| 936 | self.assertEqual(stdout, string_to_write) |
| 937 | |
| 938 | def test_writes_before_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 939 | # stdin.write before communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 940 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 941 | 'import sys,os;' |
| 942 | 'sys.stdout.write(sys.stdin.read())'], |
| 943 | stdin=subprocess.PIPE, |
| 944 | stdout=subprocess.PIPE, |
| 945 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 946 | self.addCleanup(p.stdout.close) |
| 947 | self.addCleanup(p.stderr.close) |
| 948 | self.addCleanup(p.stdin.close) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 949 | p.stdin.write(b"banana") |
| 950 | (stdout, stderr) = p.communicate(b"split") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 951 | self.assertEqual(stdout, b"bananasplit") |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 952 | self.assertEqual(stderr, b"") |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 953 | |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 954 | def test_universal_newlines_and_text(self): |
| 955 | args = [ |
| 956 | sys.executable, "-c", |
| 957 | 'import sys,os;' + SETBINARY + |
| 958 | 'buf = sys.stdout.buffer;' |
| 959 | 'buf.write(sys.stdin.readline().encode());' |
| 960 | 'buf.flush();' |
| 961 | 'buf.write(b"line2\\n");' |
| 962 | 'buf.flush();' |
| 963 | 'buf.write(sys.stdin.read().encode());' |
| 964 | 'buf.flush();' |
| 965 | 'buf.write(b"line4\\n");' |
| 966 | 'buf.flush();' |
| 967 | 'buf.write(b"line5\\r\\n");' |
| 968 | 'buf.flush();' |
| 969 | 'buf.write(b"line6\\r");' |
| 970 | 'buf.flush();' |
| 971 | 'buf.write(b"\\nline7");' |
| 972 | 'buf.flush();' |
| 973 | 'buf.write(b"\\nline8");'] |
| 974 | |
| 975 | for extra_kwarg in ('universal_newlines', 'text'): |
| 976 | p = subprocess.Popen(args, **{'stdin': subprocess.PIPE, |
| 977 | 'stdout': subprocess.PIPE, |
| 978 | extra_kwarg: True}) |
| 979 | with p: |
| 980 | p.stdin.write("line1\n") |
| 981 | p.stdin.flush() |
| 982 | self.assertEqual(p.stdout.readline(), "line1\n") |
| 983 | p.stdin.write("line3\n") |
| 984 | p.stdin.close() |
| 985 | self.addCleanup(p.stdout.close) |
| 986 | self.assertEqual(p.stdout.readline(), |
| 987 | "line2\n") |
| 988 | self.assertEqual(p.stdout.read(6), |
| 989 | "line3\n") |
| 990 | self.assertEqual(p.stdout.read(), |
| 991 | "line4\nline5\nline6\nline7\nline8") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 992 | |
| 993 | def test_universal_newlines_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 994 | # universal newlines through communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 995 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 996 | 'import sys,os;' + SETBINARY + |
Antoine Pitrou | ec2d269 | 2012-08-05 00:23:40 +0200 | [diff] [blame] | 997 | 'buf = sys.stdout.buffer;' |
| 998 | 'buf.write(b"line2\\n");' |
| 999 | 'buf.flush();' |
| 1000 | 'buf.write(b"line4\\n");' |
| 1001 | 'buf.flush();' |
| 1002 | 'buf.write(b"line5\\r\\n");' |
| 1003 | 'buf.flush();' |
| 1004 | 'buf.write(b"line6\\r");' |
| 1005 | 'buf.flush();' |
| 1006 | 'buf.write(b"\\nline7");' |
| 1007 | 'buf.flush();' |
| 1008 | 'buf.write(b"\\nline8");'], |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 1009 | stderr=subprocess.PIPE, |
| 1010 | stdout=subprocess.PIPE, |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1011 | universal_newlines=1) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 1012 | self.addCleanup(p.stdout.close) |
| 1013 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1014 | (stdout, stderr) = p.communicate() |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 1015 | self.assertEqual(stdout, |
| 1016 | "line2\nline4\nline5\nline6\nline7\nline8") |
| 1017 | |
| 1018 | def test_universal_newlines_communicate_stdin(self): |
| 1019 | # universal newlines through communicate(), with only stdin |
| 1020 | p = subprocess.Popen([sys.executable, "-c", |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 1021 | 'import sys,os;' + SETBINARY + textwrap.dedent(''' |
| 1022 | s = sys.stdin.readline() |
| 1023 | assert s == "line1\\n", repr(s) |
| 1024 | s = sys.stdin.read() |
| 1025 | assert s == "line3\\n", repr(s) |
| 1026 | ''')], |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 1027 | stdin=subprocess.PIPE, |
| 1028 | universal_newlines=1) |
| 1029 | (stdout, stderr) = p.communicate("line1\nline3\n") |
| 1030 | self.assertEqual(p.returncode, 0) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1031 | |
Andrew Svetlov | f376507 | 2012-08-14 18:35:17 +0300 | [diff] [blame] | 1032 | def test_universal_newlines_communicate_input_none(self): |
| 1033 | # Test communicate(input=None) with universal newlines. |
| 1034 | # |
| 1035 | # We set stdout to PIPE because, as of this writing, a different |
| 1036 | # code path is tested when the number of pipes is zero or one. |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1037 | p = subprocess.Popen(ZERO_RETURN_CMD, |
Andrew Svetlov | f376507 | 2012-08-14 18:35:17 +0300 | [diff] [blame] | 1038 | stdin=subprocess.PIPE, |
| 1039 | stdout=subprocess.PIPE, |
| 1040 | universal_newlines=True) |
| 1041 | p.communicate() |
| 1042 | self.assertEqual(p.returncode, 0) |
| 1043 | |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 1044 | def test_universal_newlines_communicate_stdin_stdout_stderr(self): |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 1045 | # universal newlines through communicate(), with stdin, stdout, stderr |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 1046 | p = subprocess.Popen([sys.executable, "-c", |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 1047 | 'import sys,os;' + SETBINARY + textwrap.dedent(''' |
| 1048 | s = sys.stdin.buffer.readline() |
| 1049 | sys.stdout.buffer.write(s) |
| 1050 | sys.stdout.buffer.write(b"line2\\r") |
| 1051 | sys.stderr.buffer.write(b"eline2\\n") |
| 1052 | s = sys.stdin.buffer.read() |
| 1053 | sys.stdout.buffer.write(s) |
| 1054 | sys.stdout.buffer.write(b"line4\\n") |
| 1055 | sys.stdout.buffer.write(b"line5\\r\\n") |
| 1056 | sys.stderr.buffer.write(b"eline6\\r") |
| 1057 | sys.stderr.buffer.write(b"eline7\\r\\nz") |
| 1058 | ''')], |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 1059 | stdin=subprocess.PIPE, |
| 1060 | stderr=subprocess.PIPE, |
| 1061 | stdout=subprocess.PIPE, |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 1062 | universal_newlines=True) |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 1063 | self.addCleanup(p.stdout.close) |
| 1064 | self.addCleanup(p.stderr.close) |
| 1065 | (stdout, stderr) = p.communicate("line1\nline3\n") |
| 1066 | self.assertEqual(p.returncode, 0) |
Andrew Svetlov | 943c5b3 | 2012-08-16 20:17:47 +0300 | [diff] [blame] | 1067 | self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout) |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 1068 | # Python debug build push something like "[42442 refs]\n" |
| 1069 | # to stderr at exit of subprocess. |
Andrew Svetlov | 943c5b3 | 2012-08-16 20:17:47 +0300 | [diff] [blame] | 1070 | self.assertTrue(stderr.startswith("eline2\neline6\neline7\n")) |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 1071 | |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 1072 | def test_universal_newlines_communicate_encodings(self): |
| 1073 | # Check that universal newlines mode works for various encodings, |
| 1074 | # in particular for encodings in the UTF-16 and UTF-32 families. |
| 1075 | # See issue #15595. |
| 1076 | # |
| 1077 | # UTF-16 and UTF-32-BE are sufficient to check both with BOM and |
| 1078 | # without, and UTF-16 and UTF-32. |
| 1079 | for encoding in ['utf-16', 'utf-32-be']: |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 1080 | code = ("import sys; " |
| 1081 | r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" % |
| 1082 | encoding) |
| 1083 | args = [sys.executable, '-c', code] |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 1084 | # We set stdin to be non-None because, as of this writing, |
| 1085 | # a different code path is used when the number of pipes is |
| 1086 | # zero or one. |
| 1087 | popen = subprocess.Popen(args, |
| 1088 | stdin=subprocess.PIPE, |
| 1089 | stdout=subprocess.PIPE, |
| 1090 | encoding=encoding) |
| 1091 | stdout, stderr = popen.communicate(input='') |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 1092 | self.assertEqual(stdout, '1\n2\n3\n4') |
| 1093 | |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 1094 | def test_communicate_errors(self): |
| 1095 | for errors, expected in [ |
| 1096 | ('ignore', ''), |
| 1097 | ('replace', '\ufffd\ufffd'), |
| 1098 | ('surrogateescape', '\udc80\udc80'), |
| 1099 | ('backslashreplace', '\\x80\\x80'), |
| 1100 | ]: |
| 1101 | code = ("import sys; " |
| 1102 | r"sys.stdout.buffer.write(b'[\x80\x80]')") |
| 1103 | args = [sys.executable, '-c', code] |
| 1104 | # We set stdin to be non-None because, as of this writing, |
| 1105 | # a different code path is used when the number of pipes is |
| 1106 | # zero or one. |
| 1107 | popen = subprocess.Popen(args, |
| 1108 | stdin=subprocess.PIPE, |
| 1109 | stdout=subprocess.PIPE, |
| 1110 | encoding='utf-8', |
| 1111 | errors=errors) |
| 1112 | stdout, stderr = popen.communicate(input='') |
| 1113 | self.assertEqual(stdout, '[{}]'.format(expected)) |
| 1114 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1115 | def test_no_leaking(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 1116 | # Make sure we leak no resources |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 1117 | if not mswindows: |
Peter Astrand | f7f1bb7 | 2005-03-03 20:47:37 +0000 | [diff] [blame] | 1118 | max_handles = 1026 # too much for most UNIX systems |
| 1119 | else: |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 1120 | max_handles = 2050 # too much for (at least some) Windows setups |
| 1121 | handles = [] |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 1122 | tmpdir = tempfile.mkdtemp() |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 1123 | try: |
| 1124 | for i in range(max_handles): |
| 1125 | try: |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 1126 | tmpfile = os.path.join(tmpdir, os_helper.TESTFN) |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 1127 | handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT)) |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 1128 | except OSError as e: |
| 1129 | if e.errno != errno.EMFILE: |
| 1130 | raise |
| 1131 | break |
| 1132 | else: |
| 1133 | self.skipTest("failed to reach the file descriptor limit " |
| 1134 | "(tried %d)" % max_handles) |
| 1135 | # Close a couple of them (should be enough for a subprocess) |
| 1136 | for i in range(10): |
| 1137 | os.close(handles.pop()) |
| 1138 | # Loop creating some subprocesses. If one of them leaks some fds, |
| 1139 | # the next loop iteration will fail by reaching the max fd limit. |
| 1140 | for i in range(15): |
| 1141 | p = subprocess.Popen([sys.executable, "-c", |
| 1142 | "import sys;" |
| 1143 | "sys.stdout.write(sys.stdin.read())"], |
| 1144 | stdin=subprocess.PIPE, |
| 1145 | stdout=subprocess.PIPE, |
| 1146 | stderr=subprocess.PIPE) |
| 1147 | data = p.communicate(b"lime")[0] |
| 1148 | self.assertEqual(data, b"lime") |
| 1149 | finally: |
| 1150 | for h in handles: |
| 1151 | os.close(h) |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 1152 | shutil.rmtree(tmpdir) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1153 | |
| 1154 | def test_list2cmdline(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1155 | self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']), |
| 1156 | '"a b c" d e') |
| 1157 | self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']), |
| 1158 | 'ab\\"c \\ d') |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 1159 | self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']), |
| 1160 | 'ab\\"c " \\\\" d') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1161 | self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']), |
| 1162 | 'a\\\\\\b "de fg" h') |
| 1163 | self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']), |
| 1164 | 'a\\\\\\"b c d') |
| 1165 | self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']), |
| 1166 | '"a\\\\b c" d e') |
| 1167 | self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']), |
| 1168 | '"a\\\\b\\ c" d e') |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 1169 | self.assertEqual(subprocess.list2cmdline(['ab', '']), |
| 1170 | 'ab ""') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1171 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1172 | def test_poll(self): |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1173 | p = subprocess.Popen([sys.executable, "-c", |
Ross Lagerwall | e7ad419 | 2012-02-22 06:02:07 +0200 | [diff] [blame] | 1174 | "import os; os.read(0, 1)"], |
| 1175 | stdin=subprocess.PIPE) |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1176 | self.addCleanup(p.stdin.close) |
| 1177 | self.assertIsNone(p.poll()) |
| 1178 | os.write(p.stdin.fileno(), b'A') |
| 1179 | p.wait() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1180 | # Subsequent invocations should just return the returncode |
| 1181 | self.assertEqual(p.poll(), 0) |
| 1182 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1183 | def test_wait(self): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1184 | p = subprocess.Popen(ZERO_RETURN_CMD) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1185 | self.assertEqual(p.wait(), 0) |
| 1186 | # Subsequent invocations should just return the returncode |
| 1187 | self.assertEqual(p.wait(), 0) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1188 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1189 | def test_wait_timeout(self): |
| 1190 | p = subprocess.Popen([sys.executable, |
Antoine Pitrou | dc49b2b | 2013-05-19 15:55:40 +0200 | [diff] [blame] | 1191 | "-c", "import time; time.sleep(0.3)"]) |
Reid Kleckner | 2b228f0 | 2011-03-16 16:57:54 -0400 | [diff] [blame] | 1192 | with self.assertRaises(subprocess.TimeoutExpired) as c: |
Antoine Pitrou | dc49b2b | 2013-05-19 15:55:40 +0200 | [diff] [blame] | 1193 | p.wait(timeout=0.0001) |
| 1194 | self.assertIn("0.0001", str(c.exception)) # For coverage of __str__. |
Victor Stinner | 0d63bac | 2019-12-11 11:30:03 +0100 | [diff] [blame] | 1195 | self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1196 | |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 1197 | def test_invalid_bufsize(self): |
| 1198 | # an invalid type of the bufsize argument should raise |
| 1199 | # TypeError. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1200 | with self.assertRaises(TypeError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1201 | subprocess.Popen(ZERO_RETURN_CMD, "orange") |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 1202 | |
Guido van Rossum | 46a05a7 | 2007-06-07 21:56:45 +0000 | [diff] [blame] | 1203 | def test_bufsize_is_none(self): |
| 1204 | # bufsize=None should be the same as bufsize=0. |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1205 | p = subprocess.Popen(ZERO_RETURN_CMD, None) |
Guido van Rossum | 46a05a7 | 2007-06-07 21:56:45 +0000 | [diff] [blame] | 1206 | self.assertEqual(p.wait(), 0) |
| 1207 | # Again with keyword arg |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1208 | p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None) |
Guido van Rossum | 46a05a7 | 2007-06-07 21:56:45 +0000 | [diff] [blame] | 1209 | self.assertEqual(p.wait(), 0) |
| 1210 | |
Antoine Pitrou | afe8d06 | 2014-09-21 21:10:56 +0200 | [diff] [blame] | 1211 | def _test_bufsize_equal_one(self, line, expected, universal_newlines): |
| 1212 | # subprocess may deadlock with bufsize=1, see issue #21332 |
| 1213 | with subprocess.Popen([sys.executable, "-c", "import sys;" |
| 1214 | "sys.stdout.write(sys.stdin.readline());" |
| 1215 | "sys.stdout.flush()"], |
| 1216 | stdin=subprocess.PIPE, |
| 1217 | stdout=subprocess.PIPE, |
| 1218 | stderr=subprocess.DEVNULL, |
| 1219 | bufsize=1, |
| 1220 | universal_newlines=universal_newlines) as p: |
| 1221 | p.stdin.write(line) # expect that it flushes the line in text mode |
| 1222 | os.close(p.stdin.fileno()) # close it without flushing the buffer |
| 1223 | read_line = p.stdout.readline() |
Segev Finer | 4d38517 | 2017-08-18 16:18:13 +0300 | [diff] [blame] | 1224 | with support.SuppressCrashReport(): |
| 1225 | try: |
| 1226 | p.stdin.close() |
| 1227 | except OSError: |
| 1228 | pass |
Antoine Pitrou | afe8d06 | 2014-09-21 21:10:56 +0200 | [diff] [blame] | 1229 | p.stdin = None |
| 1230 | self.assertEqual(p.returncode, 0) |
| 1231 | self.assertEqual(read_line, expected) |
| 1232 | |
| 1233 | def test_bufsize_equal_one_text_mode(self): |
| 1234 | # line is flushed in text mode with bufsize=1. |
| 1235 | # we should get the full line in return |
| 1236 | line = "line\n" |
| 1237 | self._test_bufsize_equal_one(line, line, universal_newlines=True) |
| 1238 | |
| 1239 | def test_bufsize_equal_one_binary_mode(self): |
| 1240 | # line is not flushed in binary mode with bufsize=1. |
| 1241 | # we should get empty response |
| 1242 | line = b'line' + os.linesep.encode() # assume ascii-based locale |
Alexey Izbyshev | a267056 | 2018-10-20 03:22:31 +0300 | [diff] [blame] | 1243 | with self.assertWarnsRegex(RuntimeWarning, 'line buffering'): |
| 1244 | self._test_bufsize_equal_one(line, b'', universal_newlines=False) |
Antoine Pitrou | afe8d06 | 2014-09-21 21:10:56 +0200 | [diff] [blame] | 1245 | |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 1246 | def test_leaking_fds_on_error(self): |
| 1247 | # see bug #5179: Popen leaks file descriptors to PIPEs if |
| 1248 | # the child fails to execute; this will eventually exhaust |
| 1249 | # the maximum number of open fds. 1024 seems a very common |
| 1250 | # value for that limit, but Windows has 2048, so we loop |
| 1251 | # 1024 times (each call leaked two fds). |
| 1252 | for i in range(1024): |
Victor Stinner | b31206a | 2018-01-25 19:06:05 +0100 | [diff] [blame] | 1253 | with self.assertRaises(NONEXISTING_ERRORS): |
Victor Stinner | 9a83f65 | 2017-08-21 23:51:31 +0200 | [diff] [blame] | 1254 | subprocess.Popen(NONEXISTING_CMD, |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 1255 | stdout=subprocess.PIPE, |
| 1256 | stderr=subprocess.PIPE) |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 1257 | |
Victor Stinner | 9a83f65 | 2017-08-21 23:51:31 +0200 | [diff] [blame] | 1258 | def test_nonexisting_with_pipes(self): |
| 1259 | # bpo-30121: Popen with pipes must close properly pipes on error. |
| 1260 | # Previously, os.close() was called with a Windows handle which is not |
| 1261 | # a valid file descriptor. |
| 1262 | # |
| 1263 | # Run the test in a subprocess to control how the CRT reports errors |
| 1264 | # and to get stderr content. |
| 1265 | try: |
| 1266 | import msvcrt |
| 1267 | msvcrt.CrtSetReportMode |
| 1268 | except (AttributeError, ImportError): |
| 1269 | self.skipTest("need msvcrt.CrtSetReportMode") |
| 1270 | |
| 1271 | code = textwrap.dedent(f""" |
| 1272 | import msvcrt |
| 1273 | import subprocess |
| 1274 | |
| 1275 | cmd = {NONEXISTING_CMD!r} |
| 1276 | |
| 1277 | for report_type in [msvcrt.CRT_WARN, |
| 1278 | msvcrt.CRT_ERROR, |
| 1279 | msvcrt.CRT_ASSERT]: |
| 1280 | msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE) |
| 1281 | msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR) |
| 1282 | |
| 1283 | try: |
Zachary Ware | 5537646 | 2018-02-19 14:02:38 -0600 | [diff] [blame] | 1284 | subprocess.Popen(cmd, |
Victor Stinner | 9a83f65 | 2017-08-21 23:51:31 +0200 | [diff] [blame] | 1285 | stdout=subprocess.PIPE, |
| 1286 | stderr=subprocess.PIPE) |
| 1287 | except OSError: |
| 1288 | pass |
| 1289 | """) |
| 1290 | cmd = [sys.executable, "-c", code] |
| 1291 | proc = subprocess.Popen(cmd, |
| 1292 | stderr=subprocess.PIPE, |
| 1293 | universal_newlines=True) |
| 1294 | with proc: |
| 1295 | stderr = proc.communicate()[1] |
| 1296 | self.assertEqual(stderr, "") |
| 1297 | self.assertEqual(proc.returncode, 0) |
| 1298 | |
Antoine Pitrou | a839271 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 1299 | def test_double_close_on_error(self): |
| 1300 | # Issue #18851 |
| 1301 | fds = [] |
| 1302 | def open_fds(): |
| 1303 | for i in range(20): |
| 1304 | fds.extend(os.pipe()) |
| 1305 | time.sleep(0.001) |
| 1306 | t = threading.Thread(target=open_fds) |
| 1307 | t.start() |
| 1308 | try: |
| 1309 | with self.assertRaises(EnvironmentError): |
Victor Stinner | 9a83f65 | 2017-08-21 23:51:31 +0200 | [diff] [blame] | 1310 | subprocess.Popen(NONEXISTING_CMD, |
Antoine Pitrou | a839271 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 1311 | stdin=subprocess.PIPE, |
| 1312 | stdout=subprocess.PIPE, |
| 1313 | stderr=subprocess.PIPE) |
| 1314 | finally: |
| 1315 | t.join() |
| 1316 | exc = None |
| 1317 | for fd in fds: |
| 1318 | # If a double close occurred, some of those fds will |
| 1319 | # already have been closed by mistake, and os.close() |
| 1320 | # here will raise. |
| 1321 | try: |
| 1322 | os.close(fd) |
| 1323 | except OSError as e: |
| 1324 | exc = e |
| 1325 | if exc is not None: |
| 1326 | raise exc |
| 1327 | |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1328 | def test_threadsafe_wait(self): |
| 1329 | """Issue21291: Popen.wait() needs to be threadsafe for returncode.""" |
| 1330 | proc = subprocess.Popen([sys.executable, '-c', |
| 1331 | 'import time; time.sleep(12)']) |
| 1332 | self.assertEqual(proc.returncode, None) |
| 1333 | results = [] |
| 1334 | |
| 1335 | def kill_proc_timer_thread(): |
| 1336 | results.append(('thread-start-poll-result', proc.poll())) |
| 1337 | # terminate it from the thread and wait for the result. |
| 1338 | proc.kill() |
| 1339 | proc.wait() |
| 1340 | results.append(('thread-after-kill-and-wait', proc.returncode)) |
| 1341 | # this wait should be a no-op given the above. |
| 1342 | proc.wait() |
| 1343 | results.append(('thread-after-second-wait', proc.returncode)) |
| 1344 | |
| 1345 | # This is a timing sensitive test, the failure mode is |
| 1346 | # triggered when both the main thread and this thread are in |
| 1347 | # the wait() call at once. The delay here is to allow the |
| 1348 | # main thread to most likely be blocked in its wait() call. |
| 1349 | t = threading.Timer(0.2, kill_proc_timer_thread) |
| 1350 | t.start() |
| 1351 | |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 1352 | if mswindows: |
Gregory P. Smith | ab2719f | 2014-04-23 08:38:36 -0700 | [diff] [blame] | 1353 | expected_errorcode = 1 |
| 1354 | else: |
| 1355 | # Should be -9 because of the proc.kill() from the thread. |
| 1356 | expected_errorcode = -9 |
| 1357 | |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1358 | # Wait for the process to finish; the thread should kill it |
| 1359 | # long before it finishes on its own. Supplying a timeout |
| 1360 | # triggers a different code path for better coverage. |
Victor Stinner | 0d63bac | 2019-12-11 11:30:03 +0100 | [diff] [blame] | 1361 | proc.wait(timeout=support.SHORT_TIMEOUT) |
Gregory P. Smith | ab2719f | 2014-04-23 08:38:36 -0700 | [diff] [blame] | 1362 | self.assertEqual(proc.returncode, expected_errorcode, |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1363 | msg="unexpected result in wait from main thread") |
| 1364 | |
| 1365 | # This should be a no-op with no change in returncode. |
| 1366 | proc.wait() |
Gregory P. Smith | ab2719f | 2014-04-23 08:38:36 -0700 | [diff] [blame] | 1367 | self.assertEqual(proc.returncode, expected_errorcode, |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1368 | msg="unexpected result in second main wait.") |
| 1369 | |
| 1370 | t.join() |
| 1371 | # Ensure that all of the thread results are as expected. |
| 1372 | # When a race condition occurs in wait(), the returncode could |
| 1373 | # be set by the wrong thread that doesn't actually have it |
| 1374 | # leading to an incorrect value. |
| 1375 | self.assertEqual([('thread-start-poll-result', None), |
Gregory P. Smith | ab2719f | 2014-04-23 08:38:36 -0700 | [diff] [blame] | 1376 | ('thread-after-kill-and-wait', expected_errorcode), |
| 1377 | ('thread-after-second-wait', expected_errorcode)], |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1378 | results) |
| 1379 | |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 1380 | def test_issue8780(self): |
| 1381 | # Ensure that stdout is inherited from the parent |
| 1382 | # if stdout=PIPE is not used |
| 1383 | code = ';'.join(( |
| 1384 | 'import subprocess, sys', |
| 1385 | 'retcode = subprocess.call(' |
| 1386 | "[sys.executable, '-c', 'print(\"Hello World!\")'])", |
| 1387 | 'assert retcode == 0')) |
| 1388 | output = subprocess.check_output([sys.executable, '-c', code]) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1389 | self.assertTrue(output.startswith(b'Hello World!'), ascii(output)) |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 1390 | |
Tim Golden | af5ac39 | 2010-08-06 13:03:56 +0000 | [diff] [blame] | 1391 | def test_handles_closed_on_exception(self): |
| 1392 | # If CreateProcess exits with an error, ensure the |
| 1393 | # duplicate output handles are released |
Berker Peksag | 16a1f28 | 2015-09-28 13:33:14 +0300 | [diff] [blame] | 1394 | ifhandle, ifname = tempfile.mkstemp() |
| 1395 | ofhandle, ofname = tempfile.mkstemp() |
| 1396 | efhandle, efname = tempfile.mkstemp() |
Tim Golden | af5ac39 | 2010-08-06 13:03:56 +0000 | [diff] [blame] | 1397 | try: |
| 1398 | subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle, |
| 1399 | stderr=efhandle) |
| 1400 | except OSError: |
| 1401 | os.close(ifhandle) |
| 1402 | os.remove(ifname) |
| 1403 | os.close(ofhandle) |
| 1404 | os.remove(ofname) |
| 1405 | os.close(efhandle) |
| 1406 | os.remove(efname) |
| 1407 | self.assertFalse(os.path.exists(ifname)) |
| 1408 | self.assertFalse(os.path.exists(ofname)) |
| 1409 | self.assertFalse(os.path.exists(efname)) |
| 1410 | |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 1411 | def test_communicate_epipe(self): |
| 1412 | # Issue 10963: communicate() should hide EPIPE |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1413 | p = subprocess.Popen(ZERO_RETURN_CMD, |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 1414 | stdin=subprocess.PIPE, |
| 1415 | stdout=subprocess.PIPE, |
| 1416 | stderr=subprocess.PIPE) |
| 1417 | self.addCleanup(p.stdout.close) |
| 1418 | self.addCleanup(p.stderr.close) |
| 1419 | self.addCleanup(p.stdin.close) |
| 1420 | p.communicate(b"x" * 2**20) |
| 1421 | |
Andrey Doroschenko | 645005e | 2019-11-17 17:08:31 +0300 | [diff] [blame] | 1422 | def test_repr(self): |
| 1423 | # Run a command that waits for user input, to check the repr() of |
| 1424 | # a Proc object while and after the sub-process runs. |
| 1425 | code = 'import sys; input(); sys.exit(57)' |
| 1426 | cmd = [sys.executable, '-c', code] |
| 1427 | result = "<Popen: returncode: {}" |
| 1428 | |
| 1429 | with subprocess.Popen( |
| 1430 | cmd, stdin=subprocess.PIPE, universal_newlines=True) as proc: |
| 1431 | self.assertIsNone(proc.returncode) |
| 1432 | self.assertTrue( |
| 1433 | repr(proc).startswith(result.format(proc.returncode)) and |
| 1434 | repr(proc).endswith('>') |
| 1435 | ) |
| 1436 | |
| 1437 | proc.communicate(input='exit...\n') |
| 1438 | proc.wait() |
| 1439 | |
| 1440 | self.assertIsNotNone(proc.returncode) |
| 1441 | self.assertTrue( |
| 1442 | repr(proc).startswith(result.format(proc.returncode)) and |
| 1443 | repr(proc).endswith('>') |
| 1444 | ) |
| 1445 | |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 1446 | def test_communicate_epipe_only_stdin(self): |
| 1447 | # Issue 10963: communicate() should hide EPIPE |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1448 | p = subprocess.Popen(ZERO_RETURN_CMD, |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 1449 | stdin=subprocess.PIPE) |
| 1450 | self.addCleanup(p.stdin.close) |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1451 | p.wait() |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 1452 | p.communicate(b"x" * 2**20) |
| 1453 | |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1454 | @unittest.skipUnless(hasattr(signal, 'SIGUSR1'), |
| 1455 | "Requires signal.SIGUSR1") |
| 1456 | @unittest.skipUnless(hasattr(os, 'kill'), |
| 1457 | "Requires os.kill") |
| 1458 | @unittest.skipUnless(hasattr(os, 'getppid'), |
| 1459 | "Requires os.getppid") |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 1460 | def test_communicate_eintr(self): |
| 1461 | # Issue #12493: communicate() should handle EINTR |
| 1462 | def handler(signum, frame): |
| 1463 | pass |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1464 | old_handler = signal.signal(signal.SIGUSR1, handler) |
| 1465 | self.addCleanup(signal.signal, signal.SIGUSR1, old_handler) |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 1466 | |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1467 | args = [sys.executable, "-c", |
| 1468 | 'import os, signal;' |
| 1469 | 'os.kill(os.getppid(), signal.SIGUSR1)'] |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 1470 | for stream in ('stdout', 'stderr'): |
| 1471 | kw = {stream: subprocess.PIPE} |
| 1472 | with subprocess.Popen(args, **kw) as process: |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1473 | # communicate() will be interrupted by SIGUSR1 |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 1474 | process.communicate() |
| 1475 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1476 | |
Gregory P. Smith | 3d8e776 | 2012-11-10 22:32:22 -0800 | [diff] [blame] | 1477 | # This test is Linux-ish specific for simplicity to at least have |
| 1478 | # some coverage. It is not a platform specific bug. |
| 1479 | @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()), |
| 1480 | "Linux specific") |
| 1481 | def test_failed_child_execute_fd_leak(self): |
| 1482 | """Test for the fork() failure fd leak reported in issue16327.""" |
| 1483 | fd_directory = '/proc/%d/fd' % os.getpid() |
| 1484 | fds_before_popen = os.listdir(fd_directory) |
| 1485 | with self.assertRaises(PopenTestException): |
| 1486 | PopenExecuteChildRaises( |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1487 | ZERO_RETURN_CMD, stdin=subprocess.PIPE, |
Gregory P. Smith | 3d8e776 | 2012-11-10 22:32:22 -0800 | [diff] [blame] | 1488 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 1489 | |
| 1490 | # NOTE: This test doesn't verify that the real _execute_child |
| 1491 | # does not close the file descriptors itself on the way out |
| 1492 | # during an exception. Code inspection has confirmed that. |
| 1493 | |
| 1494 | fds_after_exception = os.listdir(fd_directory) |
| 1495 | self.assertEqual(fds_before_popen, fds_after_exception) |
| 1496 | |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 1497 | @unittest.skipIf(mswindows, "behavior currently not supported on Windows") |
Gregory P. Smith | 8621bb5 | 2017-08-24 14:58:25 -0700 | [diff] [blame] | 1498 | def test_file_not_found_includes_filename(self): |
| 1499 | with self.assertRaises(FileNotFoundError) as c: |
| 1500 | subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args']) |
| 1501 | self.assertEqual(c.exception.filename, '/opt/nonexistent_binary') |
| 1502 | |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 1503 | @unittest.skipIf(mswindows, "behavior currently not supported on Windows") |
Gregory P. Smith | 8621bb5 | 2017-08-24 14:58:25 -0700 | [diff] [blame] | 1504 | def test_file_not_found_with_bad_cwd(self): |
| 1505 | with self.assertRaises(FileNotFoundError) as c: |
| 1506 | subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory') |
| 1507 | self.assertEqual(c.exception.filename, '/some/nonexistent/directory') |
| 1508 | |
Batuhan Taşkaya | 4dc5a9d | 2019-12-30 19:02:04 +0300 | [diff] [blame] | 1509 | def test_class_getitems(self): |
Guido van Rossum | 48b069a | 2020-04-07 09:50:06 -0700 | [diff] [blame] | 1510 | self.assertIsInstance(subprocess.Popen[bytes], types.GenericAlias) |
| 1511 | self.assertIsInstance(subprocess.CompletedProcess[str], types.GenericAlias) |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 1512 | |
| 1513 | class RunFuncTestCase(BaseTestCase): |
| 1514 | def run_python(self, code, **kwargs): |
| 1515 | """Run Python code in a subprocess using subprocess.run""" |
| 1516 | argv = [sys.executable, "-c", code] |
| 1517 | return subprocess.run(argv, **kwargs) |
| 1518 | |
| 1519 | def test_returncode(self): |
| 1520 | # call() function with sequence argument |
| 1521 | cp = self.run_python("import sys; sys.exit(47)") |
| 1522 | self.assertEqual(cp.returncode, 47) |
| 1523 | with self.assertRaises(subprocess.CalledProcessError): |
| 1524 | cp.check_returncode() |
| 1525 | |
| 1526 | def test_check(self): |
| 1527 | with self.assertRaises(subprocess.CalledProcessError) as c: |
| 1528 | self.run_python("import sys; sys.exit(47)", check=True) |
| 1529 | self.assertEqual(c.exception.returncode, 47) |
| 1530 | |
| 1531 | def test_check_zero(self): |
| 1532 | # check_returncode shouldn't raise when returncode is zero |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1533 | cp = subprocess.run(ZERO_RETURN_CMD, check=True) |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 1534 | self.assertEqual(cp.returncode, 0) |
| 1535 | |
| 1536 | def test_timeout(self): |
| 1537 | # run() function with timeout argument; we want to test that the child |
| 1538 | # process gets killed when the timeout expires. If the child isn't |
| 1539 | # killed, this call will deadlock since subprocess.run waits for the |
| 1540 | # child. |
| 1541 | with self.assertRaises(subprocess.TimeoutExpired): |
| 1542 | self.run_python("while True: pass", timeout=0.0001) |
| 1543 | |
| 1544 | def test_capture_stdout(self): |
| 1545 | # capture stdout with zero return code |
| 1546 | cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE) |
| 1547 | self.assertIn(b'BDFL', cp.stdout) |
| 1548 | |
| 1549 | def test_capture_stderr(self): |
| 1550 | cp = self.run_python("import sys; sys.stderr.write('BDFL')", |
| 1551 | stderr=subprocess.PIPE) |
| 1552 | self.assertIn(b'BDFL', cp.stderr) |
| 1553 | |
| 1554 | def test_check_output_stdin_arg(self): |
| 1555 | # run() can be called with stdin set to a file |
| 1556 | tf = tempfile.TemporaryFile() |
| 1557 | self.addCleanup(tf.close) |
| 1558 | tf.write(b'pear') |
| 1559 | tf.seek(0) |
| 1560 | cp = self.run_python( |
| 1561 | "import sys; sys.stdout.write(sys.stdin.read().upper())", |
| 1562 | stdin=tf, stdout=subprocess.PIPE) |
| 1563 | self.assertIn(b'PEAR', cp.stdout) |
| 1564 | |
| 1565 | def test_check_output_input_arg(self): |
| 1566 | # check_output() can be called with input set to a string |
| 1567 | cp = self.run_python( |
| 1568 | "import sys; sys.stdout.write(sys.stdin.read().upper())", |
| 1569 | input=b'pear', stdout=subprocess.PIPE) |
| 1570 | self.assertIn(b'PEAR', cp.stdout) |
| 1571 | |
| 1572 | def test_check_output_stdin_with_input_arg(self): |
| 1573 | # run() refuses to accept 'stdin' with 'input' |
| 1574 | tf = tempfile.TemporaryFile() |
| 1575 | self.addCleanup(tf.close) |
| 1576 | tf.write(b'pear') |
| 1577 | tf.seek(0) |
| 1578 | with self.assertRaises(ValueError, |
| 1579 | msg="Expected ValueError when stdin and input args supplied.") as c: |
| 1580 | output = self.run_python("print('will not be run')", |
| 1581 | stdin=tf, input=b'hare') |
| 1582 | self.assertIn('stdin', c.exception.args[0]) |
| 1583 | self.assertIn('input', c.exception.args[0]) |
| 1584 | |
| 1585 | def test_check_output_timeout(self): |
| 1586 | with self.assertRaises(subprocess.TimeoutExpired) as c: |
| 1587 | cp = self.run_python(( |
| 1588 | "import sys, time\n" |
| 1589 | "sys.stdout.write('BDFL')\n" |
| 1590 | "sys.stdout.flush()\n" |
| 1591 | "time.sleep(3600)"), |
| 1592 | # Some heavily loaded buildbots (sparc Debian 3.x) require |
| 1593 | # this much time to start and print. |
| 1594 | timeout=3, stdout=subprocess.PIPE) |
| 1595 | self.assertEqual(c.exception.output, b'BDFL') |
| 1596 | # output is aliased to stdout |
| 1597 | self.assertEqual(c.exception.stdout, b'BDFL') |
| 1598 | |
| 1599 | def test_run_kwargs(self): |
| 1600 | newenv = os.environ.copy() |
| 1601 | newenv["FRUIT"] = "banana" |
| 1602 | cp = self.run_python(('import sys, os;' |
| 1603 | 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'), |
| 1604 | env=newenv) |
| 1605 | self.assertEqual(cp.returncode, 33) |
| 1606 | |
Serhiy Storchaka | 9e3c452 | 2019-05-28 22:49:35 +0300 | [diff] [blame] | 1607 | def test_run_with_pathlike_path(self): |
| 1608 | # bpo-31961: test run(pathlike_object) |
| 1609 | # the name of a command that can be run without |
Min ho Kim | c4cacc8 | 2019-07-31 08:16:13 +1000 | [diff] [blame] | 1610 | # any arguments that exit fast |
Serhiy Storchaka | 9e3c452 | 2019-05-28 22:49:35 +0300 | [diff] [blame] | 1611 | prog = 'tree.com' if mswindows else 'ls' |
| 1612 | path = shutil.which(prog) |
| 1613 | if path is None: |
| 1614 | self.skipTest(f'{prog} required for this test') |
| 1615 | path = FakePath(path) |
| 1616 | res = subprocess.run(path, stdout=subprocess.DEVNULL) |
| 1617 | self.assertEqual(res.returncode, 0) |
| 1618 | with self.assertRaises(TypeError): |
| 1619 | subprocess.run(path, stdout=subprocess.DEVNULL, shell=True) |
| 1620 | |
| 1621 | def test_run_with_bytes_path_and_arguments(self): |
| 1622 | # bpo-31961: test run([bytes_object, b'additional arguments']) |
| 1623 | path = os.fsencode(sys.executable) |
| 1624 | args = [path, '-c', b'import sys; sys.exit(57)'] |
| 1625 | res = subprocess.run(args) |
| 1626 | self.assertEqual(res.returncode, 57) |
| 1627 | |
| 1628 | def test_run_with_pathlike_path_and_arguments(self): |
| 1629 | # bpo-31961: test run([pathlike_object, 'additional arguments']) |
| 1630 | path = FakePath(sys.executable) |
| 1631 | args = [path, '-c', 'import sys; sys.exit(57)'] |
| 1632 | res = subprocess.run(args) |
| 1633 | self.assertEqual(res.returncode, 57) |
| 1634 | |
Bo Bayles | ce0f33d | 2018-01-30 00:40:39 -0600 | [diff] [blame] | 1635 | def test_capture_output(self): |
| 1636 | cp = self.run_python(("import sys;" |
| 1637 | "sys.stdout.write('BDFL'); " |
| 1638 | "sys.stderr.write('FLUFL')"), |
| 1639 | capture_output=True) |
| 1640 | self.assertIn(b'BDFL', cp.stdout) |
| 1641 | self.assertIn(b'FLUFL', cp.stderr) |
| 1642 | |
| 1643 | def test_stdout_with_capture_output_arg(self): |
| 1644 | # run() refuses to accept 'stdout' with 'capture_output' |
| 1645 | tf = tempfile.TemporaryFile() |
| 1646 | self.addCleanup(tf.close) |
| 1647 | with self.assertRaises(ValueError, |
| 1648 | msg=("Expected ValueError when stdout and capture_output " |
| 1649 | "args supplied.")) as c: |
| 1650 | output = self.run_python("print('will not be run')", |
| 1651 | capture_output=True, stdout=tf) |
| 1652 | self.assertIn('stdout', c.exception.args[0]) |
| 1653 | self.assertIn('capture_output', c.exception.args[0]) |
| 1654 | |
| 1655 | def test_stderr_with_capture_output_arg(self): |
| 1656 | # run() refuses to accept 'stderr' with 'capture_output' |
| 1657 | tf = tempfile.TemporaryFile() |
| 1658 | self.addCleanup(tf.close) |
| 1659 | with self.assertRaises(ValueError, |
| 1660 | msg=("Expected ValueError when stderr and capture_output " |
| 1661 | "args supplied.")) as c: |
| 1662 | output = self.run_python("print('will not be run')", |
| 1663 | capture_output=True, stderr=tf) |
| 1664 | self.assertIn('stderr', c.exception.args[0]) |
| 1665 | self.assertIn('capture_output', c.exception.args[0]) |
| 1666 | |
Gregory P. Smith | 580d278 | 2019-09-11 04:23:05 -0500 | [diff] [blame] | 1667 | # This test _might_ wind up a bit fragile on loaded build+test machines |
| 1668 | # as it depends on the timing with wide enough margins for normal situations |
| 1669 | # but does assert that it happened "soon enough" to believe the right thing |
| 1670 | # happened. |
| 1671 | @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command") |
| 1672 | def test_run_with_shell_timeout_and_capture_output(self): |
| 1673 | """Output capturing after a timeout mustn't hang forever on open filehandles.""" |
| 1674 | before_secs = time.monotonic() |
| 1675 | try: |
| 1676 | subprocess.run('sleep 3', shell=True, timeout=0.1, |
| 1677 | capture_output=True) # New session unspecified. |
| 1678 | except subprocess.TimeoutExpired as exc: |
| 1679 | after_secs = time.monotonic() |
| 1680 | stacks = traceback.format_exc() # assertRaises doesn't give this. |
| 1681 | else: |
| 1682 | self.fail("TimeoutExpired not raised.") |
| 1683 | self.assertLess(after_secs - before_secs, 1.5, |
| 1684 | msg="TimeoutExpired was delayed! Bad traceback:\n```\n" |
| 1685 | f"{stacks}```") |
| 1686 | |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 1687 | |
Gregory P. Smith | 693aa80 | 2019-09-13 14:43:35 +0100 | [diff] [blame] | 1688 | def _get_test_grp_name(): |
Victor Stinner | faca855 | 2019-09-25 15:52:49 +0200 | [diff] [blame] | 1689 | for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'): |
Gregory P. Smith | 693aa80 | 2019-09-13 14:43:35 +0100 | [diff] [blame] | 1690 | if grp: |
| 1691 | try: |
| 1692 | grp.getgrnam(name_group) |
| 1693 | except KeyError: |
| 1694 | continue |
| 1695 | return name_group |
| 1696 | else: |
| 1697 | raise unittest.SkipTest('No identified group name to use for this test on this platform.') |
| 1698 | |
| 1699 | |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 1700 | @unittest.skipIf(mswindows, "POSIX specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1701 | class POSIXProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1702 | |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1703 | def setUp(self): |
| 1704 | super().setUp() |
| 1705 | self._nonexistent_dir = "/_this/pa.th/does/not/exist" |
| 1706 | |
| 1707 | def _get_chdir_exception(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1708 | try: |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1709 | os.chdir(self._nonexistent_dir) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1710 | except OSError as e: |
| 1711 | # This avoids hard coding the errno value or the OS perror() |
| 1712 | # string and instead capture the exception that we want to see |
| 1713 | # below for comparison. |
| 1714 | desired_exception = e |
| 1715 | else: |
Martin Panter | eb99570 | 2016-07-28 01:11:04 +0000 | [diff] [blame] | 1716 | self.fail("chdir to nonexistent directory %s succeeded." % |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1717 | self._nonexistent_dir) |
| 1718 | return desired_exception |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1719 | |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1720 | def test_exception_cwd(self): |
| 1721 | """Test error in the child raised in the parent for a bad cwd.""" |
| 1722 | desired_exception = self._get_chdir_exception() |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1723 | try: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1724 | p = subprocess.Popen([sys.executable, "-c", ""], |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1725 | cwd=self._nonexistent_dir) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1726 | except OSError as e: |
| 1727 | # Test that the child process chdir failure actually makes |
| 1728 | # it up to the parent process as the correct exception. |
| 1729 | self.assertEqual(desired_exception.errno, e.errno) |
| 1730 | self.assertEqual(desired_exception.strerror, e.strerror) |
Zackery Spytz | 73870bf | 2018-09-11 09:54:07 -0600 | [diff] [blame] | 1731 | self.assertEqual(desired_exception.filename, e.filename) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1732 | else: |
| 1733 | self.fail("Expected OSError: %s" % desired_exception) |
| 1734 | |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1735 | def test_exception_bad_executable(self): |
| 1736 | """Test error in the child raised in the parent for a bad executable.""" |
| 1737 | desired_exception = self._get_chdir_exception() |
| 1738 | try: |
| 1739 | p = subprocess.Popen([sys.executable, "-c", ""], |
| 1740 | executable=self._nonexistent_dir) |
| 1741 | except OSError as e: |
| 1742 | # Test that the child process exec failure actually makes |
| 1743 | # it up to the parent process as the correct exception. |
| 1744 | self.assertEqual(desired_exception.errno, e.errno) |
| 1745 | self.assertEqual(desired_exception.strerror, e.strerror) |
Zackery Spytz | 73870bf | 2018-09-11 09:54:07 -0600 | [diff] [blame] | 1746 | self.assertEqual(desired_exception.filename, e.filename) |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1747 | else: |
| 1748 | self.fail("Expected OSError: %s" % desired_exception) |
| 1749 | |
| 1750 | def test_exception_bad_args_0(self): |
| 1751 | """Test error in the child raised in the parent for a bad args[0].""" |
| 1752 | desired_exception = self._get_chdir_exception() |
| 1753 | try: |
| 1754 | p = subprocess.Popen([self._nonexistent_dir, "-c", ""]) |
| 1755 | except OSError as e: |
| 1756 | # Test that the child process exec failure actually makes |
| 1757 | # it up to the parent process as the correct exception. |
| 1758 | self.assertEqual(desired_exception.errno, e.errno) |
| 1759 | self.assertEqual(desired_exception.strerror, e.strerror) |
Zackery Spytz | 73870bf | 2018-09-11 09:54:07 -0600 | [diff] [blame] | 1760 | self.assertEqual(desired_exception.filename, e.filename) |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1761 | else: |
| 1762 | self.fail("Expected OSError: %s" % desired_exception) |
| 1763 | |
Ammar Askar | 3fc499b | 2017-09-06 02:41:30 -0400 | [diff] [blame] | 1764 | # We mock the __del__ method for Popen in the next two tests |
| 1765 | # because it does cleanup based on the pid returned by fork_exec |
| 1766 | # along with issuing a resource warning if it still exists. Since |
| 1767 | # we don't actually spawn a process in these tests we can forego |
| 1768 | # the destructor. An alternative would be to set _child_created to |
| 1769 | # False before the destructor is called but there is no easy way |
| 1770 | # to do that |
| 1771 | class PopenNoDestructor(subprocess.Popen): |
| 1772 | def __del__(self): |
| 1773 | pass |
| 1774 | |
| 1775 | @mock.patch("subprocess._posixsubprocess.fork_exec") |
| 1776 | def test_exception_errpipe_normal(self, fork_exec): |
| 1777 | """Test error passing done through errpipe_write in the good case""" |
| 1778 | def proper_error(*args): |
| 1779 | errpipe_write = args[13] |
| 1780 | # Write the hex for the error code EISDIR: 'is a directory' |
| 1781 | err_code = '{:x}'.format(errno.EISDIR).encode() |
| 1782 | os.write(errpipe_write, b"OSError:" + err_code + b":") |
| 1783 | return 0 |
| 1784 | |
| 1785 | fork_exec.side_effect = proper_error |
| 1786 | |
Victor Stinner | 11045c9 | 2017-10-05 06:32:53 -0700 | [diff] [blame] | 1787 | with mock.patch("subprocess.os.waitpid", |
| 1788 | side_effect=ChildProcessError): |
| 1789 | with self.assertRaises(IsADirectoryError): |
| 1790 | self.PopenNoDestructor(["non_existent_command"]) |
Ammar Askar | 3fc499b | 2017-09-06 02:41:30 -0400 | [diff] [blame] | 1791 | |
| 1792 | @mock.patch("subprocess._posixsubprocess.fork_exec") |
| 1793 | def test_exception_errpipe_bad_data(self, fork_exec): |
| 1794 | """Test error passing done through errpipe_write where its not |
| 1795 | in the expected format""" |
| 1796 | error_data = b"\xFF\x00\xDE\xAD" |
| 1797 | def bad_error(*args): |
| 1798 | errpipe_write = args[13] |
| 1799 | # Anything can be in the pipe, no assumptions should |
| 1800 | # be made about its encoding, so we'll write some |
| 1801 | # arbitrary hex bytes to test it out |
| 1802 | os.write(errpipe_write, error_data) |
| 1803 | return 0 |
| 1804 | |
| 1805 | fork_exec.side_effect = bad_error |
| 1806 | |
Victor Stinner | 11045c9 | 2017-10-05 06:32:53 -0700 | [diff] [blame] | 1807 | with mock.patch("subprocess.os.waitpid", |
| 1808 | side_effect=ChildProcessError): |
| 1809 | with self.assertRaises(subprocess.SubprocessError) as e: |
| 1810 | self.PopenNoDestructor(["non_existent_command"]) |
Ammar Askar | 3fc499b | 2017-09-06 02:41:30 -0400 | [diff] [blame] | 1811 | |
| 1812 | self.assertIn(repr(error_data), str(e.exception)) |
| 1813 | |
Gregory P. Smith | 5f3d04f | 2018-06-05 12:00:57 -0700 | [diff] [blame] | 1814 | @unittest.skipIf(not os.path.exists('/proc/self/status'), |
| 1815 | "need /proc/self/status") |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1816 | def test_restore_signals(self): |
Gregory P. Smith | 5f3d04f | 2018-06-05 12:00:57 -0700 | [diff] [blame] | 1817 | # Blindly assume that cat exists on systems with /proc/self/status... |
| 1818 | default_proc_status = subprocess.check_output( |
| 1819 | ['cat', '/proc/self/status'], |
| 1820 | restore_signals=False) |
| 1821 | for line in default_proc_status.splitlines(): |
| 1822 | if line.startswith(b'SigIgn'): |
| 1823 | default_sig_ign_mask = line |
| 1824 | break |
| 1825 | else: |
| 1826 | self.skipTest("SigIgn not found in /proc/self/status.") |
| 1827 | restored_proc_status = subprocess.check_output( |
| 1828 | ['cat', '/proc/self/status'], |
| 1829 | restore_signals=True) |
| 1830 | for line in restored_proc_status.splitlines(): |
| 1831 | if line.startswith(b'SigIgn'): |
| 1832 | restored_sig_ign_mask = line |
| 1833 | break |
| 1834 | self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask, |
| 1835 | msg="restore_signals=True should've unblocked " |
| 1836 | "SIGPIPE and friends.") |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1837 | |
| 1838 | def test_start_new_session(self): |
| 1839 | # For code coverage of calling setsid(). We don't care if we get an |
| 1840 | # EPERM error from it depending on the test execution environment, that |
| 1841 | # still indicates that it was called. |
| 1842 | try: |
| 1843 | output = subprocess.check_output( |
Victor Stinner | 5884043 | 2019-06-14 19:31:43 +0200 | [diff] [blame] | 1844 | [sys.executable, "-c", "import os; print(os.getsid(0))"], |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1845 | start_new_session=True) |
| 1846 | except OSError as e: |
| 1847 | if e.errno != errno.EPERM: |
| 1848 | raise |
| 1849 | else: |
Victor Stinner | 5884043 | 2019-06-14 19:31:43 +0200 | [diff] [blame] | 1850 | parent_sid = os.getsid(0) |
| 1851 | child_sid = int(output) |
| 1852 | self.assertNotEqual(parent_sid, child_sid) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1853 | |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1854 | @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform') |
| 1855 | def test_user(self): |
| 1856 | # For code coverage of the user parameter. We don't care if we get an |
| 1857 | # EPERM error from it depending on the test execution environment, that |
| 1858 | # still indicates that it was called. |
| 1859 | |
| 1860 | uid = os.geteuid() |
| 1861 | test_users = [65534 if uid != 65534 else 65533, uid] |
| 1862 | name_uid = "nobody" if sys.platform != 'darwin' else "unknown" |
| 1863 | |
| 1864 | if pwd is not None: |
Victor Stinner | f7b5d41 | 2020-03-05 14:28:40 +0100 | [diff] [blame] | 1865 | try: |
| 1866 | pwd.getpwnam(name_uid) |
| 1867 | test_users.append(name_uid) |
| 1868 | except KeyError: |
| 1869 | # unknown user name |
| 1870 | name_uid = None |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1871 | |
| 1872 | for user in test_users: |
Victor Stinner | faca855 | 2019-09-25 15:52:49 +0200 | [diff] [blame] | 1873 | # posix_spawn() may be used with close_fds=False |
| 1874 | for close_fds in (False, True): |
| 1875 | with self.subTest(user=user, close_fds=close_fds): |
| 1876 | try: |
| 1877 | output = subprocess.check_output( |
| 1878 | [sys.executable, "-c", |
| 1879 | "import os; print(os.getuid())"], |
| 1880 | user=user, |
| 1881 | close_fds=close_fds) |
| 1882 | except PermissionError: # (EACCES, EPERM) |
| 1883 | pass |
| 1884 | except OSError as e: |
| 1885 | if e.errno not in (errno.EACCES, errno.EPERM): |
| 1886 | raise |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1887 | else: |
Victor Stinner | faca855 | 2019-09-25 15:52:49 +0200 | [diff] [blame] | 1888 | if isinstance(user, str): |
| 1889 | user_uid = pwd.getpwnam(user).pw_uid |
| 1890 | else: |
| 1891 | user_uid = user |
| 1892 | child_user = int(output) |
| 1893 | self.assertEqual(child_user, user_uid) |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1894 | |
| 1895 | with self.assertRaises(ValueError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1896 | subprocess.check_call(ZERO_RETURN_CMD, user=-1) |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1897 | |
Victor Stinner | f7b5d41 | 2020-03-05 14:28:40 +0100 | [diff] [blame] | 1898 | if pwd is None and name_uid is not None: |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1899 | with self.assertRaises(ValueError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1900 | subprocess.check_call(ZERO_RETURN_CMD, user=name_uid) |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1901 | |
| 1902 | @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform') |
| 1903 | def test_user_error(self): |
| 1904 | with self.assertRaises(ValueError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1905 | subprocess.check_call(ZERO_RETURN_CMD, user=65535) |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1906 | |
| 1907 | @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform') |
| 1908 | def test_group(self): |
| 1909 | gid = os.getegid() |
| 1910 | group_list = [65534 if gid != 65534 else 65533] |
Gregory P. Smith | 693aa80 | 2019-09-13 14:43:35 +0100 | [diff] [blame] | 1911 | name_group = _get_test_grp_name() |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1912 | |
| 1913 | if grp is not None: |
| 1914 | group_list.append(name_group) |
| 1915 | |
| 1916 | for group in group_list + [gid]: |
Victor Stinner | faca855 | 2019-09-25 15:52:49 +0200 | [diff] [blame] | 1917 | # posix_spawn() may be used with close_fds=False |
| 1918 | for close_fds in (False, True): |
| 1919 | with self.subTest(group=group, close_fds=close_fds): |
| 1920 | try: |
| 1921 | output = subprocess.check_output( |
| 1922 | [sys.executable, "-c", |
| 1923 | "import os; print(os.getgid())"], |
| 1924 | group=group, |
| 1925 | close_fds=close_fds) |
| 1926 | except PermissionError: # (EACCES, EPERM) |
| 1927 | pass |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1928 | else: |
Victor Stinner | faca855 | 2019-09-25 15:52:49 +0200 | [diff] [blame] | 1929 | if isinstance(group, str): |
| 1930 | group_gid = grp.getgrnam(group).gr_gid |
| 1931 | else: |
| 1932 | group_gid = group |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1933 | |
Victor Stinner | faca855 | 2019-09-25 15:52:49 +0200 | [diff] [blame] | 1934 | child_group = int(output) |
| 1935 | self.assertEqual(child_group, group_gid) |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1936 | |
| 1937 | # make sure we bomb on negative values |
| 1938 | with self.assertRaises(ValueError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1939 | subprocess.check_call(ZERO_RETURN_CMD, group=-1) |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1940 | |
| 1941 | if grp is None: |
| 1942 | with self.assertRaises(ValueError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1943 | subprocess.check_call(ZERO_RETURN_CMD, group=name_group) |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1944 | |
| 1945 | @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform') |
| 1946 | def test_group_error(self): |
| 1947 | with self.assertRaises(ValueError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1948 | subprocess.check_call(ZERO_RETURN_CMD, group=65535) |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1949 | |
| 1950 | @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform') |
| 1951 | def test_extra_groups(self): |
| 1952 | gid = os.getegid() |
| 1953 | group_list = [65534 if gid != 65534 else 65533] |
Gregory P. Smith | 693aa80 | 2019-09-13 14:43:35 +0100 | [diff] [blame] | 1954 | name_group = _get_test_grp_name() |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1955 | perm_error = False |
| 1956 | |
| 1957 | if grp is not None: |
| 1958 | group_list.append(name_group) |
| 1959 | |
| 1960 | try: |
| 1961 | output = subprocess.check_output( |
| 1962 | [sys.executable, "-c", |
| 1963 | "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"], |
| 1964 | extra_groups=group_list) |
| 1965 | except OSError as ex: |
| 1966 | if ex.errno != errno.EPERM: |
| 1967 | raise |
| 1968 | perm_error = True |
| 1969 | |
| 1970 | else: |
| 1971 | parent_groups = os.getgroups() |
| 1972 | child_groups = json.loads(output) |
| 1973 | |
| 1974 | if grp is not None: |
| 1975 | desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g |
| 1976 | for g in group_list] |
| 1977 | else: |
| 1978 | desired_gids = group_list |
| 1979 | |
| 1980 | if perm_error: |
| 1981 | self.assertEqual(set(child_groups), set(parent_groups)) |
| 1982 | else: |
| 1983 | self.assertEqual(set(desired_gids), set(child_groups)) |
| 1984 | |
| 1985 | # make sure we bomb on negative values |
| 1986 | with self.assertRaises(ValueError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1987 | subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1]) |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1988 | |
| 1989 | if grp is None: |
| 1990 | with self.assertRaises(ValueError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1991 | subprocess.check_call(ZERO_RETURN_CMD, |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1992 | extra_groups=[name_group]) |
| 1993 | |
| 1994 | @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform') |
| 1995 | def test_extra_groups_error(self): |
| 1996 | with self.assertRaises(ValueError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 1997 | subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[]) |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 1998 | |
Gregory P. Smith | f3751ef | 2019-10-12 13:24:56 -0700 | [diff] [blame] | 1999 | @unittest.skipIf(mswindows or not hasattr(os, 'umask'), |
| 2000 | 'POSIX umask() is not available.') |
| 2001 | def test_umask(self): |
| 2002 | tmpdir = None |
| 2003 | try: |
| 2004 | tmpdir = tempfile.mkdtemp() |
| 2005 | name = os.path.join(tmpdir, "beans") |
| 2006 | # We set an unusual umask in the child so as a unique mode |
| 2007 | # for us to test the child's touched file for. |
| 2008 | subprocess.check_call( |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 2009 | [sys.executable, "-c", f"open({name!r}, 'w').close()"], |
Gregory P. Smith | f3751ef | 2019-10-12 13:24:56 -0700 | [diff] [blame] | 2010 | umask=0o053) |
| 2011 | # Ignore execute permissions entirely in our test, |
| 2012 | # filesystems could be mounted to ignore or force that. |
| 2013 | st_mode = os.stat(name).st_mode & 0o666 |
| 2014 | expected_mode = 0o624 |
| 2015 | self.assertEqual(expected_mode, st_mode, |
| 2016 | msg=f'{oct(expected_mode)} != {oct(st_mode)}') |
| 2017 | finally: |
| 2018 | if tmpdir is not None: |
| 2019 | shutil.rmtree(tmpdir) |
| 2020 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2021 | def test_run_abort(self): |
| 2022 | # returncode handles signal termination |
Antoine Pitrou | 77e904e | 2013-10-08 23:04:32 +0200 | [diff] [blame] | 2023 | with support.SuppressCrashReport(): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2024 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2025 | 'import os; os.abort()']) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2026 | p.wait() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2027 | self.assertEqual(-p.returncode, signal.SIGABRT) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2028 | |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | d6da760 | 2016-06-03 06:14:06 +0000 | [diff] [blame] | 2029 | def test_CalledProcessError_str_signal(self): |
| 2030 | err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd") |
| 2031 | error_string = str(err) |
| 2032 | # We're relying on the repr() of the signal.Signals intenum to provide |
| 2033 | # the word signal, the signal name and the numeric value. |
| 2034 | self.assertIn("signal", error_string.lower()) |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | b414906 | 2016-06-03 06:19:35 +0000 | [diff] [blame] | 2035 | # We're not being specific about the signal name as some signals have |
| 2036 | # multiple names and which name is revealed can vary. |
| 2037 | self.assertIn("SIG", error_string) |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | d6da760 | 2016-06-03 06:14:06 +0000 | [diff] [blame] | 2038 | self.assertIn(str(signal.SIGABRT), error_string) |
| 2039 | |
| 2040 | def test_CalledProcessError_str_unknown_signal(self): |
| 2041 | err = subprocess.CalledProcessError(-9876543, "fake cmd") |
| 2042 | error_string = str(err) |
| 2043 | self.assertIn("unknown signal 9876543.", error_string) |
| 2044 | |
| 2045 | def test_CalledProcessError_str_non_zero(self): |
| 2046 | err = subprocess.CalledProcessError(2, "fake cmd") |
| 2047 | error_string = str(err) |
| 2048 | self.assertIn("non-zero exit status 2.", error_string) |
| 2049 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2050 | def test_preexec(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 2051 | # DISCLAIMER: Setting environment variables is *not* a good use |
| 2052 | # of a preexec_fn. This is merely a test. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2053 | p = subprocess.Popen([sys.executable, "-c", |
| 2054 | 'import sys,os;' |
| 2055 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 2056 | stdout=subprocess.PIPE, |
| 2057 | preexec_fn=lambda: os.putenv("FRUIT", "apple")) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 2058 | with p: |
| 2059 | self.assertEqual(p.stdout.read(), b"apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2060 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 2061 | def test_preexec_exception(self): |
| 2062 | def raise_it(): |
| 2063 | raise ValueError("What if two swallows carried a coconut?") |
| 2064 | try: |
| 2065 | p = subprocess.Popen([sys.executable, "-c", ""], |
| 2066 | preexec_fn=raise_it) |
Gregory P. Smith | 8d07c26 | 2012-11-10 23:53:47 -0800 | [diff] [blame] | 2067 | except subprocess.SubprocessError as e: |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 2068 | self.assertTrue( |
| 2069 | subprocess._posixsubprocess, |
| 2070 | "Expected a ValueError from the preexec_fn") |
| 2071 | except ValueError as e: |
| 2072 | self.assertIn("coconut", e.args[0]) |
| 2073 | else: |
| 2074 | self.fail("Exception raised by preexec_fn did not make it " |
| 2075 | "to the parent process.") |
| 2076 | |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 2077 | class _TestExecuteChildPopen(subprocess.Popen): |
| 2078 | """Used to test behavior at the end of _execute_child.""" |
| 2079 | def __init__(self, testcase, *args, **kwargs): |
| 2080 | self._testcase = testcase |
| 2081 | subprocess.Popen.__init__(self, *args, **kwargs) |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 2082 | |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 2083 | def _execute_child(self, *args, **kwargs): |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 2084 | try: |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 2085 | subprocess.Popen._execute_child(self, *args, **kwargs) |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 2086 | finally: |
| 2087 | # Open a bunch of file descriptors and verify that |
| 2088 | # none of them are the same as the ones the Popen |
| 2089 | # instance is using for stdin/stdout/stderr. |
| 2090 | devzero_fds = [os.open("/dev/zero", os.O_RDONLY) |
| 2091 | for _ in range(8)] |
| 2092 | try: |
| 2093 | for fd in devzero_fds: |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 2094 | self._testcase.assertNotIn( |
| 2095 | fd, (self.stdin.fileno(), self.stdout.fileno(), |
| 2096 | self.stderr.fileno()), |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 2097 | msg="At least one fd was closed early.") |
| 2098 | finally: |
Richard Oudkerk | 0e547b6 | 2013-06-10 16:29:19 +0100 | [diff] [blame] | 2099 | for fd in devzero_fds: |
| 2100 | os.close(fd) |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 2101 | |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 2102 | @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.") |
| 2103 | def test_preexec_errpipe_does_not_double_close_pipes(self): |
| 2104 | """Issue16140: Don't double close pipes on preexec error.""" |
| 2105 | |
| 2106 | def raise_it(): |
Gregory P. Smith | 65ee6ec | 2012-11-11 10:12:40 -0800 | [diff] [blame] | 2107 | raise subprocess.SubprocessError( |
| 2108 | "force the _execute_child() errpipe_data path.") |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 2109 | |
Gregory P. Smith | c2c4cb6 | 2012-11-11 01:41:49 -0800 | [diff] [blame] | 2110 | with self.assertRaises(subprocess.SubprocessError): |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 2111 | self._TestExecuteChildPopen( |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 2112 | self, ZERO_RETURN_CMD, |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 2113 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 2114 | stderr=subprocess.PIPE, preexec_fn=raise_it) |
| 2115 | |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 2116 | def test_preexec_gc_module_failure(self): |
| 2117 | # This tests the code that disables garbage collection if the child |
| 2118 | # process will execute any Python. |
| 2119 | def raise_runtime_error(): |
| 2120 | raise RuntimeError("this shouldn't escape") |
| 2121 | enabled = gc.isenabled() |
| 2122 | orig_gc_disable = gc.disable |
| 2123 | orig_gc_isenabled = gc.isenabled |
| 2124 | try: |
| 2125 | gc.disable() |
| 2126 | self.assertFalse(gc.isenabled()) |
| 2127 | subprocess.call([sys.executable, '-c', ''], |
| 2128 | preexec_fn=lambda: None) |
| 2129 | self.assertFalse(gc.isenabled(), |
| 2130 | "Popen enabled gc when it shouldn't.") |
| 2131 | |
| 2132 | gc.enable() |
| 2133 | self.assertTrue(gc.isenabled()) |
| 2134 | subprocess.call([sys.executable, '-c', ''], |
| 2135 | preexec_fn=lambda: None) |
| 2136 | self.assertTrue(gc.isenabled(), "Popen left gc disabled.") |
| 2137 | |
| 2138 | gc.disable = raise_runtime_error |
| 2139 | self.assertRaises(RuntimeError, subprocess.Popen, |
| 2140 | [sys.executable, '-c', ''], |
| 2141 | preexec_fn=lambda: None) |
| 2142 | |
| 2143 | del gc.isenabled # force an AttributeError |
| 2144 | self.assertRaises(AttributeError, subprocess.Popen, |
| 2145 | [sys.executable, '-c', ''], |
| 2146 | preexec_fn=lambda: None) |
| 2147 | finally: |
| 2148 | gc.disable = orig_gc_disable |
| 2149 | gc.isenabled = orig_gc_isenabled |
| 2150 | if not enabled: |
| 2151 | gc.disable() |
| 2152 | |
Martin Panter | f7fdbda | 2015-12-05 09:51:52 +0000 | [diff] [blame] | 2153 | @unittest.skipIf( |
| 2154 | sys.platform == 'darwin', 'setrlimit() seems to fail on OS X') |
Martin Panter | afdd513 | 2015-11-30 02:21:41 +0000 | [diff] [blame] | 2155 | def test_preexec_fork_failure(self): |
| 2156 | # The internal code did not preserve the previous exception when |
| 2157 | # re-enabling garbage collection |
| 2158 | try: |
| 2159 | from resource import getrlimit, setrlimit, RLIMIT_NPROC |
| 2160 | except ImportError as err: |
| 2161 | self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD |
| 2162 | limits = getrlimit(RLIMIT_NPROC) |
| 2163 | [_, hard] = limits |
| 2164 | setrlimit(RLIMIT_NPROC, (0, hard)) |
| 2165 | self.addCleanup(setrlimit, RLIMIT_NPROC, limits) |
Martin Panter | 5cf791b | 2015-12-11 05:40:14 +0000 | [diff] [blame] | 2166 | try: |
Martin Panter | afdd513 | 2015-11-30 02:21:41 +0000 | [diff] [blame] | 2167 | subprocess.call([sys.executable, '-c', ''], |
| 2168 | preexec_fn=lambda: None) |
Martin Panter | 5cf791b | 2015-12-11 05:40:14 +0000 | [diff] [blame] | 2169 | except BlockingIOError: |
| 2170 | # Forking should raise EAGAIN, translated to BlockingIOError |
| 2171 | pass |
| 2172 | else: |
| 2173 | self.skipTest('RLIMIT_NPROC had no effect; probably superuser') |
Martin Panter | afdd513 | 2015-11-30 02:21:41 +0000 | [diff] [blame] | 2174 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2175 | def test_args_string(self): |
| 2176 | # args is a string |
Berker Peksag | 16a1f28 | 2015-09-28 13:33:14 +0300 | [diff] [blame] | 2177 | fd, fname = tempfile.mkstemp() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2178 | # reopen in text mode |
Victor Stinner | f6782ac | 2010-10-16 23:46:43 +0000 | [diff] [blame] | 2179 | with open(fd, "w", errors="surrogateescape") as fobj: |
Xavier de Gaye | d141531 | 2016-07-22 12:15:29 +0200 | [diff] [blame] | 2180 | fobj.write("#!%s\n" % support.unix_shell) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2181 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 2182 | sys.executable) |
| 2183 | os.chmod(fname, 0o700) |
| 2184 | p = subprocess.Popen(fname) |
| 2185 | p.wait() |
| 2186 | os.remove(fname) |
| 2187 | self.assertEqual(p.returncode, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2188 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2189 | def test_invalid_args(self): |
| 2190 | # invalid arguments should raise ValueError |
| 2191 | self.assertRaises(ValueError, subprocess.call, |
| 2192 | [sys.executable, "-c", |
| 2193 | "import sys; sys.exit(47)"], |
| 2194 | startupinfo=47) |
| 2195 | self.assertRaises(ValueError, subprocess.call, |
| 2196 | [sys.executable, "-c", |
| 2197 | "import sys; sys.exit(47)"], |
| 2198 | creationflags=47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2199 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2200 | def test_shell_sequence(self): |
| 2201 | # Run command through the shell (sequence) |
| 2202 | newenv = os.environ.copy() |
| 2203 | newenv["FRUIT"] = "apple" |
| 2204 | p = subprocess.Popen(["echo $FRUIT"], shell=1, |
| 2205 | stdout=subprocess.PIPE, |
| 2206 | env=newenv) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 2207 | with p: |
| 2208 | self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2209 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2210 | def test_shell_string(self): |
| 2211 | # Run command through the shell (string) |
| 2212 | newenv = os.environ.copy() |
| 2213 | newenv["FRUIT"] = "apple" |
| 2214 | p = subprocess.Popen("echo $FRUIT", shell=1, |
| 2215 | stdout=subprocess.PIPE, |
| 2216 | env=newenv) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 2217 | with p: |
| 2218 | self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple") |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 2219 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2220 | def test_call_string(self): |
| 2221 | # call() function with string argument on UNIX |
Berker Peksag | 16a1f28 | 2015-09-28 13:33:14 +0300 | [diff] [blame] | 2222 | fd, fname = tempfile.mkstemp() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2223 | # reopen in text mode |
Victor Stinner | f6782ac | 2010-10-16 23:46:43 +0000 | [diff] [blame] | 2224 | with open(fd, "w", errors="surrogateescape") as fobj: |
Xavier de Gaye | d141531 | 2016-07-22 12:15:29 +0200 | [diff] [blame] | 2225 | fobj.write("#!%s\n" % support.unix_shell) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2226 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 2227 | sys.executable) |
| 2228 | os.chmod(fname, 0o700) |
| 2229 | rc = subprocess.call(fname) |
| 2230 | os.remove(fname) |
| 2231 | self.assertEqual(rc, 47) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 2232 | |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 2233 | def test_specific_shell(self): |
| 2234 | # Issue #9265: Incorrect name passed as arg[0]. |
| 2235 | shells = [] |
| 2236 | for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']: |
| 2237 | for name in ['bash', 'ksh']: |
| 2238 | sh = os.path.join(prefix, name) |
| 2239 | if os.path.isfile(sh): |
| 2240 | shells.append(sh) |
| 2241 | if not shells: # Will probably work for any shell but csh. |
| 2242 | self.skipTest("bash or ksh required for this test") |
| 2243 | sh = '/bin/sh' |
| 2244 | if os.path.isfile(sh) and not os.path.islink(sh): |
| 2245 | # Test will fail if /bin/sh is a symlink to csh. |
| 2246 | shells.append(sh) |
| 2247 | for sh in shells: |
| 2248 | p = subprocess.Popen("echo $0", executable=sh, shell=True, |
| 2249 | stdout=subprocess.PIPE) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 2250 | with p: |
| 2251 | self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii')) |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 2252 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2253 | def _kill_process(self, method, *args): |
Florent Xicluna | 1d8ee3a | 2010-03-05 20:26:54 +0000 | [diff] [blame] | 2254 | # Do not inherit file handles from the parent. |
| 2255 | # It should fix failures on some platforms. |
Gregory P. Smith | dee0434 | 2013-08-29 13:35:27 -0700 | [diff] [blame] | 2256 | # Also set the SIGINT handler to the default to make sure it's not |
| 2257 | # being ignored (some tests rely on that.) |
| 2258 | old_handler = signal.signal(signal.SIGINT, signal.default_int_handler) |
| 2259 | try: |
| 2260 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 2261 | import sys, time |
| 2262 | sys.stdout.write('x\\n') |
| 2263 | sys.stdout.flush() |
| 2264 | time.sleep(30) |
| 2265 | """], |
| 2266 | close_fds=True, |
| 2267 | stdin=subprocess.PIPE, |
| 2268 | stdout=subprocess.PIPE, |
| 2269 | stderr=subprocess.PIPE) |
| 2270 | finally: |
| 2271 | signal.signal(signal.SIGINT, old_handler) |
Antoine Pitrou | 3d8580f | 2010-09-20 01:33:21 +0000 | [diff] [blame] | 2272 | # Wait for the interpreter to be completely initialized before |
| 2273 | # sending any signal. |
| 2274 | p.stdout.read(1) |
| 2275 | getattr(p, method)(*args) |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2276 | return p |
| 2277 | |
Charles-François Natali | 53221e3 | 2013-01-12 16:52:20 +0100 | [diff] [blame] | 2278 | @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')), |
| 2279 | "Due to known OS bug (issue #16762)") |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 2280 | def _kill_dead_process(self, method, *args): |
| 2281 | # Do not inherit file handles from the parent. |
| 2282 | # It should fix failures on some platforms. |
| 2283 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 2284 | import sys, time |
| 2285 | sys.stdout.write('x\\n') |
| 2286 | sys.stdout.flush() |
| 2287 | """], |
| 2288 | close_fds=True, |
| 2289 | stdin=subprocess.PIPE, |
| 2290 | stdout=subprocess.PIPE, |
| 2291 | stderr=subprocess.PIPE) |
| 2292 | # Wait for the interpreter to be completely initialized before |
| 2293 | # sending any signal. |
| 2294 | p.stdout.read(1) |
| 2295 | # The process should end after this |
| 2296 | time.sleep(1) |
| 2297 | # This shouldn't raise even though the child is now dead |
| 2298 | getattr(p, method)(*args) |
| 2299 | p.communicate() |
| 2300 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2301 | def test_send_signal(self): |
| 2302 | p = self._kill_process('send_signal', signal.SIGINT) |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 2303 | _, stderr = p.communicate() |
| 2304 | self.assertIn(b'KeyboardInterrupt', stderr) |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 2305 | self.assertNotEqual(p.wait(), 0) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 2306 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2307 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2308 | p = self._kill_process('kill') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 2309 | _, stderr = p.communicate() |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 2310 | self.assertEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2311 | self.assertEqual(p.wait(), -signal.SIGKILL) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 2312 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2313 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2314 | p = self._kill_process('terminate') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 2315 | _, stderr = p.communicate() |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 2316 | self.assertEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2317 | self.assertEqual(p.wait(), -signal.SIGTERM) |
| 2318 | |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 2319 | def test_send_signal_dead(self): |
| 2320 | # Sending a signal to a dead process |
| 2321 | self._kill_dead_process('send_signal', signal.SIGINT) |
| 2322 | |
| 2323 | def test_kill_dead(self): |
| 2324 | # Killing a dead process |
| 2325 | self._kill_dead_process('kill') |
| 2326 | |
| 2327 | def test_terminate_dead(self): |
| 2328 | # Terminating a dead process |
| 2329 | self._kill_dead_process('terminate') |
| 2330 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2331 | def _save_fds(self, save_fds): |
| 2332 | fds = [] |
| 2333 | for fd in save_fds: |
| 2334 | inheritable = os.get_inheritable(fd) |
| 2335 | saved = os.dup(fd) |
| 2336 | fds.append((fd, saved, inheritable)) |
| 2337 | return fds |
| 2338 | |
| 2339 | def _restore_fds(self, fds): |
| 2340 | for fd, saved, inheritable in fds: |
| 2341 | os.dup2(saved, fd, inheritable=inheritable) |
| 2342 | os.close(saved) |
| 2343 | |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 2344 | def check_close_std_fds(self, fds): |
| 2345 | # Issue #9905: test that subprocess pipes still work properly with |
| 2346 | # some standard fds closed |
| 2347 | stdin = 0 |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2348 | saved_fds = self._save_fds(fds) |
| 2349 | for fd, saved, inheritable in saved_fds: |
| 2350 | if fd == 0: |
| 2351 | stdin = saved |
| 2352 | break |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 2353 | try: |
| 2354 | for fd in fds: |
| 2355 | os.close(fd) |
| 2356 | out, err = subprocess.Popen([sys.executable, "-c", |
| 2357 | 'import sys;' |
| 2358 | 'sys.stdout.write("apple");' |
| 2359 | 'sys.stdout.flush();' |
| 2360 | 'sys.stderr.write("orange")'], |
| 2361 | stdin=stdin, |
| 2362 | stdout=subprocess.PIPE, |
| 2363 | stderr=subprocess.PIPE).communicate() |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 2364 | self.assertEqual(out, b'apple') |
| 2365 | self.assertEqual(err, b'orange') |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 2366 | finally: |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2367 | self._restore_fds(saved_fds) |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 2368 | |
| 2369 | def test_close_fd_0(self): |
| 2370 | self.check_close_std_fds([0]) |
| 2371 | |
| 2372 | def test_close_fd_1(self): |
| 2373 | self.check_close_std_fds([1]) |
| 2374 | |
| 2375 | def test_close_fd_2(self): |
| 2376 | self.check_close_std_fds([2]) |
| 2377 | |
| 2378 | def test_close_fds_0_1(self): |
| 2379 | self.check_close_std_fds([0, 1]) |
| 2380 | |
| 2381 | def test_close_fds_0_2(self): |
| 2382 | self.check_close_std_fds([0, 2]) |
| 2383 | |
| 2384 | def test_close_fds_1_2(self): |
| 2385 | self.check_close_std_fds([1, 2]) |
| 2386 | |
| 2387 | def test_close_fds_0_1_2(self): |
| 2388 | # Issue #10806: test that subprocess pipes still work properly with |
| 2389 | # all standard fds closed. |
| 2390 | self.check_close_std_fds([0, 1, 2]) |
| 2391 | |
Gregory P. Smith | 53dd816 | 2013-12-01 16:03:24 -0800 | [diff] [blame] | 2392 | def test_small_errpipe_write_fd(self): |
| 2393 | """Issue #15798: Popen should work when stdio fds are available.""" |
| 2394 | new_stdin = os.dup(0) |
| 2395 | new_stdout = os.dup(1) |
| 2396 | try: |
| 2397 | os.close(0) |
| 2398 | os.close(1) |
| 2399 | |
| 2400 | # Side test: if errpipe_write fails to have its CLOEXEC |
| 2401 | # flag set this should cause the parent to think the exec |
| 2402 | # failed. Extremely unlikely: everyone supports CLOEXEC. |
| 2403 | subprocess.Popen([ |
| 2404 | sys.executable, "-c", |
| 2405 | "print('AssertionError:0:CLOEXEC failure.')"]).wait() |
| 2406 | finally: |
| 2407 | # Restore original stdin and stdout |
| 2408 | os.dup2(new_stdin, 0) |
| 2409 | os.dup2(new_stdout, 1) |
| 2410 | os.close(new_stdin) |
| 2411 | os.close(new_stdout) |
| 2412 | |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 2413 | def test_remapping_std_fds(self): |
| 2414 | # open up some temporary files |
Berker Peksag | 16a1f28 | 2015-09-28 13:33:14 +0300 | [diff] [blame] | 2415 | temps = [tempfile.mkstemp() for i in range(3)] |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 2416 | try: |
| 2417 | temp_fds = [fd for fd, fname in temps] |
| 2418 | |
| 2419 | # unlink the files -- we won't need to reopen them |
| 2420 | for fd, fname in temps: |
| 2421 | os.unlink(fname) |
| 2422 | |
| 2423 | # write some data to what will become stdin, and rewind |
| 2424 | os.write(temp_fds[1], b"STDIN") |
| 2425 | os.lseek(temp_fds[1], 0, 0) |
| 2426 | |
| 2427 | # move the standard file descriptors out of the way |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2428 | saved_fds = self._save_fds(range(3)) |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 2429 | try: |
| 2430 | # duplicate the file objects over the standard fd's |
| 2431 | for fd, temp_fd in enumerate(temp_fds): |
| 2432 | os.dup2(temp_fd, fd) |
| 2433 | |
| 2434 | # now use those files in the "wrong" order, so that subprocess |
| 2435 | # has to rearrange them in the child |
| 2436 | p = subprocess.Popen([sys.executable, "-c", |
| 2437 | 'import sys; got = sys.stdin.read();' |
| 2438 | 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'], |
| 2439 | stdin=temp_fds[1], |
| 2440 | stdout=temp_fds[2], |
| 2441 | stderr=temp_fds[0]) |
| 2442 | p.wait() |
| 2443 | finally: |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2444 | self._restore_fds(saved_fds) |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 2445 | |
| 2446 | for fd in temp_fds: |
| 2447 | os.lseek(fd, 0, 0) |
| 2448 | |
| 2449 | out = os.read(temp_fds[2], 1024) |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 2450 | err = os.read(temp_fds[0], 1024).strip() |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 2451 | self.assertEqual(out, b"got STDIN") |
| 2452 | self.assertEqual(err, b"err") |
| 2453 | |
| 2454 | finally: |
| 2455 | for fd in temp_fds: |
| 2456 | os.close(fd) |
| 2457 | |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 2458 | def check_swap_fds(self, stdin_no, stdout_no, stderr_no): |
| 2459 | # open up some temporary files |
Berker Peksag | 16a1f28 | 2015-09-28 13:33:14 +0300 | [diff] [blame] | 2460 | temps = [tempfile.mkstemp() for i in range(3)] |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 2461 | temp_fds = [fd for fd, fname in temps] |
| 2462 | try: |
| 2463 | # unlink the files -- we won't need to reopen them |
| 2464 | for fd, fname in temps: |
| 2465 | os.unlink(fname) |
| 2466 | |
| 2467 | # save a copy of the standard file descriptors |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2468 | saved_fds = self._save_fds(range(3)) |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 2469 | try: |
| 2470 | # duplicate the temp files over the standard fd's 0, 1, 2 |
| 2471 | for fd, temp_fd in enumerate(temp_fds): |
| 2472 | os.dup2(temp_fd, fd) |
| 2473 | |
| 2474 | # write some data to what will become stdin, and rewind |
| 2475 | os.write(stdin_no, b"STDIN") |
| 2476 | os.lseek(stdin_no, 0, 0) |
| 2477 | |
| 2478 | # now use those files in the given order, so that subprocess |
| 2479 | # has to rearrange them in the child |
| 2480 | p = subprocess.Popen([sys.executable, "-c", |
| 2481 | 'import sys; got = sys.stdin.read();' |
| 2482 | 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'], |
| 2483 | stdin=stdin_no, |
| 2484 | stdout=stdout_no, |
| 2485 | stderr=stderr_no) |
| 2486 | p.wait() |
| 2487 | |
| 2488 | for fd in temp_fds: |
| 2489 | os.lseek(fd, 0, 0) |
| 2490 | |
| 2491 | out = os.read(stdout_no, 1024) |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 2492 | err = os.read(stderr_no, 1024).strip() |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 2493 | finally: |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2494 | self._restore_fds(saved_fds) |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 2495 | |
| 2496 | self.assertEqual(out, b"got STDIN") |
| 2497 | self.assertEqual(err, b"err") |
| 2498 | |
| 2499 | finally: |
| 2500 | for fd in temp_fds: |
| 2501 | os.close(fd) |
| 2502 | |
| 2503 | # When duping fds, if there arises a situation where one of the fds is |
| 2504 | # either 0, 1 or 2, it is possible that it is overwritten (#12607). |
| 2505 | # This tests all combinations of this. |
| 2506 | def test_swap_fds(self): |
| 2507 | self.check_swap_fds(0, 1, 2) |
| 2508 | self.check_swap_fds(0, 2, 1) |
| 2509 | self.check_swap_fds(1, 0, 2) |
| 2510 | self.check_swap_fds(1, 2, 0) |
| 2511 | self.check_swap_fds(2, 0, 1) |
| 2512 | self.check_swap_fds(2, 1, 0) |
| 2513 | |
Alexey Izbyshev | 0e7144b | 2018-03-26 22:49:35 +0300 | [diff] [blame] | 2514 | def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds): |
| 2515 | saved_fds = self._save_fds(range(3)) |
| 2516 | try: |
| 2517 | for from_fd in from_fds: |
| 2518 | with tempfile.TemporaryFile() as f: |
| 2519 | os.dup2(f.fileno(), from_fd) |
| 2520 | |
| 2521 | fd_to_close = (set(range(3)) - set(from_fds)).pop() |
| 2522 | os.close(fd_to_close) |
| 2523 | |
| 2524 | arg_names = ['stdin', 'stdout', 'stderr'] |
| 2525 | kwargs = {} |
| 2526 | for from_fd, to_fd in zip(from_fds, to_fds): |
| 2527 | kwargs[arg_names[to_fd]] = from_fd |
| 2528 | |
| 2529 | code = textwrap.dedent(r''' |
| 2530 | import os, sys |
| 2531 | skipped_fd = int(sys.argv[1]) |
| 2532 | for fd in range(3): |
| 2533 | if fd != skipped_fd: |
| 2534 | os.write(fd, str(fd).encode('ascii')) |
| 2535 | ''') |
| 2536 | |
| 2537 | skipped_fd = (set(range(3)) - set(to_fds)).pop() |
| 2538 | |
| 2539 | rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)], |
| 2540 | **kwargs) |
| 2541 | self.assertEqual(rc, 0) |
| 2542 | |
| 2543 | for from_fd, to_fd in zip(from_fds, to_fds): |
| 2544 | os.lseek(from_fd, 0, os.SEEK_SET) |
| 2545 | read_bytes = os.read(from_fd, 1024) |
| 2546 | read_fds = list(map(int, read_bytes.decode('ascii'))) |
| 2547 | msg = textwrap.dedent(f""" |
| 2548 | When testing {from_fds} to {to_fds} redirection, |
| 2549 | parent descriptor {from_fd} got redirected |
| 2550 | to descriptor(s) {read_fds} instead of descriptor {to_fd}. |
| 2551 | """) |
| 2552 | self.assertEqual([to_fd], read_fds, msg) |
| 2553 | finally: |
| 2554 | self._restore_fds(saved_fds) |
| 2555 | |
| 2556 | # Check that subprocess can remap std fds correctly even |
| 2557 | # if one of them is closed (#32844). |
| 2558 | def test_swap_std_fds_with_one_closed(self): |
| 2559 | for from_fds in itertools.combinations(range(3), 2): |
| 2560 | for to_fds in itertools.permutations(range(3), 2): |
| 2561 | self._check_swap_std_fds_with_one_closed(from_fds, to_fds) |
| 2562 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 2563 | def test_surrogates_error_message(self): |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 2564 | def prepare(): |
| 2565 | raise ValueError("surrogate:\uDCff") |
| 2566 | |
| 2567 | try: |
| 2568 | subprocess.call( |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 2569 | ZERO_RETURN_CMD, |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 2570 | preexec_fn=prepare) |
| 2571 | except ValueError as err: |
| 2572 | # Pure Python implementations keeps the message |
| 2573 | self.assertIsNone(subprocess._posixsubprocess) |
| 2574 | self.assertEqual(str(err), "surrogate:\uDCff") |
Gregory P. Smith | 8d07c26 | 2012-11-10 23:53:47 -0800 | [diff] [blame] | 2575 | except subprocess.SubprocessError as err: |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 2576 | # _posixsubprocess uses a default message |
| 2577 | self.assertIsNotNone(subprocess._posixsubprocess) |
| 2578 | self.assertEqual(str(err), "Exception occurred in preexec_fn.") |
| 2579 | else: |
Gregory P. Smith | 8d07c26 | 2012-11-10 23:53:47 -0800 | [diff] [blame] | 2580 | self.fail("Expected ValueError or subprocess.SubprocessError") |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 2581 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 2582 | def test_undecodable_env(self): |
| 2583 | for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')): |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 2584 | encoded_value = value.encode("ascii", "surrogateescape") |
| 2585 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 2586 | # test str with surrogates |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 2587 | script = "import os; print(ascii(os.getenv(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 2588 | env = os.environ.copy() |
| 2589 | env[key] = value |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 2590 | # Use C locale to get ASCII for the locale encoding to force |
Michael Felt | 89d79b1 | 2018-08-26 19:29:36 +0200 | [diff] [blame] | 2591 | # surrogate-escaping of \xFF in the child process |
Victor Stinner | ebc78d2 | 2010-10-14 10:38:17 +0000 | [diff] [blame] | 2592 | env['LC_ALL'] = 'C' |
Michael Felt | 89d79b1 | 2018-08-26 19:29:36 +0200 | [diff] [blame] | 2593 | decoded_value = value |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 2594 | stdout = subprocess.check_output( |
| 2595 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 2596 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 2597 | stdout = stdout.rstrip(b'\n\r') |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 2598 | self.assertEqual(stdout.decode('ascii'), ascii(decoded_value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 2599 | |
| 2600 | # test bytes |
| 2601 | key = key.encode("ascii", "surrogateescape") |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 2602 | script = "import os; print(ascii(os.getenvb(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 2603 | env = os.environ.copy() |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 2604 | env[key] = encoded_value |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 2605 | stdout = subprocess.check_output( |
| 2606 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 2607 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 2608 | stdout = stdout.rstrip(b'\n\r') |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 2609 | self.assertEqual(stdout.decode('ascii'), ascii(encoded_value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 2610 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 2611 | def test_bytes_program(self): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 2612 | abs_program = os.fsencode(ZERO_RETURN_CMD[0]) |
| 2613 | args = list(ZERO_RETURN_CMD[1:]) |
| 2614 | path, program = os.path.split(ZERO_RETURN_CMD[0]) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 2615 | program = os.fsencode(program) |
| 2616 | |
| 2617 | # absolute bytes path |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 2618 | exitcode = subprocess.call([abs_program]+args) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2619 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 2620 | |
Victor Stinner | 7b3b20a | 2011-03-03 12:54:05 +0000 | [diff] [blame] | 2621 | # absolute bytes path as a string |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 2622 | cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8")) |
Victor Stinner | 7b3b20a | 2011-03-03 12:54:05 +0000 | [diff] [blame] | 2623 | exitcode = subprocess.call(cmd, shell=True) |
| 2624 | self.assertEqual(exitcode, 0) |
| 2625 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 2626 | # bytes program, unicode PATH |
| 2627 | env = os.environ.copy() |
| 2628 | env["PATH"] = path |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 2629 | exitcode = subprocess.call([program]+args, env=env) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2630 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 2631 | |
| 2632 | # bytes program, bytes PATH |
| 2633 | envb = os.environb.copy() |
| 2634 | envb[b"PATH"] = os.fsencode(path) |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 2635 | exitcode = subprocess.call([program]+args, env=envb) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2636 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 2637 | |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 2638 | def test_pipe_cloexec(self): |
| 2639 | sleeper = support.findfile("input_reader.py", subdir="subprocessdata") |
| 2640 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 2641 | |
| 2642 | p1 = subprocess.Popen([sys.executable, sleeper], |
| 2643 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 2644 | stderr=subprocess.PIPE, close_fds=False) |
| 2645 | |
| 2646 | self.addCleanup(p1.communicate, b'') |
| 2647 | |
| 2648 | p2 = subprocess.Popen([sys.executable, fd_status], |
| 2649 | stdout=subprocess.PIPE, close_fds=False) |
| 2650 | |
| 2651 | output, error = p2.communicate() |
| 2652 | result_fds = set(map(int, output.split(b','))) |
| 2653 | unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(), |
| 2654 | p1.stderr.fileno()]) |
| 2655 | |
| 2656 | self.assertFalse(result_fds & unwanted_fds, |
| 2657 | "Expected no fds from %r to be open in child, " |
| 2658 | "found %r" % |
| 2659 | (unwanted_fds, result_fds & unwanted_fds)) |
| 2660 | |
| 2661 | def test_pipe_cloexec_real_tools(self): |
| 2662 | qcat = support.findfile("qcat.py", subdir="subprocessdata") |
| 2663 | qgrep = support.findfile("qgrep.py", subdir="subprocessdata") |
| 2664 | |
| 2665 | subdata = b'zxcvbn' |
| 2666 | data = subdata * 4 + b'\n' |
| 2667 | |
| 2668 | p1 = subprocess.Popen([sys.executable, qcat], |
| 2669 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 2670 | close_fds=False) |
| 2671 | |
| 2672 | p2 = subprocess.Popen([sys.executable, qgrep, subdata], |
| 2673 | stdin=p1.stdout, stdout=subprocess.PIPE, |
| 2674 | close_fds=False) |
| 2675 | |
| 2676 | self.addCleanup(p1.wait) |
| 2677 | self.addCleanup(p2.wait) |
Gregory P. Smith | 886455c | 2012-01-21 22:05:10 -0800 | [diff] [blame] | 2678 | def kill_p1(): |
| 2679 | try: |
| 2680 | p1.terminate() |
| 2681 | except ProcessLookupError: |
| 2682 | pass |
| 2683 | def kill_p2(): |
| 2684 | try: |
| 2685 | p2.terminate() |
| 2686 | except ProcessLookupError: |
| 2687 | pass |
| 2688 | self.addCleanup(kill_p1) |
| 2689 | self.addCleanup(kill_p2) |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 2690 | |
| 2691 | p1.stdin.write(data) |
| 2692 | p1.stdin.close() |
| 2693 | |
| 2694 | readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10) |
| 2695 | |
| 2696 | self.assertTrue(readfiles, "The child hung") |
| 2697 | self.assertEqual(p2.stdout.read(), data) |
| 2698 | |
Victor Stinner | faa8c13 | 2011-01-03 16:36:00 +0000 | [diff] [blame] | 2699 | p1.stdout.close() |
| 2700 | p2.stdout.close() |
| 2701 | |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 2702 | def test_close_fds(self): |
| 2703 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 2704 | |
| 2705 | fds = os.pipe() |
| 2706 | self.addCleanup(os.close, fds[0]) |
| 2707 | self.addCleanup(os.close, fds[1]) |
| 2708 | |
| 2709 | open_fds = set(fds) |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 2710 | # add a bunch more fds |
| 2711 | for _ in range(9): |
Serhiy Storchaka | 85c3033 | 2015-02-15 13:58:23 +0200 | [diff] [blame] | 2712 | fd = os.open(os.devnull, os.O_RDONLY) |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 2713 | self.addCleanup(os.close, fd) |
| 2714 | open_fds.add(fd) |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 2715 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2716 | for fd in open_fds: |
| 2717 | os.set_inheritable(fd, True) |
| 2718 | |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 2719 | p = subprocess.Popen([sys.executable, fd_status], |
| 2720 | stdout=subprocess.PIPE, close_fds=False) |
| 2721 | output, ignored = p.communicate() |
| 2722 | remaining_fds = set(map(int, output.split(b','))) |
| 2723 | |
| 2724 | self.assertEqual(remaining_fds & open_fds, open_fds, |
| 2725 | "Some fds were closed") |
| 2726 | |
| 2727 | p = subprocess.Popen([sys.executable, fd_status], |
| 2728 | stdout=subprocess.PIPE, close_fds=True) |
| 2729 | output, ignored = p.communicate() |
| 2730 | remaining_fds = set(map(int, output.split(b','))) |
| 2731 | |
| 2732 | self.assertFalse(remaining_fds & open_fds, |
| 2733 | "Some fds were left open") |
| 2734 | self.assertIn(1, remaining_fds, "Subprocess failed") |
| 2735 | |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 2736 | # Keep some of the fd's we opened open in the subprocess. |
| 2737 | # This tests _posixsubprocess.c's proper handling of fds_to_keep. |
| 2738 | fds_to_keep = set(open_fds.pop() for _ in range(8)) |
| 2739 | p = subprocess.Popen([sys.executable, fd_status], |
| 2740 | stdout=subprocess.PIPE, close_fds=True, |
izbyshev | 2d8f063 | 2017-12-19 03:26:49 +0700 | [diff] [blame] | 2741 | pass_fds=fds_to_keep) |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 2742 | output, ignored = p.communicate() |
| 2743 | remaining_fds = set(map(int, output.split(b','))) |
| 2744 | |
izbyshev | 2d8f063 | 2017-12-19 03:26:49 +0700 | [diff] [blame] | 2745 | self.assertFalse((remaining_fds - fds_to_keep) & open_fds, |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 2746 | "Some fds not in pass_fds were left open") |
| 2747 | self.assertIn(1, remaining_fds, "Subprocess failed") |
| 2748 | |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2749 | |
Gregory P. Smith | d04f699 | 2014-06-01 15:27:28 -0700 | [diff] [blame] | 2750 | @unittest.skipIf(sys.platform.startswith("freebsd") and |
| 2751 | os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev, |
| 2752 | "Requires fdescfs mounted on /dev/fd on FreeBSD.") |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2753 | def test_close_fds_when_max_fd_is_lowered(self): |
| 2754 | """Confirm that issue21618 is fixed (may fail under valgrind).""" |
| 2755 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 2756 | |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2757 | # This launches the meat of the test in a child process to |
| 2758 | # avoid messing with the larger unittest processes maximum |
| 2759 | # number of file descriptors. |
| 2760 | # This process launches: |
| 2761 | # +--> Process that lowers its RLIMIT_NOFILE aftr setting up |
| 2762 | # a bunch of high open fds above the new lower rlimit. |
| 2763 | # Those are reported via stdout before launching a new |
| 2764 | # process with close_fds=False to run the actual test: |
| 2765 | # +--> The TEST: This one launches a fd_status.py |
| 2766 | # subprocess with close_fds=True so we can find out if |
| 2767 | # any of the fds above the lowered rlimit are still open. |
| 2768 | p = subprocess.Popen([sys.executable, '-c', textwrap.dedent( |
| 2769 | ''' |
| 2770 | import os, resource, subprocess, sys, textwrap |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2771 | open_fds = set() |
| 2772 | # Add a bunch more fds to pass down. |
Gregory P. Smith | 8fed4de | 2014-06-01 15:15:44 -0700 | [diff] [blame] | 2773 | for _ in range(40): |
Serhiy Storchaka | 85c3033 | 2015-02-15 13:58:23 +0200 | [diff] [blame] | 2774 | fd = os.open(os.devnull, os.O_RDONLY) |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2775 | open_fds.add(fd) |
| 2776 | |
| 2777 | # Leave a two pairs of low ones available for use by the |
| 2778 | # internal child error pipe and the stdout pipe. |
Gregory P. Smith | 8fed4de | 2014-06-01 15:15:44 -0700 | [diff] [blame] | 2779 | # We also leave 10 more open as some Python buildbots run into |
| 2780 | # "too many open files" errors during the test if we do not. |
| 2781 | for fd in sorted(open_fds)[:14]: |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2782 | os.close(fd) |
| 2783 | open_fds.remove(fd) |
| 2784 | |
| 2785 | for fd in open_fds: |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2786 | #self.addCleanup(os.close, fd) |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2787 | os.set_inheritable(fd, True) |
| 2788 | |
| 2789 | max_fd_open = max(open_fds) |
| 2790 | |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2791 | # Communicate the open_fds to the parent unittest.TestCase process. |
| 2792 | print(','.join(map(str, sorted(open_fds)))) |
| 2793 | sys.stdout.flush() |
| 2794 | |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2795 | rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE) |
| 2796 | try: |
Gregory P. Smith | 8fed4de | 2014-06-01 15:15:44 -0700 | [diff] [blame] | 2797 | # 29 is lower than the highest fds we are leaving open. |
| 2798 | resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max)) |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2799 | # Launch a new Python interpreter with our low fd rlim_cur that |
| 2800 | # inherits open fds above that limit. It then uses subprocess |
| 2801 | # with close_fds=True to get a report of open fds in the child. |
| 2802 | # An explicit list of fds to check is passed to fd_status.py as |
| 2803 | # letting fd_status rely on its default logic would miss the |
| 2804 | # fds above rlim_cur as it normally only checks up to that limit. |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2805 | subprocess.Popen( |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2806 | [sys.executable, '-c', |
| 2807 | textwrap.dedent(""" |
| 2808 | import subprocess, sys |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2809 | subprocess.Popen([sys.executable, %r] + |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2810 | [str(x) for x in range({max_fd})], |
Gregory P. Smith | ffd529c | 2014-06-01 13:46:54 -0700 | [diff] [blame] | 2811 | close_fds=True).wait() |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2812 | """.format(max_fd=max_fd_open+1))], |
| 2813 | close_fds=False).wait() |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2814 | finally: |
| 2815 | resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max)) |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2816 | ''' % fd_status)], stdout=subprocess.PIPE) |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2817 | |
| 2818 | output, unused_stderr = p.communicate() |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2819 | output_lines = output.splitlines() |
| 2820 | self.assertEqual(len(output_lines), 2, |
Gregory P. Smith | 9204e09 | 2014-06-15 20:16:01 -0700 | [diff] [blame] | 2821 | msg="expected exactly two lines of output:\n%r" % output) |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2822 | opened_fds = set(map(int, output_lines[0].strip().split(b','))) |
| 2823 | remaining_fds = set(map(int, output_lines[1].strip().split(b','))) |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2824 | |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2825 | self.assertFalse(remaining_fds & opened_fds, |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2826 | msg="Some fds were left open.") |
| 2827 | |
| 2828 | |
Victor Stinner | 88701e2 | 2011-06-01 13:13:04 +0200 | [diff] [blame] | 2829 | # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file |
| 2830 | # descriptor of a pipe closed in the parent process is valid in the |
| 2831 | # child process according to fstat(), but the mode of the file |
| 2832 | # descriptor is invalid, and read or write raise an error. |
| 2833 | @support.requires_mac_ver(10, 5) |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 2834 | def test_pass_fds(self): |
| 2835 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 2836 | |
| 2837 | open_fds = set() |
| 2838 | |
| 2839 | for x in range(5): |
| 2840 | fds = os.pipe() |
| 2841 | self.addCleanup(os.close, fds[0]) |
| 2842 | self.addCleanup(os.close, fds[1]) |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2843 | os.set_inheritable(fds[0], True) |
| 2844 | os.set_inheritable(fds[1], True) |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 2845 | open_fds.update(fds) |
| 2846 | |
| 2847 | for fd in open_fds: |
| 2848 | p = subprocess.Popen([sys.executable, fd_status], |
| 2849 | stdout=subprocess.PIPE, close_fds=True, |
| 2850 | pass_fds=(fd, )) |
| 2851 | output, ignored = p.communicate() |
| 2852 | |
| 2853 | remaining_fds = set(map(int, output.split(b','))) |
| 2854 | to_be_closed = open_fds - {fd} |
| 2855 | |
| 2856 | self.assertIn(fd, remaining_fds, "fd to be passed not passed") |
| 2857 | self.assertFalse(remaining_fds & to_be_closed, |
| 2858 | "fd to be closed passed") |
| 2859 | |
| 2860 | # pass_fds overrides close_fds with a warning. |
| 2861 | with self.assertWarns(RuntimeWarning) as context: |
| 2862 | self.assertFalse(subprocess.call( |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 2863 | ZERO_RETURN_CMD, |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 2864 | close_fds=False, pass_fds=(fd, ))) |
| 2865 | self.assertIn('overriding close_fds', str(context.warning)) |
| 2866 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2867 | def test_pass_fds_inheritable(self): |
Victor Stinner | f6fa22e | 2013-09-01 10:22:41 +0200 | [diff] [blame] | 2868 | script = support.findfile("fd_status.py", subdir="subprocessdata") |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2869 | |
| 2870 | inheritable, non_inheritable = os.pipe() |
| 2871 | self.addCleanup(os.close, inheritable) |
| 2872 | self.addCleanup(os.close, non_inheritable) |
| 2873 | os.set_inheritable(inheritable, True) |
| 2874 | os.set_inheritable(non_inheritable, False) |
| 2875 | pass_fds = (inheritable, non_inheritable) |
| 2876 | args = [sys.executable, script] |
| 2877 | args += list(map(str, pass_fds)) |
| 2878 | |
| 2879 | p = subprocess.Popen(args, |
| 2880 | stdout=subprocess.PIPE, close_fds=True, |
| 2881 | pass_fds=pass_fds) |
| 2882 | output, ignored = p.communicate() |
| 2883 | fds = set(map(int, output.split(b','))) |
| 2884 | |
| 2885 | # the inheritable file descriptor must be inherited, so its inheritable |
| 2886 | # flag must be set in the child process after fork() and before exec() |
Victor Stinner | f6fa22e | 2013-09-01 10:22:41 +0200 | [diff] [blame] | 2887 | self.assertEqual(fds, set(pass_fds), "output=%a" % output) |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2888 | |
| 2889 | # inheritable flag must not be changed in the parent process |
| 2890 | self.assertEqual(os.get_inheritable(inheritable), True) |
| 2891 | self.assertEqual(os.get_inheritable(non_inheritable), False) |
| 2892 | |
Gregory P. Smith | ce34410 | 2018-09-10 17:46:22 -0700 | [diff] [blame] | 2893 | |
| 2894 | # bpo-32270: Ensure that descriptors specified in pass_fds |
| 2895 | # are inherited even if they are used in redirections. |
| 2896 | # Contributed by @izbyshev. |
| 2897 | def test_pass_fds_redirected(self): |
| 2898 | """Regression test for https://bugs.python.org/issue32270.""" |
| 2899 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 2900 | pass_fds = [] |
| 2901 | for _ in range(2): |
| 2902 | fd = os.open(os.devnull, os.O_RDWR) |
| 2903 | self.addCleanup(os.close, fd) |
| 2904 | pass_fds.append(fd) |
| 2905 | |
| 2906 | stdout_r, stdout_w = os.pipe() |
| 2907 | self.addCleanup(os.close, stdout_r) |
| 2908 | self.addCleanup(os.close, stdout_w) |
| 2909 | pass_fds.insert(1, stdout_w) |
| 2910 | |
| 2911 | with subprocess.Popen([sys.executable, fd_status], |
| 2912 | stdin=pass_fds[0], |
| 2913 | stdout=pass_fds[1], |
| 2914 | stderr=pass_fds[2], |
| 2915 | close_fds=True, |
| 2916 | pass_fds=pass_fds): |
| 2917 | output = os.read(stdout_r, 1024) |
| 2918 | fds = {int(num) for num in output.split(b',')} |
| 2919 | |
| 2920 | self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}") |
| 2921 | |
| 2922 | |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 2923 | def test_stdout_stdin_are_single_inout_fd(self): |
| 2924 | with io.open(os.devnull, "r+") as inout: |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 2925 | p = subprocess.Popen(ZERO_RETURN_CMD, |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 2926 | stdout=inout, stdin=inout) |
| 2927 | p.wait() |
| 2928 | |
| 2929 | def test_stdout_stderr_are_single_inout_fd(self): |
| 2930 | with io.open(os.devnull, "r+") as inout: |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 2931 | p = subprocess.Popen(ZERO_RETURN_CMD, |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 2932 | stdout=inout, stderr=inout) |
| 2933 | p.wait() |
| 2934 | |
| 2935 | def test_stderr_stdin_are_single_inout_fd(self): |
| 2936 | with io.open(os.devnull, "r+") as inout: |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 2937 | p = subprocess.Popen(ZERO_RETURN_CMD, |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 2938 | stderr=inout, stdin=inout) |
| 2939 | p.wait() |
| 2940 | |
Gregory P. Smith | e85db2b | 2010-12-14 14:38:00 +0000 | [diff] [blame] | 2941 | def test_wait_when_sigchild_ignored(self): |
| 2942 | # NOTE: sigchild_ignore.py may not be an effective test on all OSes. |
| 2943 | sigchild_ignore = support.findfile("sigchild_ignore.py", |
| 2944 | subdir="subprocessdata") |
| 2945 | p = subprocess.Popen([sys.executable, sigchild_ignore], |
| 2946 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 2947 | stdout, stderr = p.communicate() |
| 2948 | self.assertEqual(0, p.returncode, "sigchild_ignore.py exited" |
Gregory P. Smith | a80f4fb | 2010-12-14 15:23:02 +0000 | [diff] [blame] | 2949 | " non-zero with this error:\n%s" % |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 2950 | stderr.decode('utf-8')) |
Gregory P. Smith | e85db2b | 2010-12-14 14:38:00 +0000 | [diff] [blame] | 2951 | |
Antoine Pitrou | 7b98d02 | 2011-03-19 17:04:13 +0100 | [diff] [blame] | 2952 | def test_select_unbuffered(self): |
| 2953 | # Issue #11459: bufsize=0 should really set the pipes as |
| 2954 | # unbuffered (and therefore let select() work properly). |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 2955 | select = import_helper.import_module("select") |
Antoine Pitrou | 7b98d02 | 2011-03-19 17:04:13 +0100 | [diff] [blame] | 2956 | p = subprocess.Popen([sys.executable, "-c", |
| 2957 | 'import sys;' |
| 2958 | 'sys.stdout.write("apple")'], |
| 2959 | stdout=subprocess.PIPE, |
| 2960 | bufsize=0) |
| 2961 | f = p.stdout |
Ross Lagerwall | 17ace7a | 2011-03-26 21:21:46 +0200 | [diff] [blame] | 2962 | self.addCleanup(f.close) |
Antoine Pitrou | 7b98d02 | 2011-03-19 17:04:13 +0100 | [diff] [blame] | 2963 | try: |
| 2964 | self.assertEqual(f.read(4), b"appl") |
| 2965 | self.assertIn(f, select.select([f], [], [], 0.0)[0]) |
| 2966 | finally: |
| 2967 | p.wait() |
| 2968 | |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2969 | def test_zombie_fast_process_del(self): |
| 2970 | # Issue #12650: on Unix, if Popen.__del__() was called before the |
| 2971 | # process exited, it wouldn't be added to subprocess._active, and would |
| 2972 | # remain a zombie. |
| 2973 | # spawn a Popen, and delete its reference before it exits |
| 2974 | p = subprocess.Popen([sys.executable, "-c", |
| 2975 | 'import sys, time;' |
| 2976 | 'time.sleep(0.2)'], |
| 2977 | stdout=subprocess.PIPE, |
| 2978 | stderr=subprocess.PIPE) |
Nadeem Vawda | 0d7cda3 | 2011-08-19 05:12:01 +0200 | [diff] [blame] | 2979 | self.addCleanup(p.stdout.close) |
| 2980 | self.addCleanup(p.stderr.close) |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2981 | ident = id(p) |
| 2982 | pid = p.pid |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 2983 | with warnings_helper.check_warnings(('', ResourceWarning)): |
Victor Stinner | 5a48e21 | 2016-05-20 12:11:15 +0200 | [diff] [blame] | 2984 | p = None |
| 2985 | |
Ruslan Kuprieiev | 042821a | 2019-06-28 19:12:16 +0300 | [diff] [blame] | 2986 | if mswindows: |
| 2987 | # subprocess._active is not used on Windows and is set to None. |
| 2988 | self.assertIsNone(subprocess._active) |
| 2989 | else: |
| 2990 | # check that p is in the active processes list |
| 2991 | self.assertIn(ident, [id(o) for o in subprocess._active]) |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2992 | |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2993 | def test_leak_fast_process_del_killed(self): |
| 2994 | # Issue #12650: on Unix, if Popen.__del__() was called before the |
| 2995 | # process exited, and the process got killed by a signal, it would never |
| 2996 | # be removed from subprocess._active, which triggered a FD and memory |
| 2997 | # leak. |
| 2998 | # spawn a Popen, delete its reference and kill it |
| 2999 | p = subprocess.Popen([sys.executable, "-c", |
| 3000 | 'import time;' |
| 3001 | 'time.sleep(3)'], |
| 3002 | stdout=subprocess.PIPE, |
| 3003 | stderr=subprocess.PIPE) |
Nadeem Vawda | 0d7cda3 | 2011-08-19 05:12:01 +0200 | [diff] [blame] | 3004 | self.addCleanup(p.stdout.close) |
| 3005 | self.addCleanup(p.stderr.close) |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 3006 | ident = id(p) |
| 3007 | pid = p.pid |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 3008 | with warnings_helper.check_warnings(('', ResourceWarning)): |
Victor Stinner | 5a48e21 | 2016-05-20 12:11:15 +0200 | [diff] [blame] | 3009 | p = None |
| 3010 | |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 3011 | os.kill(pid, signal.SIGKILL) |
Ruslan Kuprieiev | 042821a | 2019-06-28 19:12:16 +0300 | [diff] [blame] | 3012 | if mswindows: |
| 3013 | # subprocess._active is not used on Windows and is set to None. |
| 3014 | self.assertIsNone(subprocess._active) |
| 3015 | else: |
| 3016 | # check that p is in the active processes list |
| 3017 | self.assertIn(ident, [id(o) for o in subprocess._active]) |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 3018 | |
| 3019 | # let some time for the process to exit, and create a new Popen: this |
| 3020 | # should trigger the wait() of p |
| 3021 | time.sleep(0.2) |
Victor Stinner | b31206a | 2018-01-25 19:06:05 +0100 | [diff] [blame] | 3022 | with self.assertRaises(OSError): |
Victor Stinner | 9a83f65 | 2017-08-21 23:51:31 +0200 | [diff] [blame] | 3023 | with subprocess.Popen(NONEXISTING_CMD, |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 3024 | stdout=subprocess.PIPE, |
| 3025 | stderr=subprocess.PIPE) as proc: |
| 3026 | pass |
| 3027 | # p should have been wait()ed on, and removed from the _active list |
| 3028 | self.assertRaises(OSError, os.waitpid, pid, 0) |
Ruslan Kuprieiev | 042821a | 2019-06-28 19:12:16 +0300 | [diff] [blame] | 3029 | if mswindows: |
| 3030 | # subprocess._active is not used on Windows and is set to None. |
| 3031 | self.assertIsNone(subprocess._active) |
| 3032 | else: |
| 3033 | self.assertNotIn(ident, [id(o) for o in subprocess._active]) |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 3034 | |
Charles-François Natali | 249cdc3 | 2013-08-25 18:24:45 +0200 | [diff] [blame] | 3035 | def test_close_fds_after_preexec(self): |
| 3036 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 3037 | |
| 3038 | # this FD is used as dup2() target by preexec_fn, and should be closed |
| 3039 | # in the child process |
| 3040 | fd = os.dup(1) |
| 3041 | self.addCleanup(os.close, fd) |
| 3042 | |
| 3043 | p = subprocess.Popen([sys.executable, fd_status], |
| 3044 | stdout=subprocess.PIPE, close_fds=True, |
| 3045 | preexec_fn=lambda: os.dup2(1, fd)) |
| 3046 | output, ignored = p.communicate() |
| 3047 | |
| 3048 | remaining_fds = set(map(int, output.split(b','))) |
| 3049 | |
| 3050 | self.assertNotIn(fd, remaining_fds) |
| 3051 | |
Victor Stinner | 8f437aa | 2014-10-05 17:25:19 +0200 | [diff] [blame] | 3052 | @support.cpython_only |
| 3053 | def test_fork_exec(self): |
| 3054 | # Issue #22290: fork_exec() must not crash on memory allocation failure |
| 3055 | # or other errors |
| 3056 | import _posixsubprocess |
| 3057 | gc_enabled = gc.isenabled() |
| 3058 | try: |
| 3059 | # Use a preexec function and enable the garbage collector |
| 3060 | # to force fork_exec() to re-enable the garbage collector |
| 3061 | # on error. |
| 3062 | func = lambda: None |
| 3063 | gc.enable() |
| 3064 | |
Victor Stinner | 8f437aa | 2014-10-05 17:25:19 +0200 | [diff] [blame] | 3065 | for args, exe_list, cwd, env_list in ( |
| 3066 | (123, [b"exe"], None, [b"env"]), |
| 3067 | ([b"arg"], 123, None, [b"env"]), |
| 3068 | ([b"arg"], [b"exe"], 123, [b"env"]), |
| 3069 | ([b"arg"], [b"exe"], None, 123), |
| 3070 | ): |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 3071 | with self.assertRaises(TypeError) as err: |
Victor Stinner | 8f437aa | 2014-10-05 17:25:19 +0200 | [diff] [blame] | 3072 | _posixsubprocess.fork_exec( |
| 3073 | args, exe_list, |
Serhiy Storchaka | 66bffd1 | 2017-04-19 21:12:46 +0300 | [diff] [blame] | 3074 | True, (), cwd, env_list, |
Victor Stinner | 8f437aa | 2014-10-05 17:25:19 +0200 | [diff] [blame] | 3075 | -1, -1, -1, -1, |
| 3076 | 1, 2, 3, 4, |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 3077 | True, True, |
Gregory P. Smith | f3751ef | 2019-10-12 13:24:56 -0700 | [diff] [blame] | 3078 | False, [], 0, -1, |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 3079 | func) |
| 3080 | # Attempt to prevent |
| 3081 | # "TypeError: fork_exec() takes exactly N arguments (M given)" |
| 3082 | # from passing the test. More refactoring to have us start |
| 3083 | # with a valid *args list, confirm a good call with that works |
| 3084 | # before mutating it in various ways to ensure that bad calls |
| 3085 | # with individual arg type errors raise a typeerror would be |
| 3086 | # ideal. Saving that for a future PR... |
| 3087 | self.assertNotIn('takes exactly', str(err.exception)) |
Victor Stinner | 8f437aa | 2014-10-05 17:25:19 +0200 | [diff] [blame] | 3088 | finally: |
| 3089 | if not gc_enabled: |
| 3090 | gc.disable() |
| 3091 | |
Gregory P. Smith | d0a5b1c | 2015-11-15 21:15:26 -0800 | [diff] [blame] | 3092 | @support.cpython_only |
| 3093 | def test_fork_exec_sorted_fd_sanity_check(self): |
| 3094 | # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check. |
| 3095 | import _posixsubprocess |
Serhiy Storchaka | 66bffd1 | 2017-04-19 21:12:46 +0300 | [diff] [blame] | 3096 | class BadInt: |
| 3097 | first = True |
| 3098 | def __init__(self, value): |
| 3099 | self.value = value |
| 3100 | def __int__(self): |
| 3101 | if self.first: |
| 3102 | self.first = False |
| 3103 | return self.value |
| 3104 | raise ValueError |
| 3105 | |
Gregory P. Smith | d0a5b1c | 2015-11-15 21:15:26 -0800 | [diff] [blame] | 3106 | gc_enabled = gc.isenabled() |
| 3107 | try: |
| 3108 | gc.enable() |
| 3109 | |
| 3110 | for fds_to_keep in ( |
| 3111 | (-1, 2, 3, 4, 5), # Negative number. |
| 3112 | ('str', 4), # Not an int. |
| 3113 | (18, 23, 42, 2**63), # Out of range. |
| 3114 | (5, 4), # Not sorted. |
| 3115 | (6, 7, 7, 8), # Duplicate. |
Serhiy Storchaka | 66bffd1 | 2017-04-19 21:12:46 +0300 | [diff] [blame] | 3116 | (BadInt(1), BadInt(2)), |
Gregory P. Smith | d0a5b1c | 2015-11-15 21:15:26 -0800 | [diff] [blame] | 3117 | ): |
| 3118 | with self.assertRaises( |
| 3119 | ValueError, |
| 3120 | msg='fds_to_keep={}'.format(fds_to_keep)) as c: |
| 3121 | _posixsubprocess.fork_exec( |
| 3122 | [b"false"], [b"false"], |
| 3123 | True, fds_to_keep, None, [b"env"], |
| 3124 | -1, -1, -1, -1, |
| 3125 | 1, 2, 3, 4, |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 3126 | True, True, |
Gregory P. Smith | f3751ef | 2019-10-12 13:24:56 -0700 | [diff] [blame] | 3127 | None, None, None, -1, |
Patrick McLean | 2b2ead7 | 2019-09-12 10:15:44 -0700 | [diff] [blame] | 3128 | None) |
Gregory P. Smith | d0a5b1c | 2015-11-15 21:15:26 -0800 | [diff] [blame] | 3129 | self.assertIn('fds_to_keep', str(c.exception)) |
| 3130 | finally: |
| 3131 | if not gc_enabled: |
| 3132 | gc.disable() |
Victor Stinner | 8f437aa | 2014-10-05 17:25:19 +0200 | [diff] [blame] | 3133 | |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 2daf8e7 | 2016-06-05 02:57:47 +0000 | [diff] [blame] | 3134 | def test_communicate_BrokenPipeError_stdin_close(self): |
| 3135 | # By not setting stdout or stderr or a timeout we force the fast path |
| 3136 | # that just calls _stdin_write() internally due to our mock. |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 3137 | proc = subprocess.Popen(ZERO_RETURN_CMD) |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 2daf8e7 | 2016-06-05 02:57:47 +0000 | [diff] [blame] | 3138 | with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin: |
| 3139 | mock_proc_stdin.close.side_effect = BrokenPipeError |
| 3140 | proc.communicate() # Should swallow BrokenPipeError from close. |
| 3141 | mock_proc_stdin.close.assert_called_with() |
| 3142 | |
| 3143 | def test_communicate_BrokenPipeError_stdin_write(self): |
| 3144 | # By not setting stdout or stderr or a timeout we force the fast path |
| 3145 | # that just calls _stdin_write() internally due to our mock. |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 3146 | proc = subprocess.Popen(ZERO_RETURN_CMD) |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 2daf8e7 | 2016-06-05 02:57:47 +0000 | [diff] [blame] | 3147 | with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin: |
| 3148 | mock_proc_stdin.write.side_effect = BrokenPipeError |
| 3149 | proc.communicate(b'stuff') # Should swallow the BrokenPipeError. |
| 3150 | mock_proc_stdin.write.assert_called_once_with(b'stuff') |
| 3151 | mock_proc_stdin.close.assert_called_once_with() |
| 3152 | |
| 3153 | def test_communicate_BrokenPipeError_stdin_flush(self): |
| 3154 | # Setting stdin and stdout forces the ._communicate() code path. |
| 3155 | # python -h exits faster than python -c pass (but spams stdout). |
| 3156 | proc = subprocess.Popen([sys.executable, '-h'], |
| 3157 | stdin=subprocess.PIPE, |
| 3158 | stdout=subprocess.PIPE) |
| 3159 | with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \ |
| 3160 | open(os.devnull, 'wb') as dev_null: |
| 3161 | mock_proc_stdin.flush.side_effect = BrokenPipeError |
| 3162 | # because _communicate registers a selector using proc.stdin... |
| 3163 | mock_proc_stdin.fileno.return_value = dev_null.fileno() |
| 3164 | # _communicate() should swallow BrokenPipeError from flush. |
| 3165 | proc.communicate(b'stuff') |
| 3166 | mock_proc_stdin.flush.assert_called_once_with() |
| 3167 | |
| 3168 | def test_communicate_BrokenPipeError_stdin_close_with_timeout(self): |
| 3169 | # Setting stdin and stdout forces the ._communicate() code path. |
| 3170 | # python -h exits faster than python -c pass (but spams stdout). |
| 3171 | proc = subprocess.Popen([sys.executable, '-h'], |
| 3172 | stdin=subprocess.PIPE, |
| 3173 | stdout=subprocess.PIPE) |
| 3174 | with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin: |
| 3175 | mock_proc_stdin.close.side_effect = BrokenPipeError |
| 3176 | # _communicate() should swallow BrokenPipeError from close. |
| 3177 | proc.communicate(timeout=999) |
| 3178 | mock_proc_stdin.close.assert_called_once_with() |
| 3179 | |
Victor Stinner | 7b7c6dc | 2017-08-10 12:37:39 +0200 | [diff] [blame] | 3180 | @unittest.skipUnless(_testcapi is not None |
| 3181 | and hasattr(_testcapi, 'W_STOPCODE'), |
| 3182 | 'need _testcapi.W_STOPCODE') |
| 3183 | def test_stopped(self): |
Gregory P. Smith | 50e16e3 | 2017-01-22 17:28:38 -0800 | [diff] [blame] | 3184 | """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335.""" |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 3185 | args = ZERO_RETURN_CMD |
Victor Stinner | 7b7c6dc | 2017-08-10 12:37:39 +0200 | [diff] [blame] | 3186 | proc = subprocess.Popen(args) |
Victor Stinner | cdee3f1 | 2017-06-26 17:23:03 +0200 | [diff] [blame] | 3187 | |
Victor Stinner | 7b7c6dc | 2017-08-10 12:37:39 +0200 | [diff] [blame] | 3188 | # Wait until the real process completes to avoid zombie process |
Victor Stinner | 278c1e1 | 2020-03-31 20:08:12 +0200 | [diff] [blame] | 3189 | support.wait_process(proc.pid, exitcode=0) |
Victor Stinner | cdee3f1 | 2017-06-26 17:23:03 +0200 | [diff] [blame] | 3190 | |
Victor Stinner | 7b7c6dc | 2017-08-10 12:37:39 +0200 | [diff] [blame] | 3191 | status = _testcapi.W_STOPCODE(3) |
Victor Stinner | 278c1e1 | 2020-03-31 20:08:12 +0200 | [diff] [blame] | 3192 | with mock.patch('subprocess.os.waitpid', return_value=(proc.pid, status)): |
Victor Stinner | 7b7c6dc | 2017-08-10 12:37:39 +0200 | [diff] [blame] | 3193 | returncode = proc.wait() |
Victor Stinner | cdee3f1 | 2017-06-26 17:23:03 +0200 | [diff] [blame] | 3194 | |
Victor Stinner | 7b7c6dc | 2017-08-10 12:37:39 +0200 | [diff] [blame] | 3195 | self.assertEqual(returncode, -3) |
Gregory P. Smith | 50e16e3 | 2017-01-22 17:28:38 -0800 | [diff] [blame] | 3196 | |
Victor Stinner | e85a305 | 2020-01-15 17:38:55 +0100 | [diff] [blame] | 3197 | def test_send_signal_race(self): |
| 3198 | # bpo-38630: send_signal() must poll the process exit status to reduce |
| 3199 | # the risk of sending the signal to the wrong process. |
| 3200 | proc = subprocess.Popen(ZERO_RETURN_CMD) |
| 3201 | |
| 3202 | # wait until the process completes without using the Popen APIs. |
Victor Stinner | 278c1e1 | 2020-03-31 20:08:12 +0200 | [diff] [blame] | 3203 | support.wait_process(proc.pid, exitcode=0) |
Victor Stinner | e85a305 | 2020-01-15 17:38:55 +0100 | [diff] [blame] | 3204 | |
| 3205 | # returncode is still None but the process completed. |
| 3206 | self.assertIsNone(proc.returncode) |
| 3207 | |
| 3208 | with mock.patch("os.kill") as mock_kill: |
| 3209 | proc.send_signal(signal.SIGTERM) |
| 3210 | |
| 3211 | # send_signal() didn't call os.kill() since the process already |
| 3212 | # completed. |
| 3213 | mock_kill.assert_not_called() |
| 3214 | |
| 3215 | # Don't check the returncode value: the test reads the exit status, |
| 3216 | # so Popen failed to read it and uses a default returncode instead. |
| 3217 | self.assertIsNotNone(proc.returncode) |
| 3218 | |
Alex Rebert | d3ae95e | 2020-01-22 18:28:31 -0500 | [diff] [blame] | 3219 | def test_communicate_repeated_call_after_stdout_close(self): |
| 3220 | proc = subprocess.Popen([sys.executable, '-c', |
| 3221 | 'import os, time; os.close(1), time.sleep(2)'], |
| 3222 | stdout=subprocess.PIPE) |
| 3223 | while True: |
| 3224 | try: |
| 3225 | proc.communicate(timeout=0.1) |
| 3226 | return |
| 3227 | except subprocess.TimeoutExpired: |
| 3228 | pass |
| 3229 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3230 | |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 3231 | @unittest.skipUnless(mswindows, "Windows specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 3232 | class Win32ProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 3233 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3234 | def test_startupinfo(self): |
| 3235 | # startupinfo argument |
| 3236 | # We uses hardcoded constants, because we do not want to |
| 3237 | # depend on win32all. |
| 3238 | STARTF_USESHOWWINDOW = 1 |
| 3239 | SW_MAXIMIZE = 3 |
| 3240 | startupinfo = subprocess.STARTUPINFO() |
| 3241 | startupinfo.dwFlags = STARTF_USESHOWWINDOW |
| 3242 | startupinfo.wShowWindow = SW_MAXIMIZE |
| 3243 | # Since Python is a console process, it won't be affected |
| 3244 | # by wShowWindow, but the argument should be silently |
| 3245 | # ignored |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 3246 | subprocess.call(ZERO_RETURN_CMD, |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 3247 | startupinfo=startupinfo) |
| 3248 | |
Subhendu Ghosh | ae160bb | 2017-02-25 20:29:05 +0530 | [diff] [blame] | 3249 | def test_startupinfo_keywords(self): |
| 3250 | # startupinfo argument |
| 3251 | # We use hardcoded constants, because we do not want to |
| 3252 | # depend on win32all. |
| 3253 | STARTF_USERSHOWWINDOW = 1 |
| 3254 | SW_MAXIMIZE = 3 |
| 3255 | startupinfo = subprocess.STARTUPINFO( |
| 3256 | dwFlags=STARTF_USERSHOWWINDOW, |
| 3257 | wShowWindow=SW_MAXIMIZE |
| 3258 | ) |
| 3259 | # Since Python is a console process, it won't be affected |
| 3260 | # by wShowWindow, but the argument should be silently |
| 3261 | # ignored |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 3262 | subprocess.call(ZERO_RETURN_CMD, |
Subhendu Ghosh | ae160bb | 2017-02-25 20:29:05 +0530 | [diff] [blame] | 3263 | startupinfo=startupinfo) |
| 3264 | |
Victor Stinner | 483422f | 2018-07-05 22:54:17 +0200 | [diff] [blame] | 3265 | def test_startupinfo_copy(self): |
| 3266 | # bpo-34044: Popen must not modify input STARTUPINFO structure |
| 3267 | startupinfo = subprocess.STARTUPINFO() |
| 3268 | startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW |
| 3269 | startupinfo.wShowWindow = subprocess.SW_HIDE |
| 3270 | |
| 3271 | # Call Popen() twice with the same startupinfo object to make sure |
| 3272 | # that it's not modified |
| 3273 | for _ in range(2): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 3274 | cmd = ZERO_RETURN_CMD |
Victor Stinner | 483422f | 2018-07-05 22:54:17 +0200 | [diff] [blame] | 3275 | with open(os.devnull, 'w') as null: |
| 3276 | proc = subprocess.Popen(cmd, |
| 3277 | stdout=null, |
| 3278 | stderr=subprocess.STDOUT, |
| 3279 | startupinfo=startupinfo) |
| 3280 | with proc: |
| 3281 | proc.communicate() |
| 3282 | self.assertEqual(proc.returncode, 0) |
| 3283 | |
| 3284 | self.assertEqual(startupinfo.dwFlags, |
| 3285 | subprocess.STARTF_USESHOWWINDOW) |
| 3286 | self.assertIsNone(startupinfo.hStdInput) |
| 3287 | self.assertIsNone(startupinfo.hStdOutput) |
| 3288 | self.assertIsNone(startupinfo.hStdError) |
| 3289 | self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE) |
| 3290 | self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []}) |
| 3291 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3292 | def test_creationflags(self): |
| 3293 | # creationflags argument |
| 3294 | CREATE_NEW_CONSOLE = 16 |
| 3295 | sys.stderr.write(" a DOS box should flash briefly ...\n") |
| 3296 | subprocess.call(sys.executable + |
| 3297 | ' -c "import time; time.sleep(0.25)"', |
| 3298 | creationflags=CREATE_NEW_CONSOLE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 3299 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3300 | def test_invalid_args(self): |
| 3301 | # invalid arguments should raise ValueError |
| 3302 | self.assertRaises(ValueError, subprocess.call, |
| 3303 | [sys.executable, "-c", |
| 3304 | "import sys; sys.exit(47)"], |
| 3305 | preexec_fn=lambda: 1) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3306 | |
Oren Milman | 0b3a87e | 2017-09-14 22:30:28 +0300 | [diff] [blame] | 3307 | @support.cpython_only |
| 3308 | def test_issue31471(self): |
| 3309 | # There shouldn't be an assertion failure in Popen() in case the env |
| 3310 | # argument has a bad keys() method. |
| 3311 | class BadEnv(dict): |
| 3312 | keys = None |
| 3313 | with self.assertRaises(TypeError): |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 3314 | subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv()) |
Oren Milman | 0b3a87e | 2017-09-14 22:30:28 +0300 | [diff] [blame] | 3315 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3316 | def test_close_fds(self): |
| 3317 | # close file descriptors |
| 3318 | rc = subprocess.call([sys.executable, "-c", |
| 3319 | "import sys; sys.exit(47)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 3320 | close_fds=True) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3321 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 3322 | |
Segev Finer | b2a6083 | 2017-12-18 11:28:19 +0200 | [diff] [blame] | 3323 | def test_close_fds_with_stdio(self): |
| 3324 | import msvcrt |
| 3325 | |
| 3326 | fds = os.pipe() |
| 3327 | self.addCleanup(os.close, fds[0]) |
| 3328 | self.addCleanup(os.close, fds[1]) |
| 3329 | |
| 3330 | handles = [] |
| 3331 | for fd in fds: |
| 3332 | os.set_inheritable(fd, True) |
| 3333 | handles.append(msvcrt.get_osfhandle(fd)) |
| 3334 | |
| 3335 | p = subprocess.Popen([sys.executable, "-c", |
| 3336 | "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])], |
| 3337 | stdout=subprocess.PIPE, close_fds=False) |
| 3338 | stdout, stderr = p.communicate() |
| 3339 | self.assertEqual(p.returncode, 0) |
| 3340 | int(stdout.strip()) # Check that stdout is an integer |
| 3341 | |
| 3342 | p = subprocess.Popen([sys.executable, "-c", |
| 3343 | "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])], |
| 3344 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) |
| 3345 | stdout, stderr = p.communicate() |
| 3346 | self.assertEqual(p.returncode, 1) |
| 3347 | self.assertIn(b"OSError", stderr) |
| 3348 | |
| 3349 | # The same as the previous call, but with an empty handle_list |
| 3350 | handle_list = [] |
| 3351 | startupinfo = subprocess.STARTUPINFO() |
| 3352 | startupinfo.lpAttributeList = {"handle_list": handle_list} |
| 3353 | p = subprocess.Popen([sys.executable, "-c", |
| 3354 | "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])], |
| 3355 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 3356 | startupinfo=startupinfo, close_fds=True) |
| 3357 | stdout, stderr = p.communicate() |
| 3358 | self.assertEqual(p.returncode, 1) |
| 3359 | self.assertIn(b"OSError", stderr) |
| 3360 | |
| 3361 | # Check for a warning due to using handle_list and close_fds=False |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 3362 | with warnings_helper.check_warnings((".*overriding close_fds", |
| 3363 | RuntimeWarning)): |
Segev Finer | b2a6083 | 2017-12-18 11:28:19 +0200 | [diff] [blame] | 3364 | startupinfo = subprocess.STARTUPINFO() |
| 3365 | startupinfo.lpAttributeList = {"handle_list": handles[:]} |
| 3366 | p = subprocess.Popen([sys.executable, "-c", |
| 3367 | "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])], |
| 3368 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 3369 | startupinfo=startupinfo, close_fds=False) |
| 3370 | stdout, stderr = p.communicate() |
| 3371 | self.assertEqual(p.returncode, 0) |
| 3372 | |
| 3373 | def test_empty_attribute_list(self): |
| 3374 | startupinfo = subprocess.STARTUPINFO() |
| 3375 | startupinfo.lpAttributeList = {} |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 3376 | subprocess.call(ZERO_RETURN_CMD, |
Segev Finer | b2a6083 | 2017-12-18 11:28:19 +0200 | [diff] [blame] | 3377 | startupinfo=startupinfo) |
| 3378 | |
| 3379 | def test_empty_handle_list(self): |
| 3380 | startupinfo = subprocess.STARTUPINFO() |
| 3381 | startupinfo.lpAttributeList = {"handle_list": []} |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 3382 | subprocess.call(ZERO_RETURN_CMD, |
Segev Finer | b2a6083 | 2017-12-18 11:28:19 +0200 | [diff] [blame] | 3383 | startupinfo=startupinfo) |
| 3384 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3385 | def test_shell_sequence(self): |
| 3386 | # Run command through the shell (sequence) |
| 3387 | newenv = os.environ.copy() |
| 3388 | newenv["FRUIT"] = "physalis" |
| 3389 | p = subprocess.Popen(["set"], shell=1, |
| 3390 | stdout=subprocess.PIPE, |
| 3391 | env=newenv) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 3392 | with p: |
| 3393 | self.assertIn(b"physalis", p.stdout.read()) |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 3394 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3395 | def test_shell_string(self): |
| 3396 | # Run command through the shell (string) |
| 3397 | newenv = os.environ.copy() |
| 3398 | newenv["FRUIT"] = "physalis" |
| 3399 | p = subprocess.Popen("set", shell=1, |
| 3400 | stdout=subprocess.PIPE, |
| 3401 | env=newenv) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 3402 | with p: |
| 3403 | self.assertIn(b"physalis", p.stdout.read()) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 3404 | |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 3405 | def test_shell_encodings(self): |
| 3406 | # Run command through the shell (string) |
| 3407 | for enc in ['ansi', 'oem']: |
| 3408 | newenv = os.environ.copy() |
| 3409 | newenv["FRUIT"] = "physalis" |
| 3410 | p = subprocess.Popen("set", shell=1, |
| 3411 | stdout=subprocess.PIPE, |
| 3412 | env=newenv, |
| 3413 | encoding=enc) |
| 3414 | with p: |
| 3415 | self.assertIn("physalis", p.stdout.read(), enc) |
| 3416 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3417 | def test_call_string(self): |
| 3418 | # call() function with string argument on Windows |
| 3419 | rc = subprocess.call(sys.executable + |
| 3420 | ' -c "import sys; sys.exit(47)"') |
| 3421 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 3422 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 3423 | def _kill_process(self, method, *args): |
| 3424 | # Some win32 buildbot raises EOFError if stdin is inherited |
Antoine Pitrou | a4024e2 | 2010-09-24 18:57:01 +0000 | [diff] [blame] | 3425 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 3426 | import sys, time |
| 3427 | sys.stdout.write('x\\n') |
| 3428 | sys.stdout.flush() |
| 3429 | time.sleep(30) |
| 3430 | """], |
| 3431 | stdin=subprocess.PIPE, |
| 3432 | stdout=subprocess.PIPE, |
| 3433 | stderr=subprocess.PIPE) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 3434 | with p: |
| 3435 | # Wait for the interpreter to be completely initialized before |
| 3436 | # sending any signal. |
| 3437 | p.stdout.read(1) |
| 3438 | getattr(p, method)(*args) |
| 3439 | _, stderr = p.communicate() |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 3440 | self.assertEqual(stderr, b'') |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 3441 | returncode = p.wait() |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 3442 | self.assertNotEqual(returncode, 0) |
| 3443 | |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 3444 | def _kill_dead_process(self, method, *args): |
| 3445 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 3446 | import sys, time |
| 3447 | sys.stdout.write('x\\n') |
| 3448 | sys.stdout.flush() |
| 3449 | sys.exit(42) |
| 3450 | """], |
| 3451 | stdin=subprocess.PIPE, |
| 3452 | stdout=subprocess.PIPE, |
| 3453 | stderr=subprocess.PIPE) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 3454 | with p: |
| 3455 | # Wait for the interpreter to be completely initialized before |
| 3456 | # sending any signal. |
| 3457 | p.stdout.read(1) |
| 3458 | # The process should end after this |
| 3459 | time.sleep(1) |
| 3460 | # This shouldn't raise even though the child is now dead |
| 3461 | getattr(p, method)(*args) |
| 3462 | _, stderr = p.communicate() |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 3463 | self.assertEqual(stderr, b'') |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 3464 | rc = p.wait() |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 3465 | self.assertEqual(rc, 42) |
| 3466 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 3467 | def test_send_signal(self): |
| 3468 | self._kill_process('send_signal', signal.SIGTERM) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 3469 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3470 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 3471 | self._kill_process('kill') |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 3472 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3473 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 3474 | self._kill_process('terminate') |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 3475 | |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 3476 | def test_send_signal_dead(self): |
| 3477 | self._kill_dead_process('send_signal', signal.SIGTERM) |
| 3478 | |
| 3479 | def test_kill_dead(self): |
| 3480 | self._kill_dead_process('kill') |
| 3481 | |
| 3482 | def test_terminate_dead(self): |
| 3483 | self._kill_dead_process('terminate') |
| 3484 | |
Martin Panter | 23172bd | 2016-04-16 11:28:10 +0000 | [diff] [blame] | 3485 | class MiscTests(unittest.TestCase): |
Gregory P. Smith | f4d644f | 2018-01-29 21:27:39 -0800 | [diff] [blame] | 3486 | |
| 3487 | class RecordingPopen(subprocess.Popen): |
| 3488 | """A Popen that saves a reference to each instance for testing.""" |
| 3489 | instances_created = [] |
| 3490 | |
| 3491 | def __init__(self, *args, **kwargs): |
| 3492 | super().__init__(*args, **kwargs) |
| 3493 | self.instances_created.append(self) |
| 3494 | |
| 3495 | @mock.patch.object(subprocess.Popen, "_communicate") |
| 3496 | def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate, |
| 3497 | **kwargs): |
| 3498 | """Fake a SIGINT happening during Popen._communicate() and ._wait(). |
| 3499 | |
| 3500 | This avoids the need to actually try and get test environments to send |
| 3501 | and receive signals reliably across platforms. The net effect of a ^C |
| 3502 | happening during a blocking subprocess execution which we want to clean |
| 3503 | up from is a KeyboardInterrupt coming out of communicate() or wait(). |
| 3504 | """ |
| 3505 | |
| 3506 | mock__communicate.side_effect = KeyboardInterrupt |
| 3507 | try: |
| 3508 | with mock.patch.object(subprocess.Popen, "_wait") as mock__wait: |
| 3509 | # We patch out _wait() as no signal was involved so the |
| 3510 | # child process isn't actually going to exit rapidly. |
| 3511 | mock__wait.side_effect = KeyboardInterrupt |
| 3512 | with mock.patch.object(subprocess, "Popen", |
| 3513 | self.RecordingPopen): |
| 3514 | with self.assertRaises(KeyboardInterrupt): |
| 3515 | popener([sys.executable, "-c", |
| 3516 | "import time\ntime.sleep(9)\nimport sys\n" |
| 3517 | "sys.stderr.write('\\n!runaway child!\\n')"], |
| 3518 | stdout=subprocess.DEVNULL, **kwargs) |
| 3519 | for call in mock__wait.call_args_list[1:]: |
| 3520 | self.assertNotEqual( |
| 3521 | call, mock.call(timeout=None), |
| 3522 | "no open-ended wait() after the first allowed: " |
| 3523 | f"{mock__wait.call_args_list}") |
| 3524 | sigint_calls = [] |
| 3525 | for call in mock__wait.call_args_list: |
| 3526 | if call == mock.call(timeout=0.25): # from Popen.__init__ |
| 3527 | sigint_calls.append(call) |
| 3528 | self.assertLessEqual(mock__wait.call_count, 2, |
| 3529 | msg=mock__wait.call_args_list) |
| 3530 | self.assertEqual(len(sigint_calls), 1, |
| 3531 | msg=mock__wait.call_args_list) |
| 3532 | finally: |
| 3533 | # cleanup the forgotten (due to our mocks) child process |
| 3534 | process = self.RecordingPopen.instances_created.pop() |
| 3535 | process.kill() |
| 3536 | process.wait() |
| 3537 | self.assertEqual([], self.RecordingPopen.instances_created) |
| 3538 | |
| 3539 | def test_call_keyboardinterrupt_no_kill(self): |
| 3540 | self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282) |
| 3541 | |
| 3542 | def test_run_keyboardinterrupt_no_kill(self): |
| 3543 | self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282) |
| 3544 | |
| 3545 | def test_context_manager_keyboardinterrupt_no_kill(self): |
| 3546 | def popen_via_context_manager(*args, **kwargs): |
| 3547 | with subprocess.Popen(*args, **kwargs) as unused_process: |
| 3548 | raise KeyboardInterrupt # Test how __exit__ handles ^C. |
| 3549 | self._test_keyboardinterrupt_no_kill(popen_via_context_manager) |
| 3550 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3551 | def test_getoutput(self): |
| 3552 | self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy') |
| 3553 | self.assertEqual(subprocess.getstatusoutput('echo xyzzy'), |
| 3554 | (0, 'xyzzy')) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 3555 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3556 | # we use mkdtemp in the next line to create an empty directory |
| 3557 | # under our exclusive control; from that, we can invent a pathname |
| 3558 | # that we _know_ won't exist. This is guaranteed to fail. |
| 3559 | dir = None |
| 3560 | try: |
| 3561 | dir = tempfile.mkdtemp() |
| 3562 | name = os.path.join(dir, "foo") |
Tim Golden | e004175 | 2013-11-03 12:53:17 +0000 | [diff] [blame] | 3563 | status, output = subprocess.getstatusoutput( |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 3564 | ("type " if mswindows else "cat ") + name) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 3565 | self.assertNotEqual(status, 0) |
| 3566 | finally: |
| 3567 | if dir is not None: |
| 3568 | os.rmdir(dir) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 3569 | |
Gregory P. Smith | ace5586 | 2015-04-07 15:57:54 -0700 | [diff] [blame] | 3570 | def test__all__(self): |
| 3571 | """Ensure that __all__ is populated properly.""" |
Ruben Vorderman | 23c0fb8 | 2020-10-20 01:30:02 +0200 | [diff] [blame] | 3572 | intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp", "fcntl"} |
Gregory P. Smith | ace5586 | 2015-04-07 15:57:54 -0700 | [diff] [blame] | 3573 | exported = set(subprocess.__all__) |
| 3574 | possible_exports = set() |
| 3575 | import types |
| 3576 | for name, value in subprocess.__dict__.items(): |
| 3577 | if name.startswith('_'): |
| 3578 | continue |
| 3579 | if isinstance(value, (types.ModuleType,)): |
| 3580 | continue |
| 3581 | possible_exports.add(name) |
| 3582 | self.assertEqual(exported, possible_exports - intentionally_excluded) |
| 3583 | |
| 3584 | |
Martin Panter | 23172bd | 2016-04-16 11:28:10 +0000 | [diff] [blame] | 3585 | @unittest.skipUnless(hasattr(selectors, 'PollSelector'), |
| 3586 | "Test needs selectors.PollSelector") |
| 3587 | class ProcessTestCaseNoPoll(ProcessTestCase): |
| 3588 | def setUp(self): |
| 3589 | self.orig_selector = subprocess._PopenSelector |
| 3590 | subprocess._PopenSelector = selectors.SelectSelector |
| 3591 | ProcessTestCase.setUp(self) |
| 3592 | |
| 3593 | def tearDown(self): |
| 3594 | subprocess._PopenSelector = self.orig_selector |
| 3595 | ProcessTestCase.tearDown(self) |
| 3596 | |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 3597 | |
Victor Stinner | 937ee9e | 2018-06-26 02:11:06 +0200 | [diff] [blame] | 3598 | @unittest.skipUnless(mswindows, "Windows-specific tests") |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 3599 | class CommandsWithSpaces (BaseTestCase): |
| 3600 | |
| 3601 | def setUp(self): |
| 3602 | super().setUp() |
Berker Peksag | 16a1f28 | 2015-09-28 13:33:14 +0300 | [diff] [blame] | 3603 | f, fname = tempfile.mkstemp(".py", "te st") |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 3604 | self.fname = fname.lower () |
| 3605 | os.write(f, b"import sys;" |
| 3606 | b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))" |
| 3607 | ) |
| 3608 | os.close(f) |
| 3609 | |
| 3610 | def tearDown(self): |
| 3611 | os.remove(self.fname) |
| 3612 | super().tearDown() |
| 3613 | |
| 3614 | def with_spaces(self, *args, **kwargs): |
| 3615 | kwargs['stdout'] = subprocess.PIPE |
| 3616 | p = subprocess.Popen(*args, **kwargs) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 3617 | with p: |
| 3618 | self.assertEqual( |
| 3619 | p.stdout.read ().decode("mbcs"), |
| 3620 | "2 [%r, 'ab cd']" % self.fname |
| 3621 | ) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 3622 | |
| 3623 | def test_shell_string_with_spaces(self): |
| 3624 | # call() function with string argument with spaces on Windows |
Brian Curtin | d835cf1 | 2010-08-13 20:42:57 +0000 | [diff] [blame] | 3625 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 3626 | "ab cd"), shell=1) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 3627 | |
| 3628 | def test_shell_sequence_with_spaces(self): |
| 3629 | # call() function with sequence argument with spaces on Windows |
Brian Curtin | d835cf1 | 2010-08-13 20:42:57 +0000 | [diff] [blame] | 3630 | self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 3631 | |
| 3632 | def test_noshell_string_with_spaces(self): |
| 3633 | # call() function with string argument with spaces on Windows |
| 3634 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 3635 | "ab cd")) |
| 3636 | |
| 3637 | def test_noshell_sequence_with_spaces(self): |
| 3638 | # call() function with sequence argument with spaces on Windows |
| 3639 | self.with_spaces([sys.executable, self.fname, "ab cd"]) |
| 3640 | |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 3641 | |
Georg Brandl | a86b262 | 2012-02-20 21:34:57 +0100 | [diff] [blame] | 3642 | class ContextManagerTests(BaseTestCase): |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 3643 | |
| 3644 | def test_pipe(self): |
| 3645 | with subprocess.Popen([sys.executable, "-c", |
| 3646 | "import sys;" |
| 3647 | "sys.stdout.write('stdout');" |
| 3648 | "sys.stderr.write('stderr');"], |
| 3649 | stdout=subprocess.PIPE, |
| 3650 | stderr=subprocess.PIPE) as proc: |
| 3651 | self.assertEqual(proc.stdout.read(), b"stdout") |
Victor Stinner | 6cac113 | 2019-12-08 08:38:16 +0100 | [diff] [blame] | 3652 | self.assertEqual(proc.stderr.read(), b"stderr") |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 3653 | |
| 3654 | self.assertTrue(proc.stdout.closed) |
| 3655 | self.assertTrue(proc.stderr.closed) |
| 3656 | |
| 3657 | def test_returncode(self): |
| 3658 | with subprocess.Popen([sys.executable, "-c", |
| 3659 | "import sys; sys.exit(100)"]) as proc: |
Gregory P. Smith | 6b65745 | 2011-05-11 21:42:08 -0700 | [diff] [blame] | 3660 | pass |
| 3661 | # __exit__ calls wait(), so the returncode should be set |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 3662 | self.assertEqual(proc.returncode, 100) |
| 3663 | |
| 3664 | def test_communicate_stdin(self): |
| 3665 | with subprocess.Popen([sys.executable, "-c", |
| 3666 | "import sys;" |
| 3667 | "sys.exit(sys.stdin.read() == 'context')"], |
| 3668 | stdin=subprocess.PIPE) as proc: |
| 3669 | proc.communicate(b"context") |
| 3670 | self.assertEqual(proc.returncode, 1) |
| 3671 | |
| 3672 | def test_invalid_args(self): |
Victor Stinner | b31206a | 2018-01-25 19:06:05 +0100 | [diff] [blame] | 3673 | with self.assertRaises(NONEXISTING_ERRORS): |
Victor Stinner | 9a83f65 | 2017-08-21 23:51:31 +0200 | [diff] [blame] | 3674 | with subprocess.Popen(NONEXISTING_CMD, |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 3675 | stdout=subprocess.PIPE, |
| 3676 | stderr=subprocess.PIPE) as proc: |
| 3677 | pass |
| 3678 | |
Serhiy Storchaka | ab900c2 | 2015-02-28 12:43:08 +0200 | [diff] [blame] | 3679 | def test_broken_pipe_cleanup(self): |
| 3680 | """Broken pipe error should not prevent wait() (Issue 21619)""" |
Gregory P. Smith | 67b93f8 | 2019-10-12 16:35:53 -0700 | [diff] [blame] | 3681 | proc = subprocess.Popen(ZERO_RETURN_CMD, |
Victor Stinner | 20f4bd4 | 2015-03-05 02:38:41 +0100 | [diff] [blame] | 3682 | stdin=subprocess.PIPE, |
Victor Stinner | 20f4bd4 | 2015-03-05 02:38:41 +0100 | [diff] [blame] | 3683 | bufsize=support.PIPE_MAX_SIZE*2) |
Serhiy Storchaka | f87afb0 | 2015-03-08 09:16:40 +0200 | [diff] [blame] | 3684 | proc = proc.__enter__() |
| 3685 | # Prepare to send enough data to overflow any OS pipe buffering and |
| 3686 | # guarantee a broken pipe error. Data is held in BufferedWriter |
| 3687 | # buffer until closed. |
| 3688 | proc.stdin.write(b'x' * support.PIPE_MAX_SIZE) |
Serhiy Storchaka | ab900c2 | 2015-02-28 12:43:08 +0200 | [diff] [blame] | 3689 | self.assertIsNone(proc.returncode) |
Serhiy Storchaka | f87afb0 | 2015-03-08 09:16:40 +0200 | [diff] [blame] | 3690 | # EPIPE expected under POSIX; EINVAL under Windows |
Serhiy Storchaka | cf265fd | 2015-02-28 13:27:54 +0200 | [diff] [blame] | 3691 | self.assertRaises(OSError, proc.__exit__, None, None, None) |
Serhiy Storchaka | f87afb0 | 2015-03-08 09:16:40 +0200 | [diff] [blame] | 3692 | self.assertEqual(proc.returncode, 0) |
Serhiy Storchaka | ab900c2 | 2015-02-28 12:43:08 +0200 | [diff] [blame] | 3693 | self.assertTrue(proc.stdin.closed) |
Serhiy Storchaka | ab900c2 | 2015-02-28 12:43:08 +0200 | [diff] [blame] | 3694 | |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 3695 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 3696 | if __name__ == "__main__": |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 3697 | unittest.main() |