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