Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1 | import unittest |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 2 | from test import script_helper |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 3 | from test import support |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 4 | import subprocess |
| 5 | import sys |
| 6 | import signal |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 7 | import io |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 8 | import locale |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 9 | import os |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 10 | import errno |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 11 | import tempfile |
| 12 | import time |
Tim Peters | 3761e8d | 2004-10-13 04:07:12 +0000 | [diff] [blame] | 13 | import re |
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 | d23047b | 2010-12-04 09:10:44 +0000 | [diff] [blame] | 16 | import warnings |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 17 | import select |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 18 | import shutil |
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 |
Benjamin Peterson | 964561b | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 21 | |
| 22 | try: |
Antoine Pitrou | a839271 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 23 | import threading |
| 24 | except ImportError: |
| 25 | threading = None |
Benjamin Peterson | 964561b | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 26 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 27 | mswindows = (sys.platform == "win32") |
| 28 | |
| 29 | # |
| 30 | # Depends on the following external programs: Python |
| 31 | # |
| 32 | |
| 33 | if mswindows: |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 34 | SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), ' |
| 35 | 'os.O_BINARY);') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 36 | else: |
| 37 | SETBINARY = '' |
| 38 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 39 | |
| 40 | try: |
| 41 | mkstemp = tempfile.mkstemp |
| 42 | except AttributeError: |
| 43 | # tempfile.mkstemp is not available |
| 44 | def mkstemp(): |
| 45 | """Replacement for mkstemp, calling mktemp.""" |
| 46 | fname = tempfile.mktemp() |
| 47 | return os.open(fname, os.O_RDWR|os.O_CREAT), fname |
| 48 | |
Tim Peters | 3761e8d | 2004-10-13 04:07:12 +0000 | [diff] [blame] | 49 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 50 | class BaseTestCase(unittest.TestCase): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 51 | def setUp(self): |
| 52 | # Try to minimize the number of children we have so this test |
| 53 | # doesn't crash on some buildbots (Alphas in particular). |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 54 | support.reap_children() |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 55 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 56 | def tearDown(self): |
| 57 | for inst in subprocess._active: |
| 58 | inst.wait() |
| 59 | subprocess._cleanup() |
| 60 | self.assertFalse(subprocess._active, "subprocess._active not empty") |
| 61 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 62 | def assertStderrEqual(self, stderr, expected, msg=None): |
| 63 | # In a debug build, stuff like "[6580 refs]" is printed to stderr at |
| 64 | # shutdown time. That frustrates tests trying to check stderr produced |
| 65 | # from a spawned Python process. |
Antoine Pitrou | 62f68ed | 2010-08-04 11:48:56 +0000 | [diff] [blame] | 66 | actual = support.strip_python_stderr(stderr) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 67 | # strip_python_stderr also strips whitespace, so we do too. |
| 68 | expected = expected.strip() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 69 | self.assertEqual(actual, expected, msg) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 70 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 71 | |
Gregory P. Smith | 3d8e776 | 2012-11-10 22:32:22 -0800 | [diff] [blame] | 72 | class PopenTestException(Exception): |
| 73 | pass |
| 74 | |
| 75 | |
| 76 | class PopenExecuteChildRaises(subprocess.Popen): |
| 77 | """Popen subclass for testing cleanup of subprocess.PIPE filehandles when |
| 78 | _execute_child fails. |
| 79 | """ |
| 80 | def _execute_child(self, *args, **kwargs): |
| 81 | raise PopenTestException("Forced Exception for Test") |
| 82 | |
| 83 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 84 | class ProcessTestCase(BaseTestCase): |
| 85 | |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 86 | def test_io_buffered_by_default(self): |
| 87 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 88 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 89 | stderr=subprocess.PIPE) |
| 90 | try: |
| 91 | self.assertIsInstance(p.stdin, io.BufferedIOBase) |
| 92 | self.assertIsInstance(p.stdout, io.BufferedIOBase) |
| 93 | self.assertIsInstance(p.stderr, io.BufferedIOBase) |
| 94 | finally: |
Gregory P. Smith | a1b9ed3 | 2013-03-23 11:54:22 -0700 | [diff] [blame] | 95 | p.stdin.close() |
| 96 | p.stdout.close() |
| 97 | p.stderr.close() |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 98 | p.wait() |
| 99 | |
| 100 | def test_io_unbuffered_works(self): |
| 101 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 102 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 103 | stderr=subprocess.PIPE, bufsize=0) |
| 104 | try: |
| 105 | self.assertIsInstance(p.stdin, io.RawIOBase) |
| 106 | self.assertIsInstance(p.stdout, io.RawIOBase) |
| 107 | self.assertIsInstance(p.stderr, io.RawIOBase) |
| 108 | finally: |
Gregory P. Smith | a1b9ed3 | 2013-03-23 11:54:22 -0700 | [diff] [blame] | 109 | p.stdin.close() |
| 110 | p.stdout.close() |
| 111 | p.stderr.close() |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 112 | p.wait() |
| 113 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 114 | def test_call_seq(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 115 | # call() function with sequence argument |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 116 | rc = subprocess.call([sys.executable, "-c", |
| 117 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 118 | self.assertEqual(rc, 47) |
| 119 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 120 | def test_call_timeout(self): |
| 121 | # call() function with timeout argument; we want to test that the child |
| 122 | # process gets killed when the timeout expires. If the child isn't |
| 123 | # killed, this call will deadlock since subprocess.call waits for the |
| 124 | # child. |
| 125 | self.assertRaises(subprocess.TimeoutExpired, subprocess.call, |
| 126 | [sys.executable, "-c", "while True: pass"], |
| 127 | timeout=0.1) |
| 128 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 129 | def test_check_call_zero(self): |
| 130 | # check_call() function with zero return code |
| 131 | rc = subprocess.check_call([sys.executable, "-c", |
| 132 | "import sys; sys.exit(0)"]) |
| 133 | self.assertEqual(rc, 0) |
| 134 | |
| 135 | def test_check_call_nonzero(self): |
| 136 | # check_call() function with non-zero return code |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 137 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 138 | subprocess.check_call([sys.executable, "-c", |
| 139 | "import sys; sys.exit(47)"]) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 140 | self.assertEqual(c.exception.returncode, 47) |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 141 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 142 | def test_check_output(self): |
| 143 | # check_output() function with zero return code |
| 144 | output = subprocess.check_output( |
| 145 | [sys.executable, "-c", "print('BDFL')"]) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 146 | self.assertIn(b'BDFL', output) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 147 | |
| 148 | def test_check_output_nonzero(self): |
| 149 | # check_call() function with non-zero return code |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 150 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 151 | subprocess.check_output( |
| 152 | [sys.executable, "-c", "import sys; sys.exit(5)"]) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 153 | self.assertEqual(c.exception.returncode, 5) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 154 | |
| 155 | def test_check_output_stderr(self): |
| 156 | # check_output() function stderr redirected to stdout |
| 157 | output = subprocess.check_output( |
| 158 | [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"], |
| 159 | stderr=subprocess.STDOUT) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 160 | self.assertIn(b'BDFL', output) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 161 | |
Serhiy Storchaka | fcd9f22 | 2013-04-22 20:20:54 +0300 | [diff] [blame] | 162 | def test_check_output_stdin_arg(self): |
| 163 | # check_output() can be called with stdin set to a file |
| 164 | tf = tempfile.TemporaryFile() |
| 165 | self.addCleanup(tf.close) |
| 166 | tf.write(b'pear') |
| 167 | tf.seek(0) |
| 168 | output = subprocess.check_output( |
| 169 | [sys.executable, "-c", |
| 170 | "import sys; sys.stdout.write(sys.stdin.read().upper())"], |
| 171 | stdin=tf) |
| 172 | self.assertIn(b'PEAR', output) |
| 173 | |
| 174 | def test_check_output_input_arg(self): |
| 175 | # check_output() can be called with input set to a string |
| 176 | output = subprocess.check_output( |
| 177 | [sys.executable, "-c", |
| 178 | "import sys; sys.stdout.write(sys.stdin.read().upper())"], |
| 179 | input=b'pear') |
| 180 | self.assertIn(b'PEAR', output) |
| 181 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 182 | def test_check_output_stdout_arg(self): |
Serhiy Storchaka | fcd9f22 | 2013-04-22 20:20:54 +0300 | [diff] [blame] | 183 | # check_output() refuses to accept 'stdout' argument |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 184 | with self.assertRaises(ValueError) as c: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 185 | output = subprocess.check_output( |
| 186 | [sys.executable, "-c", "print('will not be run')"], |
| 187 | stdout=sys.stdout) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 188 | self.fail("Expected ValueError when stdout arg supplied.") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 189 | self.assertIn('stdout', c.exception.args[0]) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 190 | |
Serhiy Storchaka | fcd9f22 | 2013-04-22 20:20:54 +0300 | [diff] [blame] | 191 | def test_check_output_stdin_with_input_arg(self): |
| 192 | # check_output() refuses to accept 'stdin' with 'input' |
| 193 | tf = tempfile.TemporaryFile() |
| 194 | self.addCleanup(tf.close) |
| 195 | tf.write(b'pear') |
| 196 | tf.seek(0) |
| 197 | with self.assertRaises(ValueError) as c: |
| 198 | output = subprocess.check_output( |
| 199 | [sys.executable, "-c", "print('will not be run')"], |
| 200 | stdin=tf, input=b'hare') |
| 201 | self.fail("Expected ValueError when stdin and input args supplied.") |
| 202 | self.assertIn('stdin', c.exception.args[0]) |
| 203 | self.assertIn('input', c.exception.args[0]) |
| 204 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 205 | def test_check_output_timeout(self): |
| 206 | # check_output() function with timeout arg |
| 207 | with self.assertRaises(subprocess.TimeoutExpired) as c: |
| 208 | output = subprocess.check_output( |
| 209 | [sys.executable, "-c", |
Victor Stinner | 149b1c7 | 2011-06-06 23:43:02 +0200 | [diff] [blame] | 210 | "import sys, time\n" |
| 211 | "sys.stdout.write('BDFL')\n" |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 212 | "sys.stdout.flush()\n" |
Victor Stinner | 149b1c7 | 2011-06-06 23:43:02 +0200 | [diff] [blame] | 213 | "time.sleep(3600)"], |
Reid Kleckner | da9ac72 | 2011-03-16 17:08:21 -0400 | [diff] [blame] | 214 | # Some heavily loaded buildbots (sparc Debian 3.x) require |
| 215 | # this much time to start and print. |
| 216 | timeout=3) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 217 | self.fail("Expected TimeoutExpired.") |
| 218 | self.assertEqual(c.exception.output, b'BDFL') |
| 219 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 220 | def test_call_kwargs(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 221 | # call() function with keyword args |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 222 | newenv = os.environ.copy() |
| 223 | newenv["FRUIT"] = "banana" |
| 224 | rc = subprocess.call([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 225 | 'import sys, os;' |
| 226 | 'sys.exit(os.getenv("FRUIT")=="banana")'], |
| 227 | env=newenv) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 228 | self.assertEqual(rc, 1) |
| 229 | |
Victor Stinner | 87b9bc3 | 2011-06-01 00:57:47 +0200 | [diff] [blame] | 230 | def test_invalid_args(self): |
| 231 | # Popen() called with invalid arguments should raise TypeError |
| 232 | # but Popen.__del__ should not complain (issue #12085) |
| 233 | with support.captured_stderr() as s: |
| 234 | self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1) |
| 235 | argcount = subprocess.Popen.__init__.__code__.co_argcount |
| 236 | too_many_args = [0] * (argcount + 1) |
| 237 | self.assertRaises(TypeError, subprocess.Popen, *too_many_args) |
| 238 | self.assertEqual(s.getvalue(), '') |
| 239 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 240 | def test_stdin_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 241 | # .stdin is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 242 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 243 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 244 | self.addCleanup(p.stdout.close) |
| 245 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 246 | p.wait() |
| 247 | self.assertEqual(p.stdin, None) |
| 248 | |
| 249 | def test_stdout_none(self): |
Ezio Melotti | 42a541b | 2013-03-11 05:53:34 +0200 | [diff] [blame] | 250 | # .stdout is None when not redirected, and the child's stdout will |
| 251 | # be inherited from the parent. In order to test this we run a |
| 252 | # subprocess in a subprocess: |
| 253 | # this_test |
| 254 | # \-- subprocess created by this test (parent) |
| 255 | # \-- subprocess created by the parent subprocess (child) |
| 256 | # The parent doesn't specify stdout, so the child will use the |
| 257 | # parent's stdout. This test checks that the message printed by the |
| 258 | # child goes to the parent stdout. The parent also checks that the |
| 259 | # child's stdout is None. See #11963. |
| 260 | code = ('import sys; from subprocess import Popen, PIPE;' |
| 261 | 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],' |
| 262 | ' stdin=PIPE, stderr=PIPE);' |
| 263 | 'p.wait(); assert p.stdout is None;') |
| 264 | p = subprocess.Popen([sys.executable, "-c", code], |
| 265 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 266 | self.addCleanup(p.stdout.close) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 267 | self.addCleanup(p.stderr.close) |
Ezio Melotti | 42a541b | 2013-03-11 05:53:34 +0200 | [diff] [blame] | 268 | out, err = p.communicate() |
| 269 | self.assertEqual(p.returncode, 0, err) |
| 270 | self.assertEqual(out.rstrip(), b'test_stdout_none') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 271 | |
| 272 | def test_stderr_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 273 | # .stderr is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 274 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 275 | stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 276 | self.addCleanup(p.stdout.close) |
| 277 | self.addCleanup(p.stdin.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 278 | p.wait() |
| 279 | self.assertEqual(p.stderr, None) |
| 280 | |
Chris Jerdonek | 776cb19 | 2012-10-08 15:56:43 -0700 | [diff] [blame] | 281 | def _assert_python(self, pre_args, **kwargs): |
| 282 | # We include sys.exit() to prevent the test runner from hanging |
| 283 | # whenever python is found. |
| 284 | args = pre_args + ["import sys; sys.exit(47)"] |
| 285 | p = subprocess.Popen(args, **kwargs) |
| 286 | p.wait() |
| 287 | self.assertEqual(47, p.returncode) |
| 288 | |
| 289 | def test_executable(self): |
| 290 | # Check that the executable argument works. |
Chris Jerdonek | 86b0fb2 | 2012-10-09 13:17:49 -0700 | [diff] [blame] | 291 | # |
| 292 | # On Unix (non-Mac and non-Windows), Python looks at args[0] to |
| 293 | # determine where its standard library is, so we need the directory |
| 294 | # of args[0] to be valid for the Popen() call to Python to succeed. |
| 295 | # See also issue #16170 and issue #7774. |
| 296 | doesnotexist = os.path.join(os.path.dirname(sys.executable), |
| 297 | "doesnotexist") |
| 298 | self._assert_python([doesnotexist, "-c"], executable=sys.executable) |
Chris Jerdonek | 776cb19 | 2012-10-08 15:56:43 -0700 | [diff] [blame] | 299 | |
| 300 | def test_executable_takes_precedence(self): |
| 301 | # Check that the executable argument takes precedence over args[0]. |
| 302 | # |
| 303 | # Verify first that the call succeeds without the executable arg. |
| 304 | pre_args = [sys.executable, "-c"] |
| 305 | self._assert_python(pre_args) |
| 306 | self.assertRaises(FileNotFoundError, self._assert_python, pre_args, |
| 307 | executable="doesnotexist") |
| 308 | |
| 309 | @unittest.skipIf(mswindows, "executable argument replaces shell") |
| 310 | def test_executable_replaces_shell(self): |
| 311 | # Check that the executable argument replaces the default shell |
| 312 | # when shell=True. |
| 313 | self._assert_python([], executable=sys.executable, shell=True) |
| 314 | |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 315 | # For use in the test_cwd* tests below. |
| 316 | def _normalize_cwd(self, cwd): |
| 317 | # Normalize an expected cwd (for Tru64 support). |
| 318 | # We can't use os.path.realpath since it doesn't expand Tru64 {memb} |
| 319 | # strings. See bug #1063571. |
| 320 | original_cwd = os.getcwd() |
| 321 | os.chdir(cwd) |
| 322 | cwd = os.getcwd() |
| 323 | os.chdir(original_cwd) |
| 324 | return cwd |
| 325 | |
| 326 | # For use in the test_cwd* tests below. |
| 327 | def _split_python_path(self): |
| 328 | # Return normalized (python_dir, python_base). |
| 329 | python_path = os.path.realpath(sys.executable) |
| 330 | return os.path.split(python_path) |
| 331 | |
| 332 | # For use in the test_cwd* tests below. |
| 333 | def _assert_cwd(self, expected_cwd, python_arg, **kwargs): |
| 334 | # Invoke Python via Popen, and assert that (1) the call succeeds, |
| 335 | # and that (2) the current working directory of the child process |
| 336 | # matches *expected_cwd*. |
| 337 | p = subprocess.Popen([python_arg, "-c", |
| 338 | "import os, sys; " |
| 339 | "sys.stdout.write(os.getcwd()); " |
| 340 | "sys.exit(47)"], |
| 341 | stdout=subprocess.PIPE, |
| 342 | **kwargs) |
| 343 | self.addCleanup(p.stdout.close) |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 344 | p.wait() |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 345 | self.assertEqual(47, p.returncode) |
| 346 | normcase = os.path.normcase |
| 347 | self.assertEqual(normcase(expected_cwd), |
| 348 | normcase(p.stdout.read().decode("utf-8"))) |
| 349 | |
| 350 | def test_cwd(self): |
| 351 | # Check that cwd changes the cwd for the child process. |
| 352 | temp_dir = tempfile.gettempdir() |
| 353 | temp_dir = self._normalize_cwd(temp_dir) |
| 354 | self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir) |
| 355 | |
Chris Jerdonek | c2cd626 | 2012-09-30 09:45:00 -0700 | [diff] [blame] | 356 | @unittest.skipIf(mswindows, "pending resolution of issue #15533") |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 357 | def test_cwd_with_relative_arg(self): |
| 358 | # Check that Popen looks for args[0] relative to cwd if args[0] |
| 359 | # is relative. |
| 360 | python_dir, python_base = self._split_python_path() |
| 361 | rel_python = os.path.join(os.curdir, python_base) |
| 362 | with support.temp_cwd() as wrong_dir: |
| 363 | # Before calling with the correct cwd, confirm that the call fails |
| 364 | # without cwd and with the wrong cwd. |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 365 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 366 | [rel_python]) |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 367 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 368 | [rel_python], cwd=wrong_dir) |
| 369 | python_dir = self._normalize_cwd(python_dir) |
| 370 | self._assert_cwd(python_dir, rel_python, cwd=python_dir) |
| 371 | |
Chris Jerdonek | c2cd626 | 2012-09-30 09:45:00 -0700 | [diff] [blame] | 372 | @unittest.skipIf(mswindows, "pending resolution of issue #15533") |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 373 | def test_cwd_with_relative_executable(self): |
| 374 | # Check that Popen looks for executable relative to cwd if executable |
| 375 | # is relative (and that executable takes precedence over args[0]). |
| 376 | python_dir, python_base = self._split_python_path() |
| 377 | rel_python = os.path.join(os.curdir, python_base) |
| 378 | doesntexist = "somethingyoudonthave" |
| 379 | with support.temp_cwd() as wrong_dir: |
| 380 | # Before calling with the correct cwd, confirm that the call fails |
| 381 | # without cwd and with the wrong cwd. |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 382 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 383 | [doesntexist], executable=rel_python) |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 384 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 385 | [doesntexist], executable=rel_python, |
| 386 | cwd=wrong_dir) |
| 387 | python_dir = self._normalize_cwd(python_dir) |
| 388 | self._assert_cwd(python_dir, doesntexist, executable=rel_python, |
| 389 | cwd=python_dir) |
| 390 | |
| 391 | def test_cwd_with_absolute_arg(self): |
| 392 | # Check that Popen can find the executable when the cwd is wrong |
| 393 | # if args[0] is an absolute path. |
| 394 | python_dir, python_base = self._split_python_path() |
| 395 | abs_python = os.path.join(python_dir, python_base) |
| 396 | rel_python = os.path.join(os.curdir, python_base) |
| 397 | with script_helper.temp_dir() as wrong_dir: |
| 398 | # Before calling with an absolute path, confirm that using a |
| 399 | # relative path fails. |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 400 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 401 | [rel_python], cwd=wrong_dir) |
| 402 | wrong_dir = self._normalize_cwd(wrong_dir) |
| 403 | self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir) |
| 404 | |
Vinay Sajip | 7ded1f0 | 2012-05-26 03:45:29 +0100 | [diff] [blame] | 405 | @unittest.skipIf(sys.base_prefix != sys.prefix, |
| 406 | 'Test is not venv-compatible') |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 407 | def test_executable_with_cwd(self): |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 408 | python_dir, python_base = self._split_python_path() |
| 409 | python_dir = self._normalize_cwd(python_dir) |
| 410 | self._assert_cwd(python_dir, "somethingyoudonthave", |
| 411 | executable=sys.executable, cwd=python_dir) |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 412 | |
Vinay Sajip | 7ded1f0 | 2012-05-26 03:45:29 +0100 | [diff] [blame] | 413 | @unittest.skipIf(sys.base_prefix != sys.prefix, |
| 414 | 'Test is not venv-compatible') |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 415 | @unittest.skipIf(sysconfig.is_python_build(), |
| 416 | "need an installed Python. See #7774") |
| 417 | def test_executable_without_cwd(self): |
| 418 | # For a normal installation, it should work without 'cwd' |
| 419 | # argument. For test runs in the build directory, see #7774. |
Ned Deily | e92dfbf | 2013-08-02 18:02:21 -0700 | [diff] [blame] | 420 | self._assert_cwd(os.getcwd(), "somethingyoudonthave", |
| 421 | executable=sys.executable) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 422 | |
| 423 | def test_stdin_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 424 | # stdin redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 425 | p = subprocess.Popen([sys.executable, "-c", |
| 426 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 427 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 428 | p.stdin.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 429 | p.stdin.close() |
| 430 | p.wait() |
| 431 | self.assertEqual(p.returncode, 1) |
| 432 | |
| 433 | def test_stdin_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 434 | # stdin is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 435 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 436 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 437 | d = tf.fileno() |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 438 | os.write(d, b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 439 | os.lseek(d, 0, 0) |
| 440 | p = subprocess.Popen([sys.executable, "-c", |
| 441 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 442 | stdin=d) |
| 443 | p.wait() |
| 444 | self.assertEqual(p.returncode, 1) |
| 445 | |
| 446 | def test_stdin_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 447 | # stdin is set to open file object |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 448 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 449 | self.addCleanup(tf.close) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 450 | tf.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 451 | tf.seek(0) |
| 452 | p = subprocess.Popen([sys.executable, "-c", |
| 453 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 454 | stdin=tf) |
| 455 | p.wait() |
| 456 | self.assertEqual(p.returncode, 1) |
| 457 | |
| 458 | def test_stdout_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 459 | # stdout redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 460 | p = subprocess.Popen([sys.executable, "-c", |
| 461 | 'import sys; sys.stdout.write("orange")'], |
| 462 | stdout=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 463 | self.addCleanup(p.stdout.close) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 464 | self.assertEqual(p.stdout.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 465 | |
| 466 | def test_stdout_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 467 | # stdout is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 468 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 469 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 470 | d = tf.fileno() |
| 471 | p = subprocess.Popen([sys.executable, "-c", |
| 472 | 'import sys; sys.stdout.write("orange")'], |
| 473 | stdout=d) |
| 474 | p.wait() |
| 475 | os.lseek(d, 0, 0) |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 476 | self.assertEqual(os.read(d, 1024), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 477 | |
| 478 | def test_stdout_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 479 | # stdout is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 480 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 481 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 482 | p = subprocess.Popen([sys.executable, "-c", |
| 483 | 'import sys; sys.stdout.write("orange")'], |
| 484 | stdout=tf) |
| 485 | p.wait() |
| 486 | tf.seek(0) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 487 | self.assertEqual(tf.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 488 | |
| 489 | def test_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 490 | # stderr redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 491 | p = subprocess.Popen([sys.executable, "-c", |
| 492 | 'import sys; sys.stderr.write("strawberry")'], |
| 493 | stderr=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 494 | self.addCleanup(p.stderr.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 495 | self.assertStderrEqual(p.stderr.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 496 | |
| 497 | def test_stderr_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 498 | # stderr is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 499 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 500 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 501 | d = tf.fileno() |
| 502 | p = subprocess.Popen([sys.executable, "-c", |
| 503 | 'import sys; sys.stderr.write("strawberry")'], |
| 504 | stderr=d) |
| 505 | p.wait() |
| 506 | os.lseek(d, 0, 0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 507 | self.assertStderrEqual(os.read(d, 1024), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 508 | |
| 509 | def test_stderr_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 510 | # stderr is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 511 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 512 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 513 | p = subprocess.Popen([sys.executable, "-c", |
| 514 | 'import sys; sys.stderr.write("strawberry")'], |
| 515 | stderr=tf) |
| 516 | p.wait() |
| 517 | tf.seek(0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 518 | self.assertStderrEqual(tf.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 519 | |
| 520 | def test_stdout_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 521 | # capture stdout and stderr to the same pipe |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 522 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 523 | 'import sys;' |
| 524 | 'sys.stdout.write("apple");' |
| 525 | 'sys.stdout.flush();' |
| 526 | 'sys.stderr.write("orange")'], |
| 527 | stdout=subprocess.PIPE, |
| 528 | stderr=subprocess.STDOUT) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 529 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 530 | self.assertStderrEqual(p.stdout.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 531 | |
| 532 | def test_stdout_stderr_file(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 533 | # capture stdout and stderr to the same open file |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 534 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 535 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 536 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 537 | 'import sys;' |
| 538 | 'sys.stdout.write("apple");' |
| 539 | 'sys.stdout.flush();' |
| 540 | 'sys.stderr.write("orange")'], |
| 541 | stdout=tf, |
| 542 | stderr=tf) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 543 | p.wait() |
| 544 | tf.seek(0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 545 | self.assertStderrEqual(tf.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 546 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 547 | def test_stdout_filedes_of_stdout(self): |
| 548 | # stdout is set to 1 (#1531862). |
Ezio Melotti | 42a541b | 2013-03-11 05:53:34 +0200 | [diff] [blame] | 549 | # To avoid printing the text on stdout, we do something similar to |
| 550 | # test_stdout_none (see above). The parent subprocess calls the child |
| 551 | # subprocess passing stdout=1, and this test uses stdout=PIPE in |
| 552 | # order to capture and check the output of the parent. See #11963. |
| 553 | code = ('import sys, subprocess; ' |
| 554 | 'rc = subprocess.call([sys.executable, "-c", ' |
| 555 | ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), ' |
| 556 | 'b\'test with stdout=1\'))"], stdout=1); ' |
| 557 | 'assert rc == 18') |
| 558 | p = subprocess.Popen([sys.executable, "-c", code], |
| 559 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 560 | self.addCleanup(p.stdout.close) |
| 561 | self.addCleanup(p.stderr.close) |
| 562 | out, err = p.communicate() |
| 563 | self.assertEqual(p.returncode, 0, err) |
| 564 | self.assertEqual(out.rstrip(), b'test with stdout=1') |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 565 | |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 566 | def test_stdout_devnull(self): |
| 567 | p = subprocess.Popen([sys.executable, "-c", |
| 568 | 'for i in range(10240):' |
| 569 | 'print("x" * 1024)'], |
| 570 | stdout=subprocess.DEVNULL) |
| 571 | p.wait() |
| 572 | self.assertEqual(p.stdout, None) |
| 573 | |
| 574 | def test_stderr_devnull(self): |
| 575 | p = subprocess.Popen([sys.executable, "-c", |
| 576 | 'import sys\n' |
| 577 | 'for i in range(10240):' |
| 578 | 'sys.stderr.write("x" * 1024)'], |
| 579 | stderr=subprocess.DEVNULL) |
| 580 | p.wait() |
| 581 | self.assertEqual(p.stderr, None) |
| 582 | |
| 583 | def test_stdin_devnull(self): |
| 584 | p = subprocess.Popen([sys.executable, "-c", |
| 585 | 'import sys;' |
| 586 | 'sys.stdin.read(1)'], |
| 587 | stdin=subprocess.DEVNULL) |
| 588 | p.wait() |
| 589 | self.assertEqual(p.stdin, None) |
| 590 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 591 | def test_env(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 592 | newenv = os.environ.copy() |
| 593 | newenv["FRUIT"] = "orange" |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 594 | with subprocess.Popen([sys.executable, "-c", |
| 595 | 'import sys,os;' |
| 596 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 597 | stdout=subprocess.PIPE, |
| 598 | env=newenv) as p: |
| 599 | stdout, stderr = p.communicate() |
| 600 | self.assertEqual(stdout, b"orange") |
| 601 | |
Victor Stinner | 62d5118 | 2011-06-23 01:02:25 +0200 | [diff] [blame] | 602 | # Windows requires at least the SYSTEMROOT environment variable to start |
| 603 | # Python |
| 604 | @unittest.skipIf(sys.platform == 'win32', |
| 605 | 'cannot test an empty env on Windows') |
Victor Stinner | 237e5cb | 2011-06-22 21:28:43 +0200 | [diff] [blame] | 606 | @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None, |
Victor Stinner | 372309a | 2011-06-21 21:59:06 +0200 | [diff] [blame] | 607 | 'the python library cannot be loaded ' |
| 608 | 'with an empty environment') |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 609 | def test_empty_env(self): |
| 610 | with subprocess.Popen([sys.executable, "-c", |
| 611 | 'import os; ' |
Victor Stinner | 372309a | 2011-06-21 21:59:06 +0200 | [diff] [blame] | 612 | 'print(list(os.environ.keys()))'], |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 613 | stdout=subprocess.PIPE, |
| 614 | env={}) as p: |
| 615 | stdout, stderr = p.communicate() |
Victor Stinner | 237e5cb | 2011-06-22 21:28:43 +0200 | [diff] [blame] | 616 | self.assertIn(stdout.strip(), |
| 617 | (b"[]", |
| 618 | # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty |
| 619 | # environment |
| 620 | b"['__CF_USER_TEXT_ENCODING']")) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 621 | |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 622 | def test_communicate_stdin(self): |
| 623 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 624 | 'import sys;' |
| 625 | 'sys.exit(sys.stdin.read() == "pear")'], |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 626 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 627 | p.communicate(b"pear") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 628 | self.assertEqual(p.returncode, 1) |
| 629 | |
| 630 | def test_communicate_stdout(self): |
| 631 | p = subprocess.Popen([sys.executable, "-c", |
| 632 | 'import sys; sys.stdout.write("pineapple")'], |
| 633 | stdout=subprocess.PIPE) |
| 634 | (stdout, stderr) = p.communicate() |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 635 | self.assertEqual(stdout, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 636 | self.assertEqual(stderr, None) |
| 637 | |
| 638 | def test_communicate_stderr(self): |
| 639 | p = subprocess.Popen([sys.executable, "-c", |
| 640 | 'import sys; sys.stderr.write("pineapple")'], |
| 641 | stderr=subprocess.PIPE) |
| 642 | (stdout, stderr) = p.communicate() |
| 643 | self.assertEqual(stdout, None) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 644 | self.assertStderrEqual(stderr, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 645 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 646 | def test_communicate(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 647 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 648 | 'import sys,os;' |
| 649 | 'sys.stderr.write("pineapple");' |
| 650 | 'sys.stdout.write(sys.stdin.read())'], |
| 651 | stdin=subprocess.PIPE, |
| 652 | stdout=subprocess.PIPE, |
| 653 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 654 | self.addCleanup(p.stdout.close) |
| 655 | self.addCleanup(p.stderr.close) |
| 656 | self.addCleanup(p.stdin.close) |
Georg Brandl | 1abcbf8 | 2008-07-01 19:28:43 +0000 | [diff] [blame] | 657 | (stdout, stderr) = p.communicate(b"banana") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 658 | self.assertEqual(stdout, b"banana") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 659 | self.assertStderrEqual(stderr, b"pineapple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 660 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 661 | def test_communicate_timeout(self): |
| 662 | p = subprocess.Popen([sys.executable, "-c", |
| 663 | 'import sys,os,time;' |
| 664 | 'sys.stderr.write("pineapple\\n");' |
| 665 | 'time.sleep(1);' |
| 666 | 'sys.stderr.write("pear\\n");' |
| 667 | 'sys.stdout.write(sys.stdin.read())'], |
| 668 | universal_newlines=True, |
| 669 | stdin=subprocess.PIPE, |
| 670 | stdout=subprocess.PIPE, |
| 671 | stderr=subprocess.PIPE) |
| 672 | self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana", |
| 673 | timeout=0.3) |
| 674 | # Make sure we can keep waiting for it, and that we get the whole output |
| 675 | # after it completes. |
| 676 | (stdout, stderr) = p.communicate() |
| 677 | self.assertEqual(stdout, "banana") |
| 678 | self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n") |
| 679 | |
| 680 | def test_communicate_timeout_large_ouput(self): |
Ross Lagerwall | 003c7a3 | 2012-02-12 09:02:01 +0200 | [diff] [blame] | 681 | # Test an expiring timeout while the child is outputting lots of data. |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 682 | p = subprocess.Popen([sys.executable, "-c", |
| 683 | 'import sys,os,time;' |
| 684 | 'sys.stdout.write("a" * (64 * 1024));' |
| 685 | 'time.sleep(0.2);' |
| 686 | 'sys.stdout.write("a" * (64 * 1024));' |
| 687 | 'time.sleep(0.2);' |
| 688 | 'sys.stdout.write("a" * (64 * 1024));' |
| 689 | 'time.sleep(0.2);' |
| 690 | 'sys.stdout.write("a" * (64 * 1024));'], |
| 691 | stdout=subprocess.PIPE) |
| 692 | self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4) |
| 693 | (stdout, _) = p.communicate() |
| 694 | self.assertEqual(len(stdout), 4 * 64 * 1024) |
| 695 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 696 | # Test for the fd leak reported in http://bugs.python.org/issue2791. |
| 697 | def test_communicate_pipe_fd_leak(self): |
Victor Stinner | 667d4b5 | 2010-12-25 22:40:32 +0000 | [diff] [blame] | 698 | for stdin_pipe in (False, True): |
| 699 | for stdout_pipe in (False, True): |
| 700 | for stderr_pipe in (False, True): |
| 701 | options = {} |
| 702 | if stdin_pipe: |
| 703 | options['stdin'] = subprocess.PIPE |
| 704 | if stdout_pipe: |
| 705 | options['stdout'] = subprocess.PIPE |
| 706 | if stderr_pipe: |
| 707 | options['stderr'] = subprocess.PIPE |
| 708 | if not options: |
| 709 | continue |
| 710 | p = subprocess.Popen((sys.executable, "-c", "pass"), **options) |
| 711 | p.communicate() |
| 712 | if p.stdin is not None: |
| 713 | self.assertTrue(p.stdin.closed) |
| 714 | if p.stdout is not None: |
| 715 | self.assertTrue(p.stdout.closed) |
| 716 | if p.stderr is not None: |
| 717 | self.assertTrue(p.stderr.closed) |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 718 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 719 | def test_communicate_returns(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 720 | # communicate() should return None if no redirection is active |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 721 | p = subprocess.Popen([sys.executable, "-c", |
| 722 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 723 | (stdout, stderr) = p.communicate() |
| 724 | self.assertEqual(stdout, None) |
| 725 | self.assertEqual(stderr, None) |
| 726 | |
| 727 | def test_communicate_pipe_buf(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 728 | # communicate() with writes larger than pipe_buf |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 729 | # This test will probably deadlock rather than fail, if |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 730 | # communicate() does not work properly. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 731 | x, y = os.pipe() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 732 | os.close(x) |
| 733 | os.close(y) |
| 734 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 735 | 'import sys,os;' |
| 736 | 'sys.stdout.write(sys.stdin.read(47));' |
Charles-François Natali | 2d51721 | 2011-05-29 16:36:44 +0200 | [diff] [blame] | 737 | 'sys.stderr.write("x" * %d);' |
| 738 | 'sys.stdout.write(sys.stdin.read())' % |
| 739 | support.PIPE_MAX_SIZE], |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 740 | stdin=subprocess.PIPE, |
| 741 | stdout=subprocess.PIPE, |
| 742 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 743 | self.addCleanup(p.stdout.close) |
| 744 | self.addCleanup(p.stderr.close) |
| 745 | self.addCleanup(p.stdin.close) |
Charles-François Natali | 2d51721 | 2011-05-29 16:36:44 +0200 | [diff] [blame] | 746 | string_to_write = b"a" * support.PIPE_MAX_SIZE |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 747 | (stdout, stderr) = p.communicate(string_to_write) |
| 748 | self.assertEqual(stdout, string_to_write) |
| 749 | |
| 750 | def test_writes_before_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 751 | # stdin.write before communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 752 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 753 | 'import sys,os;' |
| 754 | 'sys.stdout.write(sys.stdin.read())'], |
| 755 | stdin=subprocess.PIPE, |
| 756 | stdout=subprocess.PIPE, |
| 757 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 758 | self.addCleanup(p.stdout.close) |
| 759 | self.addCleanup(p.stderr.close) |
| 760 | self.addCleanup(p.stdin.close) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 761 | p.stdin.write(b"banana") |
| 762 | (stdout, stderr) = p.communicate(b"split") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 763 | self.assertEqual(stdout, b"bananasplit") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 764 | self.assertStderrEqual(stderr, b"") |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 765 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 766 | def test_universal_newlines(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 767 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 768 | 'import sys,os;' + SETBINARY + |
Antoine Pitrou | ec2d269 | 2012-08-05 00:23:40 +0200 | [diff] [blame] | 769 | 'buf = sys.stdout.buffer;' |
| 770 | 'buf.write(sys.stdin.readline().encode());' |
| 771 | 'buf.flush();' |
| 772 | 'buf.write(b"line2\\n");' |
| 773 | 'buf.flush();' |
| 774 | 'buf.write(sys.stdin.read().encode());' |
| 775 | 'buf.flush();' |
| 776 | 'buf.write(b"line4\\n");' |
| 777 | 'buf.flush();' |
| 778 | 'buf.write(b"line5\\r\\n");' |
| 779 | 'buf.flush();' |
| 780 | 'buf.write(b"line6\\r");' |
| 781 | 'buf.flush();' |
| 782 | 'buf.write(b"\\nline7");' |
| 783 | 'buf.flush();' |
| 784 | 'buf.write(b"\\nline8");'], |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 785 | stdin=subprocess.PIPE, |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 786 | stdout=subprocess.PIPE, |
| 787 | universal_newlines=1) |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 788 | p.stdin.write("line1\n") |
| 789 | self.assertEqual(p.stdout.readline(), "line1\n") |
| 790 | p.stdin.write("line3\n") |
| 791 | p.stdin.close() |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 792 | self.addCleanup(p.stdout.close) |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 793 | self.assertEqual(p.stdout.readline(), |
| 794 | "line2\n") |
| 795 | self.assertEqual(p.stdout.read(6), |
| 796 | "line3\n") |
| 797 | self.assertEqual(p.stdout.read(), |
| 798 | "line4\nline5\nline6\nline7\nline8") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 799 | |
| 800 | def test_universal_newlines_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 801 | # universal newlines through communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 802 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 803 | 'import sys,os;' + SETBINARY + |
Antoine Pitrou | ec2d269 | 2012-08-05 00:23:40 +0200 | [diff] [blame] | 804 | 'buf = sys.stdout.buffer;' |
| 805 | 'buf.write(b"line2\\n");' |
| 806 | 'buf.flush();' |
| 807 | 'buf.write(b"line4\\n");' |
| 808 | 'buf.flush();' |
| 809 | 'buf.write(b"line5\\r\\n");' |
| 810 | 'buf.flush();' |
| 811 | 'buf.write(b"line6\\r");' |
| 812 | 'buf.flush();' |
| 813 | 'buf.write(b"\\nline7");' |
| 814 | 'buf.flush();' |
| 815 | 'buf.write(b"\\nline8");'], |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 816 | stderr=subprocess.PIPE, |
| 817 | stdout=subprocess.PIPE, |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 818 | universal_newlines=1) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 819 | self.addCleanup(p.stdout.close) |
| 820 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 821 | (stdout, stderr) = p.communicate() |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 822 | self.assertEqual(stdout, |
| 823 | "line2\nline4\nline5\nline6\nline7\nline8") |
| 824 | |
| 825 | def test_universal_newlines_communicate_stdin(self): |
| 826 | # universal newlines through communicate(), with only stdin |
| 827 | p = subprocess.Popen([sys.executable, "-c", |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 828 | 'import sys,os;' + SETBINARY + textwrap.dedent(''' |
| 829 | s = sys.stdin.readline() |
| 830 | assert s == "line1\\n", repr(s) |
| 831 | s = sys.stdin.read() |
| 832 | assert s == "line3\\n", repr(s) |
| 833 | ''')], |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 834 | stdin=subprocess.PIPE, |
| 835 | universal_newlines=1) |
| 836 | (stdout, stderr) = p.communicate("line1\nline3\n") |
| 837 | self.assertEqual(p.returncode, 0) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 838 | |
Andrew Svetlov | f376507 | 2012-08-14 18:35:17 +0300 | [diff] [blame] | 839 | def test_universal_newlines_communicate_input_none(self): |
| 840 | # Test communicate(input=None) with universal newlines. |
| 841 | # |
| 842 | # We set stdout to PIPE because, as of this writing, a different |
| 843 | # code path is tested when the number of pipes is zero or one. |
| 844 | p = subprocess.Popen([sys.executable, "-c", "pass"], |
| 845 | stdin=subprocess.PIPE, |
| 846 | stdout=subprocess.PIPE, |
| 847 | universal_newlines=True) |
| 848 | p.communicate() |
| 849 | self.assertEqual(p.returncode, 0) |
| 850 | |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 851 | def test_universal_newlines_communicate_stdin_stdout_stderr(self): |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 852 | # universal newlines through communicate(), with stdin, stdout, stderr |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 853 | p = subprocess.Popen([sys.executable, "-c", |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 854 | 'import sys,os;' + SETBINARY + textwrap.dedent(''' |
| 855 | s = sys.stdin.buffer.readline() |
| 856 | sys.stdout.buffer.write(s) |
| 857 | sys.stdout.buffer.write(b"line2\\r") |
| 858 | sys.stderr.buffer.write(b"eline2\\n") |
| 859 | s = sys.stdin.buffer.read() |
| 860 | sys.stdout.buffer.write(s) |
| 861 | sys.stdout.buffer.write(b"line4\\n") |
| 862 | sys.stdout.buffer.write(b"line5\\r\\n") |
| 863 | sys.stderr.buffer.write(b"eline6\\r") |
| 864 | sys.stderr.buffer.write(b"eline7\\r\\nz") |
| 865 | ''')], |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 866 | stdin=subprocess.PIPE, |
| 867 | stderr=subprocess.PIPE, |
| 868 | stdout=subprocess.PIPE, |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 869 | universal_newlines=True) |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 870 | self.addCleanup(p.stdout.close) |
| 871 | self.addCleanup(p.stderr.close) |
| 872 | (stdout, stderr) = p.communicate("line1\nline3\n") |
| 873 | self.assertEqual(p.returncode, 0) |
Andrew Svetlov | 943c5b3 | 2012-08-16 20:17:47 +0300 | [diff] [blame] | 874 | self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout) |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 875 | # Python debug build push something like "[42442 refs]\n" |
| 876 | # to stderr at exit of subprocess. |
Andrew Svetlov | 943c5b3 | 2012-08-16 20:17:47 +0300 | [diff] [blame] | 877 | # Don't use assertStderrEqual because it strips CR and LF from output. |
| 878 | self.assertTrue(stderr.startswith("eline2\neline6\neline7\n")) |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 879 | |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 880 | def test_universal_newlines_communicate_encodings(self): |
| 881 | # Check that universal newlines mode works for various encodings, |
| 882 | # in particular for encodings in the UTF-16 and UTF-32 families. |
| 883 | # See issue #15595. |
| 884 | # |
| 885 | # UTF-16 and UTF-32-BE are sufficient to check both with BOM and |
| 886 | # without, and UTF-16 and UTF-32. |
Antoine Pitrou | fd4722c | 2013-10-12 00:13:50 +0200 | [diff] [blame] | 887 | import _bootlocale |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 888 | for encoding in ['utf-16', 'utf-32-be']: |
Antoine Pitrou | fd4722c | 2013-10-12 00:13:50 +0200 | [diff] [blame] | 889 | old_getpreferredencoding = _bootlocale.getpreferredencoding |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 890 | # Indirectly via io.TextIOWrapper, Popen() defaults to |
| 891 | # locale.getpreferredencoding(False) and earlier in Python 3.2 to |
| 892 | # locale.getpreferredencoding(). |
| 893 | def getpreferredencoding(do_setlocale=True): |
| 894 | return encoding |
| 895 | code = ("import sys; " |
| 896 | r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" % |
| 897 | encoding) |
| 898 | args = [sys.executable, '-c', code] |
| 899 | try: |
Antoine Pitrou | fd4722c | 2013-10-12 00:13:50 +0200 | [diff] [blame] | 900 | _bootlocale.getpreferredencoding = getpreferredencoding |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 901 | # We set stdin to be non-None because, as of this writing, |
| 902 | # a different code path is used when the number of pipes is |
| 903 | # zero or one. |
| 904 | popen = subprocess.Popen(args, universal_newlines=True, |
| 905 | stdin=subprocess.PIPE, |
| 906 | stdout=subprocess.PIPE) |
| 907 | stdout, stderr = popen.communicate(input='') |
| 908 | finally: |
Antoine Pitrou | fd4722c | 2013-10-12 00:13:50 +0200 | [diff] [blame] | 909 | _bootlocale.getpreferredencoding = old_getpreferredencoding |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 910 | self.assertEqual(stdout, '1\n2\n3\n4') |
| 911 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 912 | def test_no_leaking(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 913 | # Make sure we leak no resources |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 914 | if not mswindows: |
Peter Astrand | f7f1bb7 | 2005-03-03 20:47:37 +0000 | [diff] [blame] | 915 | max_handles = 1026 # too much for most UNIX systems |
| 916 | else: |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 917 | max_handles = 2050 # too much for (at least some) Windows setups |
| 918 | handles = [] |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 919 | tmpdir = tempfile.mkdtemp() |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 920 | try: |
| 921 | for i in range(max_handles): |
| 922 | try: |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 923 | tmpfile = os.path.join(tmpdir, support.TESTFN) |
| 924 | handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT)) |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 925 | except OSError as e: |
| 926 | if e.errno != errno.EMFILE: |
| 927 | raise |
| 928 | break |
| 929 | else: |
| 930 | self.skipTest("failed to reach the file descriptor limit " |
| 931 | "(tried %d)" % max_handles) |
| 932 | # Close a couple of them (should be enough for a subprocess) |
| 933 | for i in range(10): |
| 934 | os.close(handles.pop()) |
| 935 | # Loop creating some subprocesses. If one of them leaks some fds, |
| 936 | # the next loop iteration will fail by reaching the max fd limit. |
| 937 | for i in range(15): |
| 938 | p = subprocess.Popen([sys.executable, "-c", |
| 939 | "import sys;" |
| 940 | "sys.stdout.write(sys.stdin.read())"], |
| 941 | stdin=subprocess.PIPE, |
| 942 | stdout=subprocess.PIPE, |
| 943 | stderr=subprocess.PIPE) |
| 944 | data = p.communicate(b"lime")[0] |
| 945 | self.assertEqual(data, b"lime") |
| 946 | finally: |
| 947 | for h in handles: |
| 948 | os.close(h) |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 949 | shutil.rmtree(tmpdir) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 950 | |
| 951 | def test_list2cmdline(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 952 | self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']), |
| 953 | '"a b c" d e') |
| 954 | self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']), |
| 955 | 'ab\\"c \\ d') |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 956 | self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']), |
| 957 | 'ab\\"c " \\\\" d') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 958 | self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']), |
| 959 | 'a\\\\\\b "de fg" h') |
| 960 | self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']), |
| 961 | 'a\\\\\\"b c d') |
| 962 | self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']), |
| 963 | '"a\\\\b c" d e') |
| 964 | self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']), |
| 965 | '"a\\\\b\\ c" d e') |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 966 | self.assertEqual(subprocess.list2cmdline(['ab', '']), |
| 967 | 'ab ""') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 968 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 969 | def test_poll(self): |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 970 | p = subprocess.Popen([sys.executable, "-c", |
Ross Lagerwall | e7ad419 | 2012-02-22 06:02:07 +0200 | [diff] [blame] | 971 | "import os; os.read(0, 1)"], |
| 972 | stdin=subprocess.PIPE) |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 973 | self.addCleanup(p.stdin.close) |
| 974 | self.assertIsNone(p.poll()) |
| 975 | os.write(p.stdin.fileno(), b'A') |
| 976 | p.wait() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 977 | # Subsequent invocations should just return the returncode |
| 978 | self.assertEqual(p.poll(), 0) |
| 979 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 980 | def test_wait(self): |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 981 | p = subprocess.Popen([sys.executable, "-c", "pass"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 982 | self.assertEqual(p.wait(), 0) |
| 983 | # Subsequent invocations should just return the returncode |
| 984 | self.assertEqual(p.wait(), 0) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 985 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 986 | def test_wait_timeout(self): |
| 987 | p = subprocess.Popen([sys.executable, |
Antoine Pitrou | dc49b2b | 2013-05-19 15:55:40 +0200 | [diff] [blame] | 988 | "-c", "import time; time.sleep(0.3)"]) |
Reid Kleckner | 2b228f0 | 2011-03-16 16:57:54 -0400 | [diff] [blame] | 989 | with self.assertRaises(subprocess.TimeoutExpired) as c: |
Antoine Pitrou | dc49b2b | 2013-05-19 15:55:40 +0200 | [diff] [blame] | 990 | p.wait(timeout=0.0001) |
| 991 | self.assertIn("0.0001", str(c.exception)) # For coverage of __str__. |
Reid Kleckner | da9ac72 | 2011-03-16 17:08:21 -0400 | [diff] [blame] | 992 | # Some heavily loaded buildbots (sparc Debian 3.x) require this much |
| 993 | # time to start. |
| 994 | self.assertEqual(p.wait(timeout=3), 0) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 995 | |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 996 | def test_invalid_bufsize(self): |
| 997 | # an invalid type of the bufsize argument should raise |
| 998 | # TypeError. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 999 | with self.assertRaises(TypeError): |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 1000 | subprocess.Popen([sys.executable, "-c", "pass"], "orange") |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 1001 | |
Guido van Rossum | 46a05a7 | 2007-06-07 21:56:45 +0000 | [diff] [blame] | 1002 | def test_bufsize_is_none(self): |
| 1003 | # bufsize=None should be the same as bufsize=0. |
| 1004 | p = subprocess.Popen([sys.executable, "-c", "pass"], None) |
| 1005 | self.assertEqual(p.wait(), 0) |
| 1006 | # Again with keyword arg |
| 1007 | p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None) |
| 1008 | self.assertEqual(p.wait(), 0) |
| 1009 | |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 1010 | def test_leaking_fds_on_error(self): |
| 1011 | # see bug #5179: Popen leaks file descriptors to PIPEs if |
| 1012 | # the child fails to execute; this will eventually exhaust |
| 1013 | # the maximum number of open fds. 1024 seems a very common |
| 1014 | # value for that limit, but Windows has 2048, so we loop |
| 1015 | # 1024 times (each call leaked two fds). |
| 1016 | for i in range(1024): |
Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 1017 | with self.assertRaises(OSError) as c: |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 1018 | subprocess.Popen(['nonexisting_i_hope'], |
| 1019 | stdout=subprocess.PIPE, |
| 1020 | stderr=subprocess.PIPE) |
R David Murray | 384069c | 2011-03-13 22:26:53 -0400 | [diff] [blame] | 1021 | # ignore errors that indicate the command was not found |
R David Murray | 6924bd7 | 2011-03-13 22:48:55 -0400 | [diff] [blame] | 1022 | if c.exception.errno not in (errno.ENOENT, errno.EACCES): |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1023 | raise c.exception |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 1024 | |
Antoine Pitrou | a839271 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 1025 | @unittest.skipIf(threading is None, "threading required") |
| 1026 | def test_double_close_on_error(self): |
| 1027 | # Issue #18851 |
| 1028 | fds = [] |
| 1029 | def open_fds(): |
| 1030 | for i in range(20): |
| 1031 | fds.extend(os.pipe()) |
| 1032 | time.sleep(0.001) |
| 1033 | t = threading.Thread(target=open_fds) |
| 1034 | t.start() |
| 1035 | try: |
| 1036 | with self.assertRaises(EnvironmentError): |
| 1037 | subprocess.Popen(['nonexisting_i_hope'], |
| 1038 | stdin=subprocess.PIPE, |
| 1039 | stdout=subprocess.PIPE, |
| 1040 | stderr=subprocess.PIPE) |
| 1041 | finally: |
| 1042 | t.join() |
| 1043 | exc = None |
| 1044 | for fd in fds: |
| 1045 | # If a double close occurred, some of those fds will |
| 1046 | # already have been closed by mistake, and os.close() |
| 1047 | # here will raise. |
| 1048 | try: |
| 1049 | os.close(fd) |
| 1050 | except OSError as e: |
| 1051 | exc = e |
| 1052 | if exc is not None: |
| 1053 | raise exc |
| 1054 | |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 1055 | def test_issue8780(self): |
| 1056 | # Ensure that stdout is inherited from the parent |
| 1057 | # if stdout=PIPE is not used |
| 1058 | code = ';'.join(( |
| 1059 | 'import subprocess, sys', |
| 1060 | 'retcode = subprocess.call(' |
| 1061 | "[sys.executable, '-c', 'print(\"Hello World!\")'])", |
| 1062 | 'assert retcode == 0')) |
| 1063 | output = subprocess.check_output([sys.executable, '-c', code]) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1064 | self.assertTrue(output.startswith(b'Hello World!'), ascii(output)) |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 1065 | |
Tim Golden | af5ac39 | 2010-08-06 13:03:56 +0000 | [diff] [blame] | 1066 | def test_handles_closed_on_exception(self): |
| 1067 | # If CreateProcess exits with an error, ensure the |
| 1068 | # duplicate output handles are released |
| 1069 | ifhandle, ifname = mkstemp() |
| 1070 | ofhandle, ofname = mkstemp() |
| 1071 | efhandle, efname = mkstemp() |
| 1072 | try: |
| 1073 | subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle, |
| 1074 | stderr=efhandle) |
| 1075 | except OSError: |
| 1076 | os.close(ifhandle) |
| 1077 | os.remove(ifname) |
| 1078 | os.close(ofhandle) |
| 1079 | os.remove(ofname) |
| 1080 | os.close(efhandle) |
| 1081 | os.remove(efname) |
| 1082 | self.assertFalse(os.path.exists(ifname)) |
| 1083 | self.assertFalse(os.path.exists(ofname)) |
| 1084 | self.assertFalse(os.path.exists(efname)) |
| 1085 | |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 1086 | def test_communicate_epipe(self): |
| 1087 | # Issue 10963: communicate() should hide EPIPE |
| 1088 | p = subprocess.Popen([sys.executable, "-c", 'pass'], |
| 1089 | stdin=subprocess.PIPE, |
| 1090 | stdout=subprocess.PIPE, |
| 1091 | stderr=subprocess.PIPE) |
| 1092 | self.addCleanup(p.stdout.close) |
| 1093 | self.addCleanup(p.stderr.close) |
| 1094 | self.addCleanup(p.stdin.close) |
| 1095 | p.communicate(b"x" * 2**20) |
| 1096 | |
| 1097 | def test_communicate_epipe_only_stdin(self): |
| 1098 | # Issue 10963: communicate() should hide EPIPE |
| 1099 | p = subprocess.Popen([sys.executable, "-c", 'pass'], |
| 1100 | stdin=subprocess.PIPE) |
| 1101 | self.addCleanup(p.stdin.close) |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1102 | p.wait() |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 1103 | p.communicate(b"x" * 2**20) |
| 1104 | |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1105 | @unittest.skipUnless(hasattr(signal, 'SIGUSR1'), |
| 1106 | "Requires signal.SIGUSR1") |
| 1107 | @unittest.skipUnless(hasattr(os, 'kill'), |
| 1108 | "Requires os.kill") |
| 1109 | @unittest.skipUnless(hasattr(os, 'getppid'), |
| 1110 | "Requires os.getppid") |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 1111 | def test_communicate_eintr(self): |
| 1112 | # Issue #12493: communicate() should handle EINTR |
| 1113 | def handler(signum, frame): |
| 1114 | pass |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1115 | old_handler = signal.signal(signal.SIGUSR1, handler) |
| 1116 | self.addCleanup(signal.signal, signal.SIGUSR1, old_handler) |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 1117 | |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1118 | args = [sys.executable, "-c", |
| 1119 | 'import os, signal;' |
| 1120 | 'os.kill(os.getppid(), signal.SIGUSR1)'] |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 1121 | for stream in ('stdout', 'stderr'): |
| 1122 | kw = {stream: subprocess.PIPE} |
| 1123 | with subprocess.Popen(args, **kw) as process: |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1124 | # communicate() will be interrupted by SIGUSR1 |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 1125 | process.communicate() |
| 1126 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1127 | |
Gregory P. Smith | 3d8e776 | 2012-11-10 22:32:22 -0800 | [diff] [blame] | 1128 | # This test is Linux-ish specific for simplicity to at least have |
| 1129 | # some coverage. It is not a platform specific bug. |
| 1130 | @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()), |
| 1131 | "Linux specific") |
| 1132 | def test_failed_child_execute_fd_leak(self): |
| 1133 | """Test for the fork() failure fd leak reported in issue16327.""" |
| 1134 | fd_directory = '/proc/%d/fd' % os.getpid() |
| 1135 | fds_before_popen = os.listdir(fd_directory) |
| 1136 | with self.assertRaises(PopenTestException): |
| 1137 | PopenExecuteChildRaises( |
| 1138 | [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE, |
| 1139 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 1140 | |
| 1141 | # NOTE: This test doesn't verify that the real _execute_child |
| 1142 | # does not close the file descriptors itself on the way out |
| 1143 | # during an exception. Code inspection has confirmed that. |
| 1144 | |
| 1145 | fds_after_exception = os.listdir(fd_directory) |
| 1146 | self.assertEqual(fds_before_popen, fds_after_exception) |
| 1147 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1148 | @unittest.skipIf(mswindows, "POSIX specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1149 | class POSIXProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1150 | |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1151 | def setUp(self): |
| 1152 | super().setUp() |
| 1153 | self._nonexistent_dir = "/_this/pa.th/does/not/exist" |
| 1154 | |
| 1155 | def _get_chdir_exception(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1156 | try: |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1157 | os.chdir(self._nonexistent_dir) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1158 | except OSError as e: |
| 1159 | # This avoids hard coding the errno value or the OS perror() |
| 1160 | # string and instead capture the exception that we want to see |
| 1161 | # below for comparison. |
| 1162 | desired_exception = e |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1163 | desired_exception.strerror += ': ' + repr(self._nonexistent_dir) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1164 | else: |
| 1165 | self.fail("chdir to nonexistant directory %s succeeded." % |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1166 | self._nonexistent_dir) |
| 1167 | return desired_exception |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1168 | |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1169 | def test_exception_cwd(self): |
| 1170 | """Test error in the child raised in the parent for a bad cwd.""" |
| 1171 | desired_exception = self._get_chdir_exception() |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1172 | try: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1173 | p = subprocess.Popen([sys.executable, "-c", ""], |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1174 | cwd=self._nonexistent_dir) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1175 | except OSError as e: |
| 1176 | # Test that the child process chdir failure actually makes |
| 1177 | # it up to the parent process as the correct exception. |
| 1178 | self.assertEqual(desired_exception.errno, e.errno) |
| 1179 | self.assertEqual(desired_exception.strerror, e.strerror) |
| 1180 | else: |
| 1181 | self.fail("Expected OSError: %s" % desired_exception) |
| 1182 | |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1183 | def test_exception_bad_executable(self): |
| 1184 | """Test error in the child raised in the parent for a bad executable.""" |
| 1185 | desired_exception = self._get_chdir_exception() |
| 1186 | try: |
| 1187 | p = subprocess.Popen([sys.executable, "-c", ""], |
| 1188 | executable=self._nonexistent_dir) |
| 1189 | except OSError as e: |
| 1190 | # Test that the child process exec failure actually makes |
| 1191 | # it up to the parent process as the correct exception. |
| 1192 | self.assertEqual(desired_exception.errno, e.errno) |
| 1193 | self.assertEqual(desired_exception.strerror, e.strerror) |
| 1194 | else: |
| 1195 | self.fail("Expected OSError: %s" % desired_exception) |
| 1196 | |
| 1197 | def test_exception_bad_args_0(self): |
| 1198 | """Test error in the child raised in the parent for a bad args[0].""" |
| 1199 | desired_exception = self._get_chdir_exception() |
| 1200 | try: |
| 1201 | p = subprocess.Popen([self._nonexistent_dir, "-c", ""]) |
| 1202 | except OSError as e: |
| 1203 | # Test that the child process exec failure actually makes |
| 1204 | # it up to the parent process as the correct exception. |
| 1205 | self.assertEqual(desired_exception.errno, e.errno) |
| 1206 | self.assertEqual(desired_exception.strerror, e.strerror) |
| 1207 | else: |
| 1208 | self.fail("Expected OSError: %s" % desired_exception) |
| 1209 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1210 | def test_restore_signals(self): |
| 1211 | # Code coverage for both values of restore_signals to make sure it |
| 1212 | # at least does not blow up. |
| 1213 | # A test for behavior would be complex. Contributions welcome. |
| 1214 | subprocess.call([sys.executable, "-c", ""], restore_signals=True) |
| 1215 | subprocess.call([sys.executable, "-c", ""], restore_signals=False) |
| 1216 | |
| 1217 | def test_start_new_session(self): |
| 1218 | # For code coverage of calling setsid(). We don't care if we get an |
| 1219 | # EPERM error from it depending on the test execution environment, that |
| 1220 | # still indicates that it was called. |
| 1221 | try: |
| 1222 | output = subprocess.check_output( |
| 1223 | [sys.executable, "-c", |
| 1224 | "import os; print(os.getpgid(os.getpid()))"], |
| 1225 | start_new_session=True) |
| 1226 | except OSError as e: |
| 1227 | if e.errno != errno.EPERM: |
| 1228 | raise |
| 1229 | else: |
| 1230 | parent_pgid = os.getpgid(os.getpid()) |
| 1231 | child_pgid = int(output) |
| 1232 | self.assertNotEqual(parent_pgid, child_pgid) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1233 | |
| 1234 | def test_run_abort(self): |
| 1235 | # returncode handles signal termination |
Antoine Pitrou | 77e904e | 2013-10-08 23:04:32 +0200 | [diff] [blame] | 1236 | with support.SuppressCrashReport(): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1237 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1238 | 'import os; os.abort()']) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1239 | p.wait() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1240 | self.assertEqual(-p.returncode, signal.SIGABRT) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1241 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1242 | def test_preexec(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1243 | # DISCLAIMER: Setting environment variables is *not* a good use |
| 1244 | # of a preexec_fn. This is merely a test. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1245 | p = subprocess.Popen([sys.executable, "-c", |
| 1246 | 'import sys,os;' |
| 1247 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 1248 | stdout=subprocess.PIPE, |
| 1249 | preexec_fn=lambda: os.putenv("FRUIT", "apple")) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 1250 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1251 | self.assertEqual(p.stdout.read(), b"apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1252 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1253 | def test_preexec_exception(self): |
| 1254 | def raise_it(): |
| 1255 | raise ValueError("What if two swallows carried a coconut?") |
| 1256 | try: |
| 1257 | p = subprocess.Popen([sys.executable, "-c", ""], |
| 1258 | preexec_fn=raise_it) |
Gregory P. Smith | 8d07c26 | 2012-11-10 23:53:47 -0800 | [diff] [blame] | 1259 | except subprocess.SubprocessError as e: |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1260 | self.assertTrue( |
| 1261 | subprocess._posixsubprocess, |
| 1262 | "Expected a ValueError from the preexec_fn") |
| 1263 | except ValueError as e: |
| 1264 | self.assertIn("coconut", e.args[0]) |
| 1265 | else: |
| 1266 | self.fail("Exception raised by preexec_fn did not make it " |
| 1267 | "to the parent process.") |
| 1268 | |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 1269 | class _TestExecuteChildPopen(subprocess.Popen): |
| 1270 | """Used to test behavior at the end of _execute_child.""" |
| 1271 | def __init__(self, testcase, *args, **kwargs): |
| 1272 | self._testcase = testcase |
| 1273 | subprocess.Popen.__init__(self, *args, **kwargs) |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1274 | |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 1275 | def _execute_child(self, *args, **kwargs): |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1276 | try: |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 1277 | subprocess.Popen._execute_child(self, *args, **kwargs) |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1278 | finally: |
| 1279 | # Open a bunch of file descriptors and verify that |
| 1280 | # none of them are the same as the ones the Popen |
| 1281 | # instance is using for stdin/stdout/stderr. |
| 1282 | devzero_fds = [os.open("/dev/zero", os.O_RDONLY) |
| 1283 | for _ in range(8)] |
| 1284 | try: |
| 1285 | for fd in devzero_fds: |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 1286 | self._testcase.assertNotIn( |
| 1287 | fd, (self.stdin.fileno(), self.stdout.fileno(), |
| 1288 | self.stderr.fileno()), |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1289 | msg="At least one fd was closed early.") |
| 1290 | finally: |
Richard Oudkerk | 0e547b6 | 2013-06-10 16:29:19 +0100 | [diff] [blame] | 1291 | for fd in devzero_fds: |
| 1292 | os.close(fd) |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1293 | |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 1294 | @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.") |
| 1295 | def test_preexec_errpipe_does_not_double_close_pipes(self): |
| 1296 | """Issue16140: Don't double close pipes on preexec error.""" |
| 1297 | |
| 1298 | def raise_it(): |
Gregory P. Smith | 65ee6ec | 2012-11-11 10:12:40 -0800 | [diff] [blame] | 1299 | raise subprocess.SubprocessError( |
| 1300 | "force the _execute_child() errpipe_data path.") |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1301 | |
Gregory P. Smith | c2c4cb6 | 2012-11-11 01:41:49 -0800 | [diff] [blame] | 1302 | with self.assertRaises(subprocess.SubprocessError): |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 1303 | self._TestExecuteChildPopen( |
| 1304 | self, [sys.executable, "-c", "pass"], |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1305 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1306 | stderr=subprocess.PIPE, preexec_fn=raise_it) |
| 1307 | |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 1308 | def test_preexec_gc_module_failure(self): |
| 1309 | # This tests the code that disables garbage collection if the child |
| 1310 | # process will execute any Python. |
| 1311 | def raise_runtime_error(): |
| 1312 | raise RuntimeError("this shouldn't escape") |
| 1313 | enabled = gc.isenabled() |
| 1314 | orig_gc_disable = gc.disable |
| 1315 | orig_gc_isenabled = gc.isenabled |
| 1316 | try: |
| 1317 | gc.disable() |
| 1318 | self.assertFalse(gc.isenabled()) |
| 1319 | subprocess.call([sys.executable, '-c', ''], |
| 1320 | preexec_fn=lambda: None) |
| 1321 | self.assertFalse(gc.isenabled(), |
| 1322 | "Popen enabled gc when it shouldn't.") |
| 1323 | |
| 1324 | gc.enable() |
| 1325 | self.assertTrue(gc.isenabled()) |
| 1326 | subprocess.call([sys.executable, '-c', ''], |
| 1327 | preexec_fn=lambda: None) |
| 1328 | self.assertTrue(gc.isenabled(), "Popen left gc disabled.") |
| 1329 | |
| 1330 | gc.disable = raise_runtime_error |
| 1331 | self.assertRaises(RuntimeError, subprocess.Popen, |
| 1332 | [sys.executable, '-c', ''], |
| 1333 | preexec_fn=lambda: None) |
| 1334 | |
| 1335 | del gc.isenabled # force an AttributeError |
| 1336 | self.assertRaises(AttributeError, subprocess.Popen, |
| 1337 | [sys.executable, '-c', ''], |
| 1338 | preexec_fn=lambda: None) |
| 1339 | finally: |
| 1340 | gc.disable = orig_gc_disable |
| 1341 | gc.isenabled = orig_gc_isenabled |
| 1342 | if not enabled: |
| 1343 | gc.disable() |
| 1344 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1345 | def test_args_string(self): |
| 1346 | # args is a string |
| 1347 | fd, fname = mkstemp() |
| 1348 | # reopen in text mode |
Victor Stinner | f6782ac | 2010-10-16 23:46:43 +0000 | [diff] [blame] | 1349 | with open(fd, "w", errors="surrogateescape") as fobj: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1350 | fobj.write("#!/bin/sh\n") |
| 1351 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 1352 | sys.executable) |
| 1353 | os.chmod(fname, 0o700) |
| 1354 | p = subprocess.Popen(fname) |
| 1355 | p.wait() |
| 1356 | os.remove(fname) |
| 1357 | self.assertEqual(p.returncode, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1358 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1359 | def test_invalid_args(self): |
| 1360 | # invalid arguments should raise ValueError |
| 1361 | self.assertRaises(ValueError, subprocess.call, |
| 1362 | [sys.executable, "-c", |
| 1363 | "import sys; sys.exit(47)"], |
| 1364 | startupinfo=47) |
| 1365 | self.assertRaises(ValueError, subprocess.call, |
| 1366 | [sys.executable, "-c", |
| 1367 | "import sys; sys.exit(47)"], |
| 1368 | creationflags=47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1369 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1370 | def test_shell_sequence(self): |
| 1371 | # Run command through the shell (sequence) |
| 1372 | newenv = os.environ.copy() |
| 1373 | newenv["FRUIT"] = "apple" |
| 1374 | p = subprocess.Popen(["echo $FRUIT"], shell=1, |
| 1375 | stdout=subprocess.PIPE, |
| 1376 | env=newenv) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 1377 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1378 | 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] | 1379 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1380 | def test_shell_string(self): |
| 1381 | # Run command through the shell (string) |
| 1382 | newenv = os.environ.copy() |
| 1383 | newenv["FRUIT"] = "apple" |
| 1384 | p = subprocess.Popen("echo $FRUIT", shell=1, |
| 1385 | stdout=subprocess.PIPE, |
| 1386 | env=newenv) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 1387 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1388 | 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] | 1389 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1390 | def test_call_string(self): |
| 1391 | # call() function with string argument on UNIX |
| 1392 | fd, fname = mkstemp() |
| 1393 | # reopen in text mode |
Victor Stinner | f6782ac | 2010-10-16 23:46:43 +0000 | [diff] [blame] | 1394 | with open(fd, "w", errors="surrogateescape") as fobj: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1395 | fobj.write("#!/bin/sh\n") |
| 1396 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 1397 | sys.executable) |
| 1398 | os.chmod(fname, 0o700) |
| 1399 | rc = subprocess.call(fname) |
| 1400 | os.remove(fname) |
| 1401 | self.assertEqual(rc, 47) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1402 | |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 1403 | def test_specific_shell(self): |
| 1404 | # Issue #9265: Incorrect name passed as arg[0]. |
| 1405 | shells = [] |
| 1406 | for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']: |
| 1407 | for name in ['bash', 'ksh']: |
| 1408 | sh = os.path.join(prefix, name) |
| 1409 | if os.path.isfile(sh): |
| 1410 | shells.append(sh) |
| 1411 | if not shells: # Will probably work for any shell but csh. |
| 1412 | self.skipTest("bash or ksh required for this test") |
| 1413 | sh = '/bin/sh' |
| 1414 | if os.path.isfile(sh) and not os.path.islink(sh): |
| 1415 | # Test will fail if /bin/sh is a symlink to csh. |
| 1416 | shells.append(sh) |
| 1417 | for sh in shells: |
| 1418 | p = subprocess.Popen("echo $0", executable=sh, shell=True, |
| 1419 | stdout=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 1420 | self.addCleanup(p.stdout.close) |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 1421 | self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii')) |
| 1422 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1423 | def _kill_process(self, method, *args): |
Florent Xicluna | 1d8ee3a | 2010-03-05 20:26:54 +0000 | [diff] [blame] | 1424 | # Do not inherit file handles from the parent. |
| 1425 | # It should fix failures on some platforms. |
Gregory P. Smith | dee0434 | 2013-08-29 13:35:27 -0700 | [diff] [blame] | 1426 | # Also set the SIGINT handler to the default to make sure it's not |
| 1427 | # being ignored (some tests rely on that.) |
| 1428 | old_handler = signal.signal(signal.SIGINT, signal.default_int_handler) |
| 1429 | try: |
| 1430 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1431 | import sys, time |
| 1432 | sys.stdout.write('x\\n') |
| 1433 | sys.stdout.flush() |
| 1434 | time.sleep(30) |
| 1435 | """], |
| 1436 | close_fds=True, |
| 1437 | stdin=subprocess.PIPE, |
| 1438 | stdout=subprocess.PIPE, |
| 1439 | stderr=subprocess.PIPE) |
| 1440 | finally: |
| 1441 | signal.signal(signal.SIGINT, old_handler) |
Antoine Pitrou | 3d8580f | 2010-09-20 01:33:21 +0000 | [diff] [blame] | 1442 | # Wait for the interpreter to be completely initialized before |
| 1443 | # sending any signal. |
| 1444 | p.stdout.read(1) |
| 1445 | getattr(p, method)(*args) |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1446 | return p |
| 1447 | |
Charles-François Natali | 53221e3 | 2013-01-12 16:52:20 +0100 | [diff] [blame] | 1448 | @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')), |
| 1449 | "Due to known OS bug (issue #16762)") |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1450 | def _kill_dead_process(self, method, *args): |
| 1451 | # Do not inherit file handles from the parent. |
| 1452 | # It should fix failures on some platforms. |
| 1453 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1454 | import sys, time |
| 1455 | sys.stdout.write('x\\n') |
| 1456 | sys.stdout.flush() |
| 1457 | """], |
| 1458 | close_fds=True, |
| 1459 | stdin=subprocess.PIPE, |
| 1460 | stdout=subprocess.PIPE, |
| 1461 | stderr=subprocess.PIPE) |
| 1462 | # Wait for the interpreter to be completely initialized before |
| 1463 | # sending any signal. |
| 1464 | p.stdout.read(1) |
| 1465 | # The process should end after this |
| 1466 | time.sleep(1) |
| 1467 | # This shouldn't raise even though the child is now dead |
| 1468 | getattr(p, method)(*args) |
| 1469 | p.communicate() |
| 1470 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1471 | def test_send_signal(self): |
| 1472 | p = self._kill_process('send_signal', signal.SIGINT) |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1473 | _, stderr = p.communicate() |
| 1474 | self.assertIn(b'KeyboardInterrupt', stderr) |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1475 | self.assertNotEqual(p.wait(), 0) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1476 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1477 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1478 | p = self._kill_process('kill') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1479 | _, stderr = p.communicate() |
| 1480 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1481 | self.assertEqual(p.wait(), -signal.SIGKILL) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1482 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1483 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1484 | p = self._kill_process('terminate') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1485 | _, stderr = p.communicate() |
| 1486 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1487 | self.assertEqual(p.wait(), -signal.SIGTERM) |
| 1488 | |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1489 | def test_send_signal_dead(self): |
| 1490 | # Sending a signal to a dead process |
| 1491 | self._kill_dead_process('send_signal', signal.SIGINT) |
| 1492 | |
| 1493 | def test_kill_dead(self): |
| 1494 | # Killing a dead process |
| 1495 | self._kill_dead_process('kill') |
| 1496 | |
| 1497 | def test_terminate_dead(self): |
| 1498 | # Terminating a dead process |
| 1499 | self._kill_dead_process('terminate') |
| 1500 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1501 | def _save_fds(self, save_fds): |
| 1502 | fds = [] |
| 1503 | for fd in save_fds: |
| 1504 | inheritable = os.get_inheritable(fd) |
| 1505 | saved = os.dup(fd) |
| 1506 | fds.append((fd, saved, inheritable)) |
| 1507 | return fds |
| 1508 | |
| 1509 | def _restore_fds(self, fds): |
| 1510 | for fd, saved, inheritable in fds: |
| 1511 | os.dup2(saved, fd, inheritable=inheritable) |
| 1512 | os.close(saved) |
| 1513 | |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 1514 | def check_close_std_fds(self, fds): |
| 1515 | # Issue #9905: test that subprocess pipes still work properly with |
| 1516 | # some standard fds closed |
| 1517 | stdin = 0 |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1518 | saved_fds = self._save_fds(fds) |
| 1519 | for fd, saved, inheritable in saved_fds: |
| 1520 | if fd == 0: |
| 1521 | stdin = saved |
| 1522 | break |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 1523 | try: |
| 1524 | for fd in fds: |
| 1525 | os.close(fd) |
| 1526 | out, err = subprocess.Popen([sys.executable, "-c", |
| 1527 | 'import sys;' |
| 1528 | 'sys.stdout.write("apple");' |
| 1529 | 'sys.stdout.flush();' |
| 1530 | 'sys.stderr.write("orange")'], |
| 1531 | stdin=stdin, |
| 1532 | stdout=subprocess.PIPE, |
| 1533 | stderr=subprocess.PIPE).communicate() |
| 1534 | err = support.strip_python_stderr(err) |
| 1535 | self.assertEqual((out, err), (b'apple', b'orange')) |
| 1536 | finally: |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1537 | self._restore_fds(saved_fds) |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 1538 | |
| 1539 | def test_close_fd_0(self): |
| 1540 | self.check_close_std_fds([0]) |
| 1541 | |
| 1542 | def test_close_fd_1(self): |
| 1543 | self.check_close_std_fds([1]) |
| 1544 | |
| 1545 | def test_close_fd_2(self): |
| 1546 | self.check_close_std_fds([2]) |
| 1547 | |
| 1548 | def test_close_fds_0_1(self): |
| 1549 | self.check_close_std_fds([0, 1]) |
| 1550 | |
| 1551 | def test_close_fds_0_2(self): |
| 1552 | self.check_close_std_fds([0, 2]) |
| 1553 | |
| 1554 | def test_close_fds_1_2(self): |
| 1555 | self.check_close_std_fds([1, 2]) |
| 1556 | |
| 1557 | def test_close_fds_0_1_2(self): |
| 1558 | # Issue #10806: test that subprocess pipes still work properly with |
| 1559 | # all standard fds closed. |
| 1560 | self.check_close_std_fds([0, 1, 2]) |
| 1561 | |
Gregory P. Smith | 53dd816 | 2013-12-01 16:03:24 -0800 | [diff] [blame] | 1562 | def test_small_errpipe_write_fd(self): |
| 1563 | """Issue #15798: Popen should work when stdio fds are available.""" |
| 1564 | new_stdin = os.dup(0) |
| 1565 | new_stdout = os.dup(1) |
| 1566 | try: |
| 1567 | os.close(0) |
| 1568 | os.close(1) |
| 1569 | |
| 1570 | # Side test: if errpipe_write fails to have its CLOEXEC |
| 1571 | # flag set this should cause the parent to think the exec |
| 1572 | # failed. Extremely unlikely: everyone supports CLOEXEC. |
| 1573 | subprocess.Popen([ |
| 1574 | sys.executable, "-c", |
| 1575 | "print('AssertionError:0:CLOEXEC failure.')"]).wait() |
| 1576 | finally: |
| 1577 | # Restore original stdin and stdout |
| 1578 | os.dup2(new_stdin, 0) |
| 1579 | os.dup2(new_stdout, 1) |
| 1580 | os.close(new_stdin) |
| 1581 | os.close(new_stdout) |
| 1582 | |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 1583 | def test_remapping_std_fds(self): |
| 1584 | # open up some temporary files |
| 1585 | temps = [mkstemp() for i in range(3)] |
| 1586 | try: |
| 1587 | temp_fds = [fd for fd, fname in temps] |
| 1588 | |
| 1589 | # unlink the files -- we won't need to reopen them |
| 1590 | for fd, fname in temps: |
| 1591 | os.unlink(fname) |
| 1592 | |
| 1593 | # write some data to what will become stdin, and rewind |
| 1594 | os.write(temp_fds[1], b"STDIN") |
| 1595 | os.lseek(temp_fds[1], 0, 0) |
| 1596 | |
| 1597 | # move the standard file descriptors out of the way |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1598 | saved_fds = self._save_fds(range(3)) |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 1599 | try: |
| 1600 | # duplicate the file objects over the standard fd's |
| 1601 | for fd, temp_fd in enumerate(temp_fds): |
| 1602 | os.dup2(temp_fd, fd) |
| 1603 | |
| 1604 | # now use those files in the "wrong" order, so that subprocess |
| 1605 | # has to rearrange them in the child |
| 1606 | p = subprocess.Popen([sys.executable, "-c", |
| 1607 | 'import sys; got = sys.stdin.read();' |
| 1608 | 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'], |
| 1609 | stdin=temp_fds[1], |
| 1610 | stdout=temp_fds[2], |
| 1611 | stderr=temp_fds[0]) |
| 1612 | p.wait() |
| 1613 | finally: |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1614 | self._restore_fds(saved_fds) |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 1615 | |
| 1616 | for fd in temp_fds: |
| 1617 | os.lseek(fd, 0, 0) |
| 1618 | |
| 1619 | out = os.read(temp_fds[2], 1024) |
| 1620 | err = support.strip_python_stderr(os.read(temp_fds[0], 1024)) |
| 1621 | self.assertEqual(out, b"got STDIN") |
| 1622 | self.assertEqual(err, b"err") |
| 1623 | |
| 1624 | finally: |
| 1625 | for fd in temp_fds: |
| 1626 | os.close(fd) |
| 1627 | |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 1628 | def check_swap_fds(self, stdin_no, stdout_no, stderr_no): |
| 1629 | # open up some temporary files |
| 1630 | temps = [mkstemp() for i in range(3)] |
| 1631 | temp_fds = [fd for fd, fname in temps] |
| 1632 | try: |
| 1633 | # unlink the files -- we won't need to reopen them |
| 1634 | for fd, fname in temps: |
| 1635 | os.unlink(fname) |
| 1636 | |
| 1637 | # save a copy of the standard file descriptors |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1638 | saved_fds = self._save_fds(range(3)) |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 1639 | try: |
| 1640 | # duplicate the temp files over the standard fd's 0, 1, 2 |
| 1641 | for fd, temp_fd in enumerate(temp_fds): |
| 1642 | os.dup2(temp_fd, fd) |
| 1643 | |
| 1644 | # write some data to what will become stdin, and rewind |
| 1645 | os.write(stdin_no, b"STDIN") |
| 1646 | os.lseek(stdin_no, 0, 0) |
| 1647 | |
| 1648 | # now use those files in the given order, so that subprocess |
| 1649 | # has to rearrange them in the child |
| 1650 | p = subprocess.Popen([sys.executable, "-c", |
| 1651 | 'import sys; got = sys.stdin.read();' |
| 1652 | 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'], |
| 1653 | stdin=stdin_no, |
| 1654 | stdout=stdout_no, |
| 1655 | stderr=stderr_no) |
| 1656 | p.wait() |
| 1657 | |
| 1658 | for fd in temp_fds: |
| 1659 | os.lseek(fd, 0, 0) |
| 1660 | |
| 1661 | out = os.read(stdout_no, 1024) |
| 1662 | err = support.strip_python_stderr(os.read(stderr_no, 1024)) |
| 1663 | finally: |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1664 | self._restore_fds(saved_fds) |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 1665 | |
| 1666 | self.assertEqual(out, b"got STDIN") |
| 1667 | self.assertEqual(err, b"err") |
| 1668 | |
| 1669 | finally: |
| 1670 | for fd in temp_fds: |
| 1671 | os.close(fd) |
| 1672 | |
| 1673 | # When duping fds, if there arises a situation where one of the fds is |
| 1674 | # either 0, 1 or 2, it is possible that it is overwritten (#12607). |
| 1675 | # This tests all combinations of this. |
| 1676 | def test_swap_fds(self): |
| 1677 | self.check_swap_fds(0, 1, 2) |
| 1678 | self.check_swap_fds(0, 2, 1) |
| 1679 | self.check_swap_fds(1, 0, 2) |
| 1680 | self.check_swap_fds(1, 2, 0) |
| 1681 | self.check_swap_fds(2, 0, 1) |
| 1682 | self.check_swap_fds(2, 1, 0) |
| 1683 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1684 | def test_surrogates_error_message(self): |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 1685 | def prepare(): |
| 1686 | raise ValueError("surrogate:\uDCff") |
| 1687 | |
| 1688 | try: |
| 1689 | subprocess.call( |
| 1690 | [sys.executable, "-c", "pass"], |
| 1691 | preexec_fn=prepare) |
| 1692 | except ValueError as err: |
| 1693 | # Pure Python implementations keeps the message |
| 1694 | self.assertIsNone(subprocess._posixsubprocess) |
| 1695 | self.assertEqual(str(err), "surrogate:\uDCff") |
Gregory P. Smith | 8d07c26 | 2012-11-10 23:53:47 -0800 | [diff] [blame] | 1696 | except subprocess.SubprocessError as err: |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 1697 | # _posixsubprocess uses a default message |
| 1698 | self.assertIsNotNone(subprocess._posixsubprocess) |
| 1699 | self.assertEqual(str(err), "Exception occurred in preexec_fn.") |
| 1700 | else: |
Gregory P. Smith | 8d07c26 | 2012-11-10 23:53:47 -0800 | [diff] [blame] | 1701 | self.fail("Expected ValueError or subprocess.SubprocessError") |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 1702 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1703 | def test_undecodable_env(self): |
| 1704 | for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')): |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 1705 | encoded_value = value.encode("ascii", "surrogateescape") |
| 1706 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1707 | # test str with surrogates |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 1708 | script = "import os; print(ascii(os.getenv(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1709 | env = os.environ.copy() |
| 1710 | env[key] = value |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 1711 | # Use C locale to get ASCII for the locale encoding to force |
Victor Stinner | 89f3ad1 | 2010-10-14 10:43:31 +0000 | [diff] [blame] | 1712 | # surrogate-escaping of \xFF in the child process; otherwise it can |
| 1713 | # be decoded as-is if the default locale is latin-1. |
Victor Stinner | ebc78d2 | 2010-10-14 10:38:17 +0000 | [diff] [blame] | 1714 | env['LC_ALL'] = 'C' |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 1715 | if sys.platform.startswith("aix"): |
| 1716 | # On AIX, the C locale uses the Latin1 encoding |
| 1717 | decoded_value = encoded_value.decode("latin1", "surrogateescape") |
| 1718 | else: |
| 1719 | # On other UNIXes, the C locale uses the ASCII encoding |
| 1720 | decoded_value = value |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1721 | stdout = subprocess.check_output( |
| 1722 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1723 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1724 | stdout = stdout.rstrip(b'\n\r') |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 1725 | self.assertEqual(stdout.decode('ascii'), ascii(decoded_value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1726 | |
| 1727 | # test bytes |
| 1728 | key = key.encode("ascii", "surrogateescape") |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 1729 | script = "import os; print(ascii(os.getenvb(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1730 | env = os.environ.copy() |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 1731 | env[key] = encoded_value |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1732 | stdout = subprocess.check_output( |
| 1733 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1734 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1735 | stdout = stdout.rstrip(b'\n\r') |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 1736 | self.assertEqual(stdout.decode('ascii'), ascii(encoded_value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1737 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1738 | def test_bytes_program(self): |
| 1739 | abs_program = os.fsencode(sys.executable) |
| 1740 | path, program = os.path.split(sys.executable) |
| 1741 | program = os.fsencode(program) |
| 1742 | |
| 1743 | # absolute bytes path |
| 1744 | exitcode = subprocess.call([abs_program, "-c", "pass"]) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1745 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1746 | |
Victor Stinner | 7b3b20a | 2011-03-03 12:54:05 +0000 | [diff] [blame] | 1747 | # absolute bytes path as a string |
| 1748 | cmd = b"'" + abs_program + b"' -c pass" |
| 1749 | exitcode = subprocess.call(cmd, shell=True) |
| 1750 | self.assertEqual(exitcode, 0) |
| 1751 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1752 | # bytes program, unicode PATH |
| 1753 | env = os.environ.copy() |
| 1754 | env["PATH"] = path |
| 1755 | exitcode = subprocess.call([program, "-c", "pass"], env=env) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1756 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1757 | |
| 1758 | # bytes program, bytes PATH |
| 1759 | envb = os.environb.copy() |
| 1760 | envb[b"PATH"] = os.fsencode(path) |
| 1761 | exitcode = subprocess.call([program, "-c", "pass"], env=envb) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1762 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1763 | |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 1764 | def test_pipe_cloexec(self): |
| 1765 | sleeper = support.findfile("input_reader.py", subdir="subprocessdata") |
| 1766 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 1767 | |
| 1768 | p1 = subprocess.Popen([sys.executable, sleeper], |
| 1769 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1770 | stderr=subprocess.PIPE, close_fds=False) |
| 1771 | |
| 1772 | self.addCleanup(p1.communicate, b'') |
| 1773 | |
| 1774 | p2 = subprocess.Popen([sys.executable, fd_status], |
| 1775 | stdout=subprocess.PIPE, close_fds=False) |
| 1776 | |
| 1777 | output, error = p2.communicate() |
| 1778 | result_fds = set(map(int, output.split(b','))) |
| 1779 | unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(), |
| 1780 | p1.stderr.fileno()]) |
| 1781 | |
| 1782 | self.assertFalse(result_fds & unwanted_fds, |
| 1783 | "Expected no fds from %r to be open in child, " |
| 1784 | "found %r" % |
| 1785 | (unwanted_fds, result_fds & unwanted_fds)) |
| 1786 | |
| 1787 | def test_pipe_cloexec_real_tools(self): |
| 1788 | qcat = support.findfile("qcat.py", subdir="subprocessdata") |
| 1789 | qgrep = support.findfile("qgrep.py", subdir="subprocessdata") |
| 1790 | |
| 1791 | subdata = b'zxcvbn' |
| 1792 | data = subdata * 4 + b'\n' |
| 1793 | |
| 1794 | p1 = subprocess.Popen([sys.executable, qcat], |
| 1795 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1796 | close_fds=False) |
| 1797 | |
| 1798 | p2 = subprocess.Popen([sys.executable, qgrep, subdata], |
| 1799 | stdin=p1.stdout, stdout=subprocess.PIPE, |
| 1800 | close_fds=False) |
| 1801 | |
| 1802 | self.addCleanup(p1.wait) |
| 1803 | self.addCleanup(p2.wait) |
Gregory P. Smith | 886455c | 2012-01-21 22:05:10 -0800 | [diff] [blame] | 1804 | def kill_p1(): |
| 1805 | try: |
| 1806 | p1.terminate() |
| 1807 | except ProcessLookupError: |
| 1808 | pass |
| 1809 | def kill_p2(): |
| 1810 | try: |
| 1811 | p2.terminate() |
| 1812 | except ProcessLookupError: |
| 1813 | pass |
| 1814 | self.addCleanup(kill_p1) |
| 1815 | self.addCleanup(kill_p2) |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 1816 | |
| 1817 | p1.stdin.write(data) |
| 1818 | p1.stdin.close() |
| 1819 | |
| 1820 | readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10) |
| 1821 | |
| 1822 | self.assertTrue(readfiles, "The child hung") |
| 1823 | self.assertEqual(p2.stdout.read(), data) |
| 1824 | |
Victor Stinner | faa8c13 | 2011-01-03 16:36:00 +0000 | [diff] [blame] | 1825 | p1.stdout.close() |
| 1826 | p2.stdout.close() |
| 1827 | |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 1828 | def test_close_fds(self): |
| 1829 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 1830 | |
| 1831 | fds = os.pipe() |
| 1832 | self.addCleanup(os.close, fds[0]) |
| 1833 | self.addCleanup(os.close, fds[1]) |
| 1834 | |
| 1835 | open_fds = set(fds) |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 1836 | # add a bunch more fds |
| 1837 | for _ in range(9): |
| 1838 | fd = os.open("/dev/null", os.O_RDONLY) |
| 1839 | self.addCleanup(os.close, fd) |
| 1840 | open_fds.add(fd) |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 1841 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1842 | for fd in open_fds: |
| 1843 | os.set_inheritable(fd, True) |
| 1844 | |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 1845 | p = subprocess.Popen([sys.executable, fd_status], |
| 1846 | stdout=subprocess.PIPE, close_fds=False) |
| 1847 | output, ignored = p.communicate() |
| 1848 | remaining_fds = set(map(int, output.split(b','))) |
| 1849 | |
| 1850 | self.assertEqual(remaining_fds & open_fds, open_fds, |
| 1851 | "Some fds were closed") |
| 1852 | |
| 1853 | p = subprocess.Popen([sys.executable, fd_status], |
| 1854 | stdout=subprocess.PIPE, close_fds=True) |
| 1855 | output, ignored = p.communicate() |
| 1856 | remaining_fds = set(map(int, output.split(b','))) |
| 1857 | |
| 1858 | self.assertFalse(remaining_fds & open_fds, |
| 1859 | "Some fds were left open") |
| 1860 | self.assertIn(1, remaining_fds, "Subprocess failed") |
| 1861 | |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 1862 | # Keep some of the fd's we opened open in the subprocess. |
| 1863 | # This tests _posixsubprocess.c's proper handling of fds_to_keep. |
| 1864 | fds_to_keep = set(open_fds.pop() for _ in range(8)) |
| 1865 | p = subprocess.Popen([sys.executable, fd_status], |
| 1866 | stdout=subprocess.PIPE, close_fds=True, |
| 1867 | pass_fds=()) |
| 1868 | output, ignored = p.communicate() |
| 1869 | remaining_fds = set(map(int, output.split(b','))) |
| 1870 | |
| 1871 | self.assertFalse(remaining_fds & fds_to_keep & open_fds, |
| 1872 | "Some fds not in pass_fds were left open") |
| 1873 | self.assertIn(1, remaining_fds, "Subprocess failed") |
| 1874 | |
Victor Stinner | 88701e2 | 2011-06-01 13:13:04 +0200 | [diff] [blame] | 1875 | # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file |
| 1876 | # descriptor of a pipe closed in the parent process is valid in the |
| 1877 | # child process according to fstat(), but the mode of the file |
| 1878 | # descriptor is invalid, and read or write raise an error. |
| 1879 | @support.requires_mac_ver(10, 5) |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 1880 | def test_pass_fds(self): |
| 1881 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 1882 | |
| 1883 | open_fds = set() |
| 1884 | |
| 1885 | for x in range(5): |
| 1886 | fds = os.pipe() |
| 1887 | self.addCleanup(os.close, fds[0]) |
| 1888 | self.addCleanup(os.close, fds[1]) |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1889 | os.set_inheritable(fds[0], True) |
| 1890 | os.set_inheritable(fds[1], True) |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 1891 | open_fds.update(fds) |
| 1892 | |
| 1893 | for fd in open_fds: |
| 1894 | p = subprocess.Popen([sys.executable, fd_status], |
| 1895 | stdout=subprocess.PIPE, close_fds=True, |
| 1896 | pass_fds=(fd, )) |
| 1897 | output, ignored = p.communicate() |
| 1898 | |
| 1899 | remaining_fds = set(map(int, output.split(b','))) |
| 1900 | to_be_closed = open_fds - {fd} |
| 1901 | |
| 1902 | self.assertIn(fd, remaining_fds, "fd to be passed not passed") |
| 1903 | self.assertFalse(remaining_fds & to_be_closed, |
| 1904 | "fd to be closed passed") |
| 1905 | |
| 1906 | # pass_fds overrides close_fds with a warning. |
| 1907 | with self.assertWarns(RuntimeWarning) as context: |
| 1908 | self.assertFalse(subprocess.call( |
| 1909 | [sys.executable, "-c", "import sys; sys.exit(0)"], |
| 1910 | close_fds=False, pass_fds=(fd, ))) |
| 1911 | self.assertIn('overriding close_fds', str(context.warning)) |
| 1912 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1913 | def test_pass_fds_inheritable(self): |
Victor Stinner | f6fa22e | 2013-09-01 10:22:41 +0200 | [diff] [blame] | 1914 | script = support.findfile("fd_status.py", subdir="subprocessdata") |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1915 | |
| 1916 | inheritable, non_inheritable = os.pipe() |
| 1917 | self.addCleanup(os.close, inheritable) |
| 1918 | self.addCleanup(os.close, non_inheritable) |
| 1919 | os.set_inheritable(inheritable, True) |
| 1920 | os.set_inheritable(non_inheritable, False) |
| 1921 | pass_fds = (inheritable, non_inheritable) |
| 1922 | args = [sys.executable, script] |
| 1923 | args += list(map(str, pass_fds)) |
| 1924 | |
| 1925 | p = subprocess.Popen(args, |
| 1926 | stdout=subprocess.PIPE, close_fds=True, |
| 1927 | pass_fds=pass_fds) |
| 1928 | output, ignored = p.communicate() |
| 1929 | fds = set(map(int, output.split(b','))) |
| 1930 | |
| 1931 | # the inheritable file descriptor must be inherited, so its inheritable |
| 1932 | # 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] | 1933 | self.assertEqual(fds, set(pass_fds), "output=%a" % output) |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1934 | |
| 1935 | # inheritable flag must not be changed in the parent process |
| 1936 | self.assertEqual(os.get_inheritable(inheritable), True) |
| 1937 | self.assertEqual(os.get_inheritable(non_inheritable), False) |
| 1938 | |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 1939 | def test_stdout_stdin_are_single_inout_fd(self): |
| 1940 | with io.open(os.devnull, "r+") as inout: |
| 1941 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 1942 | stdout=inout, stdin=inout) |
| 1943 | p.wait() |
| 1944 | |
| 1945 | def test_stdout_stderr_are_single_inout_fd(self): |
| 1946 | with io.open(os.devnull, "r+") as inout: |
| 1947 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 1948 | stdout=inout, stderr=inout) |
| 1949 | p.wait() |
| 1950 | |
| 1951 | def test_stderr_stdin_are_single_inout_fd(self): |
| 1952 | with io.open(os.devnull, "r+") as inout: |
| 1953 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 1954 | stderr=inout, stdin=inout) |
| 1955 | p.wait() |
| 1956 | |
Gregory P. Smith | e85db2b | 2010-12-14 14:38:00 +0000 | [diff] [blame] | 1957 | def test_wait_when_sigchild_ignored(self): |
| 1958 | # NOTE: sigchild_ignore.py may not be an effective test on all OSes. |
| 1959 | sigchild_ignore = support.findfile("sigchild_ignore.py", |
| 1960 | subdir="subprocessdata") |
| 1961 | p = subprocess.Popen([sys.executable, sigchild_ignore], |
| 1962 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 1963 | stdout, stderr = p.communicate() |
| 1964 | self.assertEqual(0, p.returncode, "sigchild_ignore.py exited" |
Gregory P. Smith | a80f4fb | 2010-12-14 15:23:02 +0000 | [diff] [blame] | 1965 | " non-zero with this error:\n%s" % |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 1966 | stderr.decode('utf-8')) |
Gregory P. Smith | e85db2b | 2010-12-14 14:38:00 +0000 | [diff] [blame] | 1967 | |
Antoine Pitrou | 7b98d02 | 2011-03-19 17:04:13 +0100 | [diff] [blame] | 1968 | def test_select_unbuffered(self): |
| 1969 | # Issue #11459: bufsize=0 should really set the pipes as |
| 1970 | # unbuffered (and therefore let select() work properly). |
| 1971 | select = support.import_module("select") |
| 1972 | p = subprocess.Popen([sys.executable, "-c", |
| 1973 | 'import sys;' |
| 1974 | 'sys.stdout.write("apple")'], |
| 1975 | stdout=subprocess.PIPE, |
| 1976 | bufsize=0) |
| 1977 | f = p.stdout |
Ross Lagerwall | 17ace7a | 2011-03-26 21:21:46 +0200 | [diff] [blame] | 1978 | self.addCleanup(f.close) |
Antoine Pitrou | 7b98d02 | 2011-03-19 17:04:13 +0100 | [diff] [blame] | 1979 | try: |
| 1980 | self.assertEqual(f.read(4), b"appl") |
| 1981 | self.assertIn(f, select.select([f], [], [], 0.0)[0]) |
| 1982 | finally: |
| 1983 | p.wait() |
| 1984 | |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 1985 | def test_zombie_fast_process_del(self): |
| 1986 | # Issue #12650: on Unix, if Popen.__del__() was called before the |
| 1987 | # process exited, it wouldn't be added to subprocess._active, and would |
| 1988 | # remain a zombie. |
| 1989 | # spawn a Popen, and delete its reference before it exits |
| 1990 | p = subprocess.Popen([sys.executable, "-c", |
| 1991 | 'import sys, time;' |
| 1992 | 'time.sleep(0.2)'], |
| 1993 | stdout=subprocess.PIPE, |
| 1994 | stderr=subprocess.PIPE) |
Nadeem Vawda | 0d7cda3 | 2011-08-19 05:12:01 +0200 | [diff] [blame] | 1995 | self.addCleanup(p.stdout.close) |
| 1996 | self.addCleanup(p.stderr.close) |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 1997 | ident = id(p) |
| 1998 | pid = p.pid |
| 1999 | del p |
| 2000 | # check that p is in the active processes list |
| 2001 | self.assertIn(ident, [id(o) for o in subprocess._active]) |
| 2002 | |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2003 | def test_leak_fast_process_del_killed(self): |
| 2004 | # Issue #12650: on Unix, if Popen.__del__() was called before the |
| 2005 | # process exited, and the process got killed by a signal, it would never |
| 2006 | # be removed from subprocess._active, which triggered a FD and memory |
| 2007 | # leak. |
| 2008 | # spawn a Popen, delete its reference and kill it |
| 2009 | p = subprocess.Popen([sys.executable, "-c", |
| 2010 | 'import time;' |
| 2011 | 'time.sleep(3)'], |
| 2012 | stdout=subprocess.PIPE, |
| 2013 | stderr=subprocess.PIPE) |
Nadeem Vawda | 0d7cda3 | 2011-08-19 05:12:01 +0200 | [diff] [blame] | 2014 | self.addCleanup(p.stdout.close) |
| 2015 | self.addCleanup(p.stderr.close) |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2016 | ident = id(p) |
| 2017 | pid = p.pid |
| 2018 | del p |
| 2019 | os.kill(pid, signal.SIGKILL) |
| 2020 | # check that p is in the active processes list |
| 2021 | self.assertIn(ident, [id(o) for o in subprocess._active]) |
| 2022 | |
| 2023 | # let some time for the process to exit, and create a new Popen: this |
| 2024 | # should trigger the wait() of p |
| 2025 | time.sleep(0.2) |
Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 2026 | with self.assertRaises(OSError) as c: |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2027 | with subprocess.Popen(['nonexisting_i_hope'], |
| 2028 | stdout=subprocess.PIPE, |
| 2029 | stderr=subprocess.PIPE) as proc: |
| 2030 | pass |
| 2031 | # p should have been wait()ed on, and removed from the _active list |
| 2032 | self.assertRaises(OSError, os.waitpid, pid, 0) |
| 2033 | self.assertNotIn(ident, [id(o) for o in subprocess._active]) |
| 2034 | |
Charles-François Natali | 249cdc3 | 2013-08-25 18:24:45 +0200 | [diff] [blame] | 2035 | def test_close_fds_after_preexec(self): |
| 2036 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 2037 | |
| 2038 | # this FD is used as dup2() target by preexec_fn, and should be closed |
| 2039 | # in the child process |
| 2040 | fd = os.dup(1) |
| 2041 | self.addCleanup(os.close, fd) |
| 2042 | |
| 2043 | p = subprocess.Popen([sys.executable, fd_status], |
| 2044 | stdout=subprocess.PIPE, close_fds=True, |
| 2045 | preexec_fn=lambda: os.dup2(1, fd)) |
| 2046 | output, ignored = p.communicate() |
| 2047 | |
| 2048 | remaining_fds = set(map(int, output.split(b','))) |
| 2049 | |
| 2050 | self.assertNotIn(fd, remaining_fds) |
| 2051 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2052 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 2053 | @unittest.skipUnless(mswindows, "Windows specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 2054 | class Win32ProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 2055 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2056 | def test_startupinfo(self): |
| 2057 | # startupinfo argument |
| 2058 | # We uses hardcoded constants, because we do not want to |
| 2059 | # depend on win32all. |
| 2060 | STARTF_USESHOWWINDOW = 1 |
| 2061 | SW_MAXIMIZE = 3 |
| 2062 | startupinfo = subprocess.STARTUPINFO() |
| 2063 | startupinfo.dwFlags = STARTF_USESHOWWINDOW |
| 2064 | startupinfo.wShowWindow = SW_MAXIMIZE |
| 2065 | # Since Python is a console process, it won't be affected |
| 2066 | # by wShowWindow, but the argument should be silently |
| 2067 | # ignored |
| 2068 | subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2069 | startupinfo=startupinfo) |
| 2070 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2071 | def test_creationflags(self): |
| 2072 | # creationflags argument |
| 2073 | CREATE_NEW_CONSOLE = 16 |
| 2074 | sys.stderr.write(" a DOS box should flash briefly ...\n") |
| 2075 | subprocess.call(sys.executable + |
| 2076 | ' -c "import time; time.sleep(0.25)"', |
| 2077 | creationflags=CREATE_NEW_CONSOLE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2078 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2079 | def test_invalid_args(self): |
| 2080 | # invalid arguments should raise ValueError |
| 2081 | self.assertRaises(ValueError, subprocess.call, |
| 2082 | [sys.executable, "-c", |
| 2083 | "import sys; sys.exit(47)"], |
| 2084 | preexec_fn=lambda: 1) |
| 2085 | self.assertRaises(ValueError, subprocess.call, |
| 2086 | [sys.executable, "-c", |
| 2087 | "import sys; sys.exit(47)"], |
| 2088 | stdout=subprocess.PIPE, |
| 2089 | close_fds=True) |
| 2090 | |
| 2091 | def test_close_fds(self): |
| 2092 | # close file descriptors |
| 2093 | rc = subprocess.call([sys.executable, "-c", |
| 2094 | "import sys; sys.exit(47)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2095 | close_fds=True) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2096 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2097 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2098 | def test_shell_sequence(self): |
| 2099 | # Run command through the shell (sequence) |
| 2100 | newenv = os.environ.copy() |
| 2101 | newenv["FRUIT"] = "physalis" |
| 2102 | p = subprocess.Popen(["set"], shell=1, |
| 2103 | stdout=subprocess.PIPE, |
| 2104 | env=newenv) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 2105 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2106 | self.assertIn(b"physalis", p.stdout.read()) |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 2107 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2108 | def test_shell_string(self): |
| 2109 | # Run command through the shell (string) |
| 2110 | newenv = os.environ.copy() |
| 2111 | newenv["FRUIT"] = "physalis" |
| 2112 | p = subprocess.Popen("set", shell=1, |
| 2113 | stdout=subprocess.PIPE, |
| 2114 | env=newenv) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 2115 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2116 | self.assertIn(b"physalis", p.stdout.read()) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2117 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2118 | def test_call_string(self): |
| 2119 | # call() function with string argument on Windows |
| 2120 | rc = subprocess.call(sys.executable + |
| 2121 | ' -c "import sys; sys.exit(47)"') |
| 2122 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2123 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2124 | def _kill_process(self, method, *args): |
| 2125 | # Some win32 buildbot raises EOFError if stdin is inherited |
Antoine Pitrou | a4024e2 | 2010-09-24 18:57:01 +0000 | [diff] [blame] | 2126 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 2127 | import sys, time |
| 2128 | sys.stdout.write('x\\n') |
| 2129 | sys.stdout.flush() |
| 2130 | time.sleep(30) |
| 2131 | """], |
| 2132 | stdin=subprocess.PIPE, |
| 2133 | stdout=subprocess.PIPE, |
| 2134 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 2135 | self.addCleanup(p.stdout.close) |
| 2136 | self.addCleanup(p.stderr.close) |
| 2137 | self.addCleanup(p.stdin.close) |
Antoine Pitrou | a4024e2 | 2010-09-24 18:57:01 +0000 | [diff] [blame] | 2138 | # Wait for the interpreter to be completely initialized before |
| 2139 | # sending any signal. |
| 2140 | p.stdout.read(1) |
| 2141 | getattr(p, method)(*args) |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 2142 | _, stderr = p.communicate() |
| 2143 | self.assertStderrEqual(stderr, b'') |
Antoine Pitrou | a4024e2 | 2010-09-24 18:57:01 +0000 | [diff] [blame] | 2144 | returncode = p.wait() |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2145 | self.assertNotEqual(returncode, 0) |
| 2146 | |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 2147 | def _kill_dead_process(self, method, *args): |
| 2148 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 2149 | import sys, time |
| 2150 | sys.stdout.write('x\\n') |
| 2151 | sys.stdout.flush() |
| 2152 | sys.exit(42) |
| 2153 | """], |
| 2154 | stdin=subprocess.PIPE, |
| 2155 | stdout=subprocess.PIPE, |
| 2156 | stderr=subprocess.PIPE) |
| 2157 | self.addCleanup(p.stdout.close) |
| 2158 | self.addCleanup(p.stderr.close) |
| 2159 | self.addCleanup(p.stdin.close) |
| 2160 | # Wait for the interpreter to be completely initialized before |
| 2161 | # sending any signal. |
| 2162 | p.stdout.read(1) |
| 2163 | # The process should end after this |
| 2164 | time.sleep(1) |
| 2165 | # This shouldn't raise even though the child is now dead |
| 2166 | getattr(p, method)(*args) |
| 2167 | _, stderr = p.communicate() |
| 2168 | self.assertStderrEqual(stderr, b'') |
| 2169 | rc = p.wait() |
| 2170 | self.assertEqual(rc, 42) |
| 2171 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2172 | def test_send_signal(self): |
| 2173 | self._kill_process('send_signal', signal.SIGTERM) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 2174 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2175 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2176 | self._kill_process('kill') |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 2177 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2178 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2179 | self._kill_process('terminate') |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 2180 | |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 2181 | def test_send_signal_dead(self): |
| 2182 | self._kill_dead_process('send_signal', signal.SIGTERM) |
| 2183 | |
| 2184 | def test_kill_dead(self): |
| 2185 | self._kill_dead_process('kill') |
| 2186 | |
| 2187 | def test_terminate_dead(self): |
| 2188 | self._kill_dead_process('terminate') |
| 2189 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2190 | class CommandTests(unittest.TestCase): |
| 2191 | def test_getoutput(self): |
| 2192 | self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy') |
| 2193 | self.assertEqual(subprocess.getstatusoutput('echo xyzzy'), |
| 2194 | (0, 'xyzzy')) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 2195 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2196 | # we use mkdtemp in the next line to create an empty directory |
| 2197 | # under our exclusive control; from that, we can invent a pathname |
| 2198 | # that we _know_ won't exist. This is guaranteed to fail. |
| 2199 | dir = None |
| 2200 | try: |
| 2201 | dir = tempfile.mkdtemp() |
| 2202 | name = os.path.join(dir, "foo") |
Tim Golden | e004175 | 2013-11-03 12:53:17 +0000 | [diff] [blame] | 2203 | status, output = subprocess.getstatusoutput( |
| 2204 | ("type " if mswindows else "cat ") + name) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2205 | self.assertNotEqual(status, 0) |
| 2206 | finally: |
| 2207 | if dir is not None: |
| 2208 | os.rmdir(dir) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 2209 | |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 2210 | |
Charles-François Natali | 3a4586a | 2013-11-08 19:56:59 +0100 | [diff] [blame] | 2211 | @unittest.skipUnless(hasattr(selectors, 'PollSelector'), |
| 2212 | "Test needs selectors.PollSelector") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2213 | class ProcessTestCaseNoPoll(ProcessTestCase): |
| 2214 | def setUp(self): |
Charles-François Natali | 3a4586a | 2013-11-08 19:56:59 +0100 | [diff] [blame] | 2215 | self.orig_selector = subprocess._PopenSelector |
| 2216 | subprocess._PopenSelector = selectors.SelectSelector |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2217 | ProcessTestCase.setUp(self) |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 2218 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2219 | def tearDown(self): |
Charles-François Natali | 3a4586a | 2013-11-08 19:56:59 +0100 | [diff] [blame] | 2220 | subprocess._PopenSelector = self.orig_selector |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2221 | ProcessTestCase.tearDown(self) |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 2222 | |
| 2223 | |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 2224 | class HelperFunctionTests(unittest.TestCase): |
Gregory P. Smith | af6d3b8 | 2010-03-01 02:56:44 +0000 | [diff] [blame] | 2225 | @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows") |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 2226 | def test_eintr_retry_call(self): |
| 2227 | record_calls = [] |
| 2228 | def fake_os_func(*args): |
| 2229 | record_calls.append(args) |
| 2230 | if len(record_calls) == 2: |
| 2231 | raise OSError(errno.EINTR, "fake interrupted system call") |
| 2232 | return tuple(reversed(args)) |
| 2233 | |
| 2234 | self.assertEqual((999, 256), |
| 2235 | subprocess._eintr_retry_call(fake_os_func, 256, 999)) |
| 2236 | self.assertEqual([(256, 999)], record_calls) |
| 2237 | # This time there will be an EINTR so it will loop once. |
| 2238 | self.assertEqual((666,), |
| 2239 | subprocess._eintr_retry_call(fake_os_func, 666)) |
| 2240 | self.assertEqual([(256, 999), (666,), (666,)], record_calls) |
| 2241 | |
| 2242 | |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 2243 | @unittest.skipUnless(mswindows, "Windows-specific tests") |
| 2244 | class CommandsWithSpaces (BaseTestCase): |
| 2245 | |
| 2246 | def setUp(self): |
| 2247 | super().setUp() |
| 2248 | f, fname = mkstemp(".py", "te st") |
| 2249 | self.fname = fname.lower () |
| 2250 | os.write(f, b"import sys;" |
| 2251 | b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))" |
| 2252 | ) |
| 2253 | os.close(f) |
| 2254 | |
| 2255 | def tearDown(self): |
| 2256 | os.remove(self.fname) |
| 2257 | super().tearDown() |
| 2258 | |
| 2259 | def with_spaces(self, *args, **kwargs): |
| 2260 | kwargs['stdout'] = subprocess.PIPE |
| 2261 | p = subprocess.Popen(*args, **kwargs) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 2262 | self.addCleanup(p.stdout.close) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 2263 | self.assertEqual( |
| 2264 | p.stdout.read ().decode("mbcs"), |
| 2265 | "2 [%r, 'ab cd']" % self.fname |
| 2266 | ) |
| 2267 | |
| 2268 | def test_shell_string_with_spaces(self): |
| 2269 | # call() function with string argument with spaces on Windows |
Brian Curtin | d835cf1 | 2010-08-13 20:42:57 +0000 | [diff] [blame] | 2270 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 2271 | "ab cd"), shell=1) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 2272 | |
| 2273 | def test_shell_sequence_with_spaces(self): |
| 2274 | # call() function with sequence argument with spaces on Windows |
Brian Curtin | d835cf1 | 2010-08-13 20:42:57 +0000 | [diff] [blame] | 2275 | self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 2276 | |
| 2277 | def test_noshell_string_with_spaces(self): |
| 2278 | # call() function with string argument with spaces on Windows |
| 2279 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 2280 | "ab cd")) |
| 2281 | |
| 2282 | def test_noshell_sequence_with_spaces(self): |
| 2283 | # call() function with sequence argument with spaces on Windows |
| 2284 | self.with_spaces([sys.executable, self.fname, "ab cd"]) |
| 2285 | |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2286 | |
Georg Brandl | a86b262 | 2012-02-20 21:34:57 +0100 | [diff] [blame] | 2287 | class ContextManagerTests(BaseTestCase): |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2288 | |
| 2289 | def test_pipe(self): |
| 2290 | with subprocess.Popen([sys.executable, "-c", |
| 2291 | "import sys;" |
| 2292 | "sys.stdout.write('stdout');" |
| 2293 | "sys.stderr.write('stderr');"], |
| 2294 | stdout=subprocess.PIPE, |
| 2295 | stderr=subprocess.PIPE) as proc: |
| 2296 | self.assertEqual(proc.stdout.read(), b"stdout") |
| 2297 | self.assertStderrEqual(proc.stderr.read(), b"stderr") |
| 2298 | |
| 2299 | self.assertTrue(proc.stdout.closed) |
| 2300 | self.assertTrue(proc.stderr.closed) |
| 2301 | |
| 2302 | def test_returncode(self): |
| 2303 | with subprocess.Popen([sys.executable, "-c", |
| 2304 | "import sys; sys.exit(100)"]) as proc: |
Gregory P. Smith | 6b65745 | 2011-05-11 21:42:08 -0700 | [diff] [blame] | 2305 | pass |
| 2306 | # __exit__ calls wait(), so the returncode should be set |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2307 | self.assertEqual(proc.returncode, 100) |
| 2308 | |
| 2309 | def test_communicate_stdin(self): |
| 2310 | with subprocess.Popen([sys.executable, "-c", |
| 2311 | "import sys;" |
| 2312 | "sys.exit(sys.stdin.read() == 'context')"], |
| 2313 | stdin=subprocess.PIPE) as proc: |
| 2314 | proc.communicate(b"context") |
| 2315 | self.assertEqual(proc.returncode, 1) |
| 2316 | |
| 2317 | def test_invalid_args(self): |
Andrew Svetlov | b172697 | 2012-12-26 23:34:54 +0200 | [diff] [blame] | 2318 | with self.assertRaises(FileNotFoundError) as c: |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2319 | with subprocess.Popen(['nonexisting_i_hope'], |
| 2320 | stdout=subprocess.PIPE, |
| 2321 | stderr=subprocess.PIPE) as proc: |
| 2322 | pass |
| 2323 | |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2324 | |
Gregory P. Smith | 3b4652e | 2011-03-15 15:43:39 -0400 | [diff] [blame] | 2325 | def test_main(): |
| 2326 | unit_tests = (ProcessTestCase, |
| 2327 | POSIXProcessTestCase, |
| 2328 | Win32ProcessTestCase, |
Gregory P. Smith | 3b4652e | 2011-03-15 15:43:39 -0400 | [diff] [blame] | 2329 | CommandTests, |
| 2330 | ProcessTestCaseNoPoll, |
| 2331 | HelperFunctionTests, |
| 2332 | CommandsWithSpaces, |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 2333 | ContextManagerTests, |
| 2334 | ) |
Gregory P. Smith | 3b4652e | 2011-03-15 15:43:39 -0400 | [diff] [blame] | 2335 | |
| 2336 | support.run_unittest(*unit_tests) |
| 2337 | support.reap_children() |
| 2338 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2339 | if __name__ == "__main__": |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 2340 | unittest.main() |