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