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