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