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