Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1 | import unittest |
| 2 | from test import test_support |
| 3 | import subprocess |
| 4 | import sys |
Gregory P. Smith | f0739cb | 2017-01-22 22:38:28 -0800 | [diff] [blame] | 5 | import platform |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 6 | import signal |
| 7 | import os |
Gregory P. Smith | cce211f | 2010-03-01 00:05:08 +0000 | [diff] [blame] | 8 | import errno |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 9 | import tempfile |
| 10 | import time |
Tim Peters | 3761e8d | 2004-10-13 04:07:12 +0000 | [diff] [blame] | 11 | import re |
Ezio Melotti | 8f6a287 | 2010-02-10 21:40:33 +0000 | [diff] [blame] | 12 | import sysconfig |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 13 | |
Benjamin Peterson | 8b59c23 | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 14 | try: |
Gregory P. Smith | f0739cb | 2017-01-22 22:38:28 -0800 | [diff] [blame] | 15 | import ctypes |
| 16 | except ImportError: |
| 17 | ctypes = None |
| 18 | |
| 19 | try: |
Benjamin Peterson | 8b59c23 | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 20 | import resource |
| 21 | except ImportError: |
| 22 | resource = None |
Antoine Pitrou | 33fc744 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 23 | try: |
| 24 | import threading |
| 25 | except ImportError: |
| 26 | threading = None |
Benjamin Peterson | 8b59c23 | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 27 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 28 | mswindows = (sys.platform == "win32") |
| 29 | |
| 30 | # |
| 31 | # Depends on the following external programs: Python |
| 32 | # |
| 33 | |
| 34 | if mswindows: |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 35 | SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), ' |
| 36 | 'os.O_BINARY);') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 37 | else: |
| 38 | SETBINARY = '' |
| 39 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 40 | |
Florent Xicluna | fc4d6d7 | 2010-03-23 14:36:45 +0000 | [diff] [blame] | 41 | class BaseTestCase(unittest.TestCase): |
Neal Norwitz | b15ac31 | 2006-06-29 04:10:08 +0000 | [diff] [blame] | 42 | def setUp(self): |
Tim Peters | 38ff36c | 2006-06-30 06:18:39 +0000 | [diff] [blame] | 43 | # Try to minimize the number of children we have so this test |
| 44 | # doesn't crash on some buildbots (Alphas in particular). |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 45 | test_support.reap_children() |
Neal Norwitz | b15ac31 | 2006-06-29 04:10:08 +0000 | [diff] [blame] | 46 | |
Florent Xicluna | ab5e17f | 2010-03-04 21:31:58 +0000 | [diff] [blame] | 47 | def tearDown(self): |
| 48 | for inst in subprocess._active: |
| 49 | inst.wait() |
| 50 | subprocess._cleanup() |
| 51 | self.assertFalse(subprocess._active, "subprocess._active not empty") |
| 52 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 53 | def assertStderrEqual(self, stderr, expected, msg=None): |
| 54 | # In a debug build, stuff like "[6580 refs]" is printed to stderr at |
| 55 | # shutdown time. That frustrates tests trying to check stderr produced |
| 56 | # from a spawned Python process. |
| 57 | actual = re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr) |
| 58 | self.assertEqual(actual, expected, msg) |
Neal Norwitz | b15ac31 | 2006-06-29 04:10:08 +0000 | [diff] [blame] | 59 | |
Florent Xicluna | fc4d6d7 | 2010-03-23 14:36:45 +0000 | [diff] [blame] | 60 | |
Gregory P. Smith | 9d3b6e9 | 2012-11-10 22:49:03 -0800 | [diff] [blame] | 61 | class PopenTestException(Exception): |
| 62 | pass |
| 63 | |
| 64 | |
| 65 | class PopenExecuteChildRaises(subprocess.Popen): |
| 66 | """Popen subclass for testing cleanup of subprocess.PIPE filehandles when |
| 67 | _execute_child fails. |
| 68 | """ |
| 69 | def _execute_child(self, *args, **kwargs): |
| 70 | raise PopenTestException("Forced Exception for Test") |
| 71 | |
| 72 | |
Florent Xicluna | fc4d6d7 | 2010-03-23 14:36:45 +0000 | [diff] [blame] | 73 | class ProcessTestCase(BaseTestCase): |
| 74 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 75 | def test_call_seq(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 76 | # call() function with sequence argument |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 77 | rc = subprocess.call([sys.executable, "-c", |
| 78 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 79 | self.assertEqual(rc, 47) |
| 80 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 81 | def test_check_call_zero(self): |
| 82 | # check_call() function with zero return code |
| 83 | rc = subprocess.check_call([sys.executable, "-c", |
| 84 | "import sys; sys.exit(0)"]) |
| 85 | self.assertEqual(rc, 0) |
| 86 | |
| 87 | def test_check_call_nonzero(self): |
| 88 | # check_call() function with non-zero return code |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 89 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 90 | subprocess.check_call([sys.executable, "-c", |
| 91 | "import sys; sys.exit(47)"]) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 92 | self.assertEqual(c.exception.returncode, 47) |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 93 | |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 94 | def test_check_output(self): |
| 95 | # check_output() function with zero return code |
| 96 | output = subprocess.check_output( |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 97 | [sys.executable, "-c", "print 'BDFL'"]) |
Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 98 | self.assertIn('BDFL', output) |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 99 | |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 100 | def test_check_output_nonzero(self): |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 101 | # check_call() function with non-zero return code |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 102 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 103 | subprocess.check_output( |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 104 | [sys.executable, "-c", "import sys; sys.exit(5)"]) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 105 | self.assertEqual(c.exception.returncode, 5) |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 106 | |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 107 | def test_check_output_stderr(self): |
| 108 | # check_output() function stderr redirected to stdout |
| 109 | output = subprocess.check_output( |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 110 | [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"], |
| 111 | stderr=subprocess.STDOUT) |
Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 112 | self.assertIn('BDFL', output) |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 113 | |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 114 | def test_check_output_stdout_arg(self): |
| 115 | # check_output() function stderr redirected to stdout |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 116 | with self.assertRaises(ValueError) as c: |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 117 | output = subprocess.check_output( |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 118 | [sys.executable, "-c", "print 'will not be run'"], |
| 119 | stdout=sys.stdout) |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 120 | self.fail("Expected ValueError when stdout arg supplied.") |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 121 | self.assertIn('stdout', c.exception.args[0]) |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 122 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 123 | def test_call_kwargs(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 124 | # call() function with keyword args |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 125 | newenv = os.environ.copy() |
| 126 | newenv["FRUIT"] = "banana" |
| 127 | rc = subprocess.call([sys.executable, "-c", |
Florent Xicluna | bab22a7 | 2010-03-04 19:40:48 +0000 | [diff] [blame] | 128 | 'import sys, os;' |
| 129 | 'sys.exit(os.getenv("FRUIT")=="banana")'], |
| 130 | env=newenv) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 131 | self.assertEqual(rc, 1) |
| 132 | |
Victor Stinner | 776e69b | 2011-06-01 01:03:00 +0200 | [diff] [blame] | 133 | def test_invalid_args(self): |
| 134 | # Popen() called with invalid arguments should raise TypeError |
| 135 | # but Popen.__del__ should not complain (issue #12085) |
Victor Stinner | e9b185f | 2011-06-01 01:57:48 +0200 | [diff] [blame] | 136 | with test_support.captured_stderr() as s: |
Victor Stinner | 776e69b | 2011-06-01 01:03:00 +0200 | [diff] [blame] | 137 | self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1) |
| 138 | argcount = subprocess.Popen.__init__.__code__.co_argcount |
| 139 | too_many_args = [0] * (argcount + 1) |
| 140 | self.assertRaises(TypeError, subprocess.Popen, *too_many_args) |
| 141 | self.assertEqual(s.getvalue(), '') |
| 142 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 143 | def test_stdin_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 144 | # .stdin is None when not redirected |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 145 | p = subprocess.Popen([sys.executable, "-c", 'print "banana"'], |
| 146 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 147 | self.addCleanup(p.stdout.close) |
| 148 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 149 | p.wait() |
| 150 | self.assertEqual(p.stdin, None) |
| 151 | |
| 152 | def test_stdout_none(self): |
Ezio Melotti | efaad09 | 2013-03-11 00:34:33 +0200 | [diff] [blame] | 153 | # .stdout is None when not redirected, and the child's stdout will |
| 154 | # be inherited from the parent. In order to test this we run a |
| 155 | # subprocess in a subprocess: |
| 156 | # this_test |
| 157 | # \-- subprocess created by this test (parent) |
| 158 | # \-- subprocess created by the parent subprocess (child) |
| 159 | # The parent doesn't specify stdout, so the child will use the |
| 160 | # parent's stdout. This test checks that the message printed by the |
| 161 | # child goes to the parent stdout. The parent also checks that the |
| 162 | # child's stdout is None. See #11963. |
| 163 | code = ('import sys; from subprocess import Popen, PIPE;' |
| 164 | 'p = Popen([sys.executable, "-c", "print \'test_stdout_none\'"],' |
| 165 | ' stdin=PIPE, stderr=PIPE);' |
| 166 | 'p.wait(); assert p.stdout is None;') |
| 167 | p = subprocess.Popen([sys.executable, "-c", code], |
| 168 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 169 | self.addCleanup(p.stdout.close) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 170 | self.addCleanup(p.stderr.close) |
Ezio Melotti | efaad09 | 2013-03-11 00:34:33 +0200 | [diff] [blame] | 171 | out, err = p.communicate() |
| 172 | self.assertEqual(p.returncode, 0, err) |
| 173 | self.assertEqual(out.rstrip(), 'test_stdout_none') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 174 | |
| 175 | def test_stderr_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 176 | # .stderr is None when not redirected |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 177 | p = subprocess.Popen([sys.executable, "-c", 'print "banana"'], |
| 178 | stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 179 | self.addCleanup(p.stdout.close) |
| 180 | self.addCleanup(p.stdin.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 181 | p.wait() |
| 182 | self.assertEqual(p.stderr, None) |
| 183 | |
Ezio Melotti | 8f6a287 | 2010-02-10 21:40:33 +0000 | [diff] [blame] | 184 | def test_executable_with_cwd(self): |
Florent Xicluna | 6376370 | 2010-03-11 01:50:48 +0000 | [diff] [blame] | 185 | python_dir = os.path.dirname(os.path.realpath(sys.executable)) |
Ezio Melotti | 8f6a287 | 2010-02-10 21:40:33 +0000 | [diff] [blame] | 186 | p = subprocess.Popen(["somethingyoudonthave", "-c", |
| 187 | "import sys; sys.exit(47)"], |
| 188 | executable=sys.executable, cwd=python_dir) |
| 189 | p.wait() |
| 190 | self.assertEqual(p.returncode, 47) |
| 191 | |
| 192 | @unittest.skipIf(sysconfig.is_python_build(), |
| 193 | "need an installed Python. See #7774") |
| 194 | def test_executable_without_cwd(self): |
| 195 | # For a normal installation, it should work without 'cwd' |
| 196 | # argument. For test runs in the build directory, see #7774. |
| 197 | p = subprocess.Popen(["somethingyoudonthave", "-c", |
| 198 | "import sys; sys.exit(47)"], |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 199 | executable=sys.executable) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 200 | p.wait() |
| 201 | self.assertEqual(p.returncode, 47) |
| 202 | |
| 203 | def test_stdin_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 204 | # stdin redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 205 | p = subprocess.Popen([sys.executable, "-c", |
| 206 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 207 | stdin=subprocess.PIPE) |
| 208 | p.stdin.write("pear") |
| 209 | p.stdin.close() |
| 210 | p.wait() |
| 211 | self.assertEqual(p.returncode, 1) |
| 212 | |
| 213 | def test_stdin_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 214 | # stdin is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 215 | tf = tempfile.TemporaryFile() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 216 | d = tf.fileno() |
| 217 | os.write(d, "pear") |
| 218 | os.lseek(d, 0, 0) |
| 219 | p = subprocess.Popen([sys.executable, "-c", |
| 220 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 221 | stdin=d) |
| 222 | p.wait() |
| 223 | self.assertEqual(p.returncode, 1) |
| 224 | |
| 225 | def test_stdin_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 226 | # stdin is set to open file object |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 227 | tf = tempfile.TemporaryFile() |
| 228 | tf.write("pear") |
| 229 | tf.seek(0) |
| 230 | p = subprocess.Popen([sys.executable, "-c", |
| 231 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 232 | stdin=tf) |
| 233 | p.wait() |
| 234 | self.assertEqual(p.returncode, 1) |
| 235 | |
| 236 | def test_stdout_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 237 | # stdout redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 238 | p = subprocess.Popen([sys.executable, "-c", |
| 239 | 'import sys; sys.stdout.write("orange")'], |
| 240 | stdout=subprocess.PIPE) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 241 | self.addCleanup(p.stdout.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 242 | self.assertEqual(p.stdout.read(), "orange") |
| 243 | |
| 244 | def test_stdout_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 245 | # stdout is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 246 | tf = tempfile.TemporaryFile() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 247 | d = tf.fileno() |
| 248 | p = subprocess.Popen([sys.executable, "-c", |
| 249 | 'import sys; sys.stdout.write("orange")'], |
| 250 | stdout=d) |
| 251 | p.wait() |
| 252 | os.lseek(d, 0, 0) |
| 253 | self.assertEqual(os.read(d, 1024), "orange") |
| 254 | |
| 255 | def test_stdout_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 256 | # stdout is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 257 | tf = tempfile.TemporaryFile() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 258 | p = subprocess.Popen([sys.executable, "-c", |
| 259 | 'import sys; sys.stdout.write("orange")'], |
| 260 | stdout=tf) |
| 261 | p.wait() |
| 262 | tf.seek(0) |
| 263 | self.assertEqual(tf.read(), "orange") |
| 264 | |
| 265 | def test_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 266 | # stderr redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 267 | p = subprocess.Popen([sys.executable, "-c", |
| 268 | 'import sys; sys.stderr.write("strawberry")'], |
| 269 | stderr=subprocess.PIPE) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 270 | self.addCleanup(p.stderr.close) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 271 | self.assertStderrEqual(p.stderr.read(), "strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 272 | |
| 273 | def test_stderr_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 274 | # stderr is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 275 | tf = tempfile.TemporaryFile() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 276 | d = tf.fileno() |
| 277 | p = subprocess.Popen([sys.executable, "-c", |
| 278 | 'import sys; sys.stderr.write("strawberry")'], |
| 279 | stderr=d) |
| 280 | p.wait() |
| 281 | os.lseek(d, 0, 0) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 282 | self.assertStderrEqual(os.read(d, 1024), "strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 283 | |
| 284 | def test_stderr_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 285 | # stderr is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 286 | tf = tempfile.TemporaryFile() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 287 | p = subprocess.Popen([sys.executable, "-c", |
| 288 | 'import sys; sys.stderr.write("strawberry")'], |
| 289 | stderr=tf) |
| 290 | p.wait() |
| 291 | tf.seek(0) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 292 | self.assertStderrEqual(tf.read(), "strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 293 | |
Martin Panter | 1edccfa | 2016-05-13 01:54:44 +0000 | [diff] [blame] | 294 | def test_stderr_redirect_with_no_stdout_redirect(self): |
| 295 | # test stderr=STDOUT while stdout=None (not set) |
| 296 | |
| 297 | # - grandchild prints to stderr |
| 298 | # - child redirects grandchild's stderr to its stdout |
| 299 | # - the parent should get grandchild's stderr in child's stdout |
| 300 | p = subprocess.Popen([sys.executable, "-c", |
| 301 | 'import sys, subprocess;' |
| 302 | 'rc = subprocess.call([sys.executable, "-c",' |
| 303 | ' "import sys;"' |
| 304 | ' "sys.stderr.write(\'42\')"],' |
| 305 | ' stderr=subprocess.STDOUT);' |
| 306 | 'sys.exit(rc)'], |
| 307 | stdout=subprocess.PIPE, |
| 308 | stderr=subprocess.PIPE) |
| 309 | stdout, stderr = p.communicate() |
| 310 | #NOTE: stdout should get stderr from grandchild |
| 311 | self.assertStderrEqual(stdout, b'42') |
| 312 | self.assertStderrEqual(stderr, b'') # should be empty |
| 313 | self.assertEqual(p.returncode, 0) |
| 314 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 315 | def test_stdout_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 316 | # capture stdout and stderr to the same pipe |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 317 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 318 | 'import sys;' |
| 319 | 'sys.stdout.write("apple");' |
| 320 | 'sys.stdout.flush();' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 321 | 'sys.stderr.write("orange")'], |
| 322 | stdout=subprocess.PIPE, |
| 323 | stderr=subprocess.STDOUT) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 324 | self.addCleanup(p.stdout.close) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 325 | self.assertStderrEqual(p.stdout.read(), "appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 326 | |
| 327 | def test_stdout_stderr_file(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 328 | # capture stdout and stderr to the same open file |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 329 | tf = tempfile.TemporaryFile() |
| 330 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 331 | 'import sys;' |
| 332 | 'sys.stdout.write("apple");' |
| 333 | 'sys.stdout.flush();' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 334 | 'sys.stderr.write("orange")'], |
| 335 | stdout=tf, |
| 336 | stderr=tf) |
| 337 | p.wait() |
| 338 | tf.seek(0) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 339 | self.assertStderrEqual(tf.read(), "appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 340 | |
Gustavo Niemeyer | c36bede | 2006-09-07 00:48:33 +0000 | [diff] [blame] | 341 | def test_stdout_filedes_of_stdout(self): |
| 342 | # stdout is set to 1 (#1531862). |
Ezio Melotti | 9b9cd4c | 2013-03-11 03:21:08 +0200 | [diff] [blame] | 343 | # To avoid printing the text on stdout, we do something similar to |
Ezio Melotti | efaad09 | 2013-03-11 00:34:33 +0200 | [diff] [blame] | 344 | # test_stdout_none (see above). The parent subprocess calls the child |
| 345 | # subprocess passing stdout=1, and this test uses stdout=PIPE in |
| 346 | # order to capture and check the output of the parent. See #11963. |
| 347 | code = ('import sys, subprocess; ' |
| 348 | 'rc = subprocess.call([sys.executable, "-c", ' |
| 349 | ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), ' |
Ezio Melotti | 9b9cd4c | 2013-03-11 03:21:08 +0200 | [diff] [blame] | 350 | '\'test with stdout=1\'))"], stdout=1); ' |
| 351 | 'assert rc == 18') |
Ezio Melotti | efaad09 | 2013-03-11 00:34:33 +0200 | [diff] [blame] | 352 | p = subprocess.Popen([sys.executable, "-c", code], |
| 353 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 354 | self.addCleanup(p.stdout.close) |
| 355 | self.addCleanup(p.stderr.close) |
| 356 | out, err = p.communicate() |
| 357 | self.assertEqual(p.returncode, 0, err) |
Ezio Melotti | 9b9cd4c | 2013-03-11 03:21:08 +0200 | [diff] [blame] | 358 | self.assertEqual(out.rstrip(), 'test with stdout=1') |
Gustavo Niemeyer | c36bede | 2006-09-07 00:48:33 +0000 | [diff] [blame] | 359 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 360 | def test_cwd(self): |
Guido van Rossum | e9a0e88 | 2007-12-20 17:28:10 +0000 | [diff] [blame] | 361 | tmpdir = tempfile.gettempdir() |
Peter Astrand | 195404f | 2004-11-12 15:51:48 +0000 | [diff] [blame] | 362 | # We cannot use os.path.realpath to canonicalize the path, |
| 363 | # since it doesn't expand Tru64 {memb} strings. See bug 1063571. |
| 364 | cwd = os.getcwd() |
| 365 | os.chdir(tmpdir) |
| 366 | tmpdir = os.getcwd() |
| 367 | os.chdir(cwd) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 368 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 369 | 'import sys,os;' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 370 | 'sys.stdout.write(os.getcwd())'], |
| 371 | stdout=subprocess.PIPE, |
| 372 | cwd=tmpdir) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 373 | self.addCleanup(p.stdout.close) |
Fredrik Lundh | 59c0559 | 2004-10-13 06:55:40 +0000 | [diff] [blame] | 374 | normcase = os.path.normcase |
| 375 | self.assertEqual(normcase(p.stdout.read()), normcase(tmpdir)) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 376 | |
| 377 | def test_env(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 378 | newenv = os.environ.copy() |
| 379 | newenv["FRUIT"] = "orange" |
| 380 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 381 | 'import sys,os;' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 382 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 383 | stdout=subprocess.PIPE, |
| 384 | env=newenv) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 385 | self.addCleanup(p.stdout.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 386 | self.assertEqual(p.stdout.read(), "orange") |
| 387 | |
Serhiy Storchaka | 9dda2ca | 2017-06-24 11:49:00 +0300 | [diff] [blame^] | 388 | def test_invalid_cmd(self): |
| 389 | # null character in the command name |
| 390 | cmd = sys.executable + '\0' |
| 391 | with self.assertRaises(TypeError): |
| 392 | subprocess.Popen([cmd, "-c", "pass"]) |
| 393 | |
| 394 | # null character in the command argument |
| 395 | with self.assertRaises(TypeError): |
| 396 | subprocess.Popen([sys.executable, "-c", "pass#\0"]) |
| 397 | |
| 398 | def test_invalid_env(self): |
| 399 | # null character in the enviroment variable name |
| 400 | newenv = os.environ.copy() |
| 401 | newenv["FRUIT\0VEGETABLE"] = "cabbage" |
| 402 | with self.assertRaises(TypeError): |
| 403 | subprocess.Popen([sys.executable, "-c", "pass"], env=newenv) |
| 404 | |
| 405 | # null character in the enviroment variable value |
| 406 | newenv = os.environ.copy() |
| 407 | newenv["FRUIT"] = "orange\0VEGETABLE=cabbage" |
| 408 | with self.assertRaises(TypeError): |
| 409 | subprocess.Popen([sys.executable, "-c", "pass"], env=newenv) |
| 410 | |
| 411 | # equal character in the enviroment variable name |
| 412 | newenv = os.environ.copy() |
| 413 | newenv["FRUIT=ORANGE"] = "lemon" |
| 414 | with self.assertRaises(ValueError): |
| 415 | subprocess.Popen([sys.executable, "-c", "pass"], env=newenv) |
| 416 | |
| 417 | # equal character in the enviroment variable value |
| 418 | newenv = os.environ.copy() |
| 419 | newenv["FRUIT"] = "orange=lemon" |
| 420 | p = subprocess.Popen([sys.executable, "-c", |
| 421 | 'import sys, os;' |
| 422 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 423 | stdout=subprocess.PIPE, |
| 424 | env=newenv) |
| 425 | stdout, stderr = p.communicate() |
| 426 | self.assertEqual(stdout, "orange=lemon") |
| 427 | |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 428 | def test_communicate_stdin(self): |
| 429 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 430 | 'import sys;' |
| 431 | 'sys.exit(sys.stdin.read() == "pear")'], |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 432 | stdin=subprocess.PIPE) |
| 433 | p.communicate("pear") |
| 434 | self.assertEqual(p.returncode, 1) |
| 435 | |
| 436 | def test_communicate_stdout(self): |
| 437 | p = subprocess.Popen([sys.executable, "-c", |
| 438 | 'import sys; sys.stdout.write("pineapple")'], |
| 439 | stdout=subprocess.PIPE) |
| 440 | (stdout, stderr) = p.communicate() |
| 441 | self.assertEqual(stdout, "pineapple") |
| 442 | self.assertEqual(stderr, None) |
| 443 | |
| 444 | def test_communicate_stderr(self): |
| 445 | p = subprocess.Popen([sys.executable, "-c", |
| 446 | 'import sys; sys.stderr.write("pineapple")'], |
| 447 | stderr=subprocess.PIPE) |
| 448 | (stdout, stderr) = p.communicate() |
| 449 | self.assertEqual(stdout, None) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 450 | self.assertStderrEqual(stderr, "pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 451 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 452 | def test_communicate(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 453 | p = subprocess.Popen([sys.executable, "-c", |
Gregory P. Smith | 4036fd4 | 2008-05-26 20:22:14 +0000 | [diff] [blame] | 454 | 'import sys,os;' |
| 455 | 'sys.stderr.write("pineapple");' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 456 | 'sys.stdout.write(sys.stdin.read())'], |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 457 | stdin=subprocess.PIPE, |
| 458 | stdout=subprocess.PIPE, |
| 459 | stderr=subprocess.PIPE) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 460 | self.addCleanup(p.stdout.close) |
| 461 | self.addCleanup(p.stderr.close) |
| 462 | self.addCleanup(p.stdin.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 463 | (stdout, stderr) = p.communicate("banana") |
| 464 | self.assertEqual(stdout, "banana") |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 465 | self.assertStderrEqual(stderr, "pineapple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 466 | |
Gregory P. Smith | 4036fd4 | 2008-05-26 20:22:14 +0000 | [diff] [blame] | 467 | # This test is Linux specific for simplicity to at least have |
| 468 | # some coverage. It is not a platform specific bug. |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 469 | @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()), |
| 470 | "Linux specific") |
| 471 | # Test for the fd leak reported in http://bugs.python.org/issue2791. |
| 472 | def test_communicate_pipe_fd_leak(self): |
| 473 | fd_directory = '/proc/%d/fd' % os.getpid() |
| 474 | num_fds_before_popen = len(os.listdir(fd_directory)) |
Martin Panter | ad6a99c | 2016-09-10 10:38:22 +0000 | [diff] [blame] | 475 | p = subprocess.Popen([sys.executable, "-c", "print('')"], |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 476 | stdout=subprocess.PIPE) |
| 477 | p.communicate() |
| 478 | num_fds_after_communicate = len(os.listdir(fd_directory)) |
| 479 | del p |
| 480 | num_fds_after_destruction = len(os.listdir(fd_directory)) |
| 481 | self.assertEqual(num_fds_before_popen, num_fds_after_destruction) |
| 482 | self.assertEqual(num_fds_before_popen, num_fds_after_communicate) |
Gregory P. Smith | 4036fd4 | 2008-05-26 20:22:14 +0000 | [diff] [blame] | 483 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 484 | def test_communicate_returns(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 485 | # communicate() should return None if no redirection is active |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 486 | p = subprocess.Popen([sys.executable, "-c", |
| 487 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 488 | (stdout, stderr) = p.communicate() |
| 489 | self.assertEqual(stdout, None) |
| 490 | self.assertEqual(stderr, None) |
| 491 | |
| 492 | def test_communicate_pipe_buf(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 493 | # communicate() with writes larger than pipe_buf |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 494 | # This test will probably deadlock rather than fail, if |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 495 | # communicate() does not work properly. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 496 | x, y = os.pipe() |
| 497 | if mswindows: |
| 498 | pipe_buf = 512 |
| 499 | else: |
| 500 | pipe_buf = os.fpathconf(x, "PC_PIPE_BUF") |
| 501 | os.close(x) |
| 502 | os.close(y) |
| 503 | p = subprocess.Popen([sys.executable, "-c", |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 504 | 'import sys,os;' |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 505 | 'sys.stdout.write(sys.stdin.read(47));' |
| 506 | 'sys.stderr.write("xyz"*%d);' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 507 | 'sys.stdout.write(sys.stdin.read())' % pipe_buf], |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 508 | stdin=subprocess.PIPE, |
| 509 | stdout=subprocess.PIPE, |
| 510 | stderr=subprocess.PIPE) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 511 | self.addCleanup(p.stdout.close) |
| 512 | self.addCleanup(p.stderr.close) |
| 513 | self.addCleanup(p.stdin.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 514 | string_to_write = "abc"*pipe_buf |
| 515 | (stdout, stderr) = p.communicate(string_to_write) |
| 516 | self.assertEqual(stdout, string_to_write) |
| 517 | |
| 518 | def test_writes_before_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 519 | # stdin.write before communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 520 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 521 | 'import sys,os;' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 522 | 'sys.stdout.write(sys.stdin.read())'], |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 523 | stdin=subprocess.PIPE, |
| 524 | stdout=subprocess.PIPE, |
| 525 | stderr=subprocess.PIPE) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 526 | self.addCleanup(p.stdout.close) |
| 527 | self.addCleanup(p.stderr.close) |
| 528 | self.addCleanup(p.stdin.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 529 | p.stdin.write("banana") |
| 530 | (stdout, stderr) = p.communicate("split") |
| 531 | self.assertEqual(stdout, "bananasplit") |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 532 | self.assertStderrEqual(stderr, "") |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 533 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 534 | def test_universal_newlines(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 535 | p = subprocess.Popen([sys.executable, "-c", |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 536 | 'import sys,os;' + SETBINARY + |
| 537 | 'sys.stdout.write("line1\\n");' |
| 538 | 'sys.stdout.flush();' |
| 539 | 'sys.stdout.write("line2\\r");' |
| 540 | 'sys.stdout.flush();' |
| 541 | 'sys.stdout.write("line3\\r\\n");' |
| 542 | 'sys.stdout.flush();' |
| 543 | 'sys.stdout.write("line4\\r");' |
| 544 | 'sys.stdout.flush();' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 545 | 'sys.stdout.write("\\nline5");' |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 546 | 'sys.stdout.flush();' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 547 | 'sys.stdout.write("\\nline6");'], |
| 548 | stdout=subprocess.PIPE, |
| 549 | universal_newlines=1) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 550 | self.addCleanup(p.stdout.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 551 | stdout = p.stdout.read() |
Neal Norwitz | a6d01ce | 2006-05-02 06:23:22 +0000 | [diff] [blame] | 552 | if hasattr(file, 'newlines'): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 553 | # Interpreter with universal newline support |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 554 | self.assertEqual(stdout, |
| 555 | "line1\nline2\nline3\nline4\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 556 | else: |
| 557 | # Interpreter without universal newline support |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 558 | self.assertEqual(stdout, |
| 559 | "line1\nline2\rline3\r\nline4\r\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 560 | |
| 561 | def test_universal_newlines_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 562 | # universal newlines through communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 563 | p = subprocess.Popen([sys.executable, "-c", |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 564 | 'import sys,os;' + SETBINARY + |
| 565 | 'sys.stdout.write("line1\\n");' |
| 566 | 'sys.stdout.flush();' |
| 567 | 'sys.stdout.write("line2\\r");' |
| 568 | 'sys.stdout.flush();' |
| 569 | 'sys.stdout.write("line3\\r\\n");' |
| 570 | 'sys.stdout.flush();' |
| 571 | 'sys.stdout.write("line4\\r");' |
| 572 | 'sys.stdout.flush();' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 573 | 'sys.stdout.write("\\nline5");' |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 574 | 'sys.stdout.flush();' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 575 | 'sys.stdout.write("\\nline6");'], |
| 576 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 577 | universal_newlines=1) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 578 | self.addCleanup(p.stdout.close) |
| 579 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 580 | (stdout, stderr) = p.communicate() |
Neal Norwitz | a6d01ce | 2006-05-02 06:23:22 +0000 | [diff] [blame] | 581 | if hasattr(file, 'newlines'): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 582 | # Interpreter with universal newline support |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 583 | self.assertEqual(stdout, |
| 584 | "line1\nline2\nline3\nline4\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 585 | else: |
| 586 | # Interpreter without universal newline support |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 587 | self.assertEqual(stdout, |
| 588 | "line1\nline2\rline3\r\nline4\r\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 589 | |
| 590 | def test_no_leaking(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 591 | # Make sure we leak no resources |
Antoine Pitrou | b0b3bff | 2010-09-18 22:42:30 +0000 | [diff] [blame] | 592 | if not mswindows: |
Peter Astrand | f7f1bb7 | 2005-03-03 20:47:37 +0000 | [diff] [blame] | 593 | max_handles = 1026 # too much for most UNIX systems |
| 594 | else: |
Antoine Pitrou | b0b3bff | 2010-09-18 22:42:30 +0000 | [diff] [blame] | 595 | max_handles = 2050 # too much for (at least some) Windows setups |
| 596 | handles = [] |
| 597 | try: |
| 598 | for i in range(max_handles): |
| 599 | try: |
| 600 | handles.append(os.open(test_support.TESTFN, |
| 601 | os.O_WRONLY | os.O_CREAT)) |
| 602 | except OSError as e: |
| 603 | if e.errno != errno.EMFILE: |
| 604 | raise |
| 605 | break |
| 606 | else: |
| 607 | self.skipTest("failed to reach the file descriptor limit " |
| 608 | "(tried %d)" % max_handles) |
| 609 | # Close a couple of them (should be enough for a subprocess) |
| 610 | for i in range(10): |
| 611 | os.close(handles.pop()) |
| 612 | # Loop creating some subprocesses. If one of them leaks some fds, |
| 613 | # the next loop iteration will fail by reaching the max fd limit. |
| 614 | for i in range(15): |
| 615 | p = subprocess.Popen([sys.executable, "-c", |
| 616 | "import sys;" |
| 617 | "sys.stdout.write(sys.stdin.read())"], |
| 618 | stdin=subprocess.PIPE, |
| 619 | stdout=subprocess.PIPE, |
| 620 | stderr=subprocess.PIPE) |
| 621 | data = p.communicate(b"lime")[0] |
| 622 | self.assertEqual(data, b"lime") |
| 623 | finally: |
| 624 | for h in handles: |
| 625 | os.close(h) |
Mark Dickinson | 313dc9b | 2012-10-07 15:41:38 +0100 | [diff] [blame] | 626 | test_support.unlink(test_support.TESTFN) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 627 | |
| 628 | def test_list2cmdline(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 629 | self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']), |
| 630 | '"a b c" d e') |
| 631 | self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']), |
| 632 | 'ab\\"c \\ d') |
Gregory P. Smith | e047e6d | 2008-01-19 20:49:02 +0000 | [diff] [blame] | 633 | self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']), |
| 634 | 'ab\\"c " \\\\" d') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 635 | self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']), |
| 636 | 'a\\\\\\b "de fg" h') |
| 637 | self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']), |
| 638 | 'a\\\\\\"b c d') |
| 639 | self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']), |
| 640 | '"a\\\\b c" d e') |
| 641 | self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']), |
| 642 | '"a\\\\b\\ c" d e') |
Peter Astrand | 10514a7 | 2007-01-13 22:35:35 +0000 | [diff] [blame] | 643 | self.assertEqual(subprocess.list2cmdline(['ab', '']), |
| 644 | 'ab ""') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 645 | |
| 646 | |
| 647 | def test_poll(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 648 | p = subprocess.Popen([sys.executable, |
Tim Peters | 29b6b4f | 2004-10-13 03:43:40 +0000 | [diff] [blame] | 649 | "-c", "import time; time.sleep(1)"]) |
| 650 | count = 0 |
| 651 | while p.poll() is None: |
| 652 | time.sleep(0.1) |
| 653 | count += 1 |
| 654 | # We expect that the poll loop probably went around about 10 times, |
| 655 | # but, based on system scheduling we can't control, it's possible |
| 656 | # poll() never returned None. It "should be" very rare that it |
| 657 | # didn't go around at least twice. |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 658 | self.assertGreaterEqual(count, 2) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 659 | # Subsequent invocations should just return the returncode |
| 660 | self.assertEqual(p.poll(), 0) |
| 661 | |
| 662 | |
| 663 | def test_wait(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 664 | p = subprocess.Popen([sys.executable, |
| 665 | "-c", "import time; time.sleep(2)"]) |
| 666 | self.assertEqual(p.wait(), 0) |
| 667 | # Subsequent invocations should just return the returncode |
| 668 | self.assertEqual(p.wait(), 0) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 669 | |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 670 | |
| 671 | def test_invalid_bufsize(self): |
| 672 | # an invalid type of the bufsize argument should raise |
| 673 | # TypeError. |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 674 | with self.assertRaises(TypeError): |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 675 | subprocess.Popen([sys.executable, "-c", "pass"], "orange") |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 676 | |
Georg Brandl | f3715d2 | 2009-02-14 17:01:36 +0000 | [diff] [blame] | 677 | def test_leaking_fds_on_error(self): |
| 678 | # see bug #5179: Popen leaks file descriptors to PIPEs if |
| 679 | # the child fails to execute; this will eventually exhaust |
| 680 | # the maximum number of open fds. 1024 seems a very common |
| 681 | # value for that limit, but Windows has 2048, so we loop |
| 682 | # 1024 times (each call leaked two fds). |
| 683 | for i in range(1024): |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 684 | # Windows raises IOError. Others raise OSError. |
| 685 | with self.assertRaises(EnvironmentError) as c: |
Georg Brandl | f3715d2 | 2009-02-14 17:01:36 +0000 | [diff] [blame] | 686 | subprocess.Popen(['nonexisting_i_hope'], |
| 687 | stdout=subprocess.PIPE, |
| 688 | stderr=subprocess.PIPE) |
R David Murray | cdd5fc9 | 2011-03-13 22:37:18 -0400 | [diff] [blame] | 689 | # ignore errors that indicate the command was not found |
| 690 | if c.exception.errno not in (errno.ENOENT, errno.EACCES): |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 691 | raise c.exception |
Georg Brandl | f3715d2 | 2009-02-14 17:01:36 +0000 | [diff] [blame] | 692 | |
Antoine Pitrou | 33fc744 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 693 | @unittest.skipIf(threading is None, "threading required") |
| 694 | def test_double_close_on_error(self): |
| 695 | # Issue #18851 |
| 696 | fds = [] |
| 697 | def open_fds(): |
| 698 | for i in range(20): |
| 699 | fds.extend(os.pipe()) |
| 700 | time.sleep(0.001) |
| 701 | t = threading.Thread(target=open_fds) |
| 702 | t.start() |
| 703 | try: |
| 704 | with self.assertRaises(EnvironmentError): |
| 705 | subprocess.Popen(['nonexisting_i_hope'], |
| 706 | stdin=subprocess.PIPE, |
| 707 | stdout=subprocess.PIPE, |
| 708 | stderr=subprocess.PIPE) |
| 709 | finally: |
| 710 | t.join() |
| 711 | exc = None |
| 712 | for fd in fds: |
| 713 | # If a double close occurred, some of those fds will |
| 714 | # already have been closed by mistake, and os.close() |
| 715 | # here will raise. |
| 716 | try: |
| 717 | os.close(fd) |
| 718 | except OSError as e: |
| 719 | exc = e |
| 720 | if exc is not None: |
| 721 | raise exc |
| 722 | |
Tim Golden | 90374f5 | 2010-08-06 13:14:33 +0000 | [diff] [blame] | 723 | def test_handles_closed_on_exception(self): |
| 724 | # If CreateProcess exits with an error, ensure the |
| 725 | # duplicate output handles are released |
Berker Peksag | b7c3515 | 2015-09-28 15:37:57 +0300 | [diff] [blame] | 726 | ifhandle, ifname = tempfile.mkstemp() |
| 727 | ofhandle, ofname = tempfile.mkstemp() |
| 728 | efhandle, efname = tempfile.mkstemp() |
Tim Golden | 90374f5 | 2010-08-06 13:14:33 +0000 | [diff] [blame] | 729 | try: |
| 730 | subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle, |
| 731 | stderr=efhandle) |
| 732 | except OSError: |
| 733 | os.close(ifhandle) |
| 734 | os.remove(ifname) |
| 735 | os.close(ofhandle) |
| 736 | os.remove(ofname) |
| 737 | os.close(efhandle) |
| 738 | os.remove(efname) |
| 739 | self.assertFalse(os.path.exists(ifname)) |
| 740 | self.assertFalse(os.path.exists(ofname)) |
| 741 | self.assertFalse(os.path.exists(efname)) |
| 742 | |
Ross Lagerwall | 104c3f1 | 2011-04-05 15:24:34 +0200 | [diff] [blame] | 743 | def test_communicate_epipe(self): |
| 744 | # Issue 10963: communicate() should hide EPIPE |
| 745 | p = subprocess.Popen([sys.executable, "-c", 'pass'], |
| 746 | stdin=subprocess.PIPE, |
| 747 | stdout=subprocess.PIPE, |
| 748 | stderr=subprocess.PIPE) |
| 749 | self.addCleanup(p.stdout.close) |
| 750 | self.addCleanup(p.stderr.close) |
| 751 | self.addCleanup(p.stdin.close) |
| 752 | p.communicate("x" * 2**20) |
| 753 | |
| 754 | def test_communicate_epipe_only_stdin(self): |
| 755 | # Issue 10963: communicate() should hide EPIPE |
| 756 | p = subprocess.Popen([sys.executable, "-c", 'pass'], |
| 757 | stdin=subprocess.PIPE) |
| 758 | self.addCleanup(p.stdin.close) |
| 759 | time.sleep(2) |
| 760 | p.communicate("x" * 2**20) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 761 | |
Gregory P. Smith | 9d3b6e9 | 2012-11-10 22:49:03 -0800 | [diff] [blame] | 762 | # This test is Linux-ish specific for simplicity to at least have |
| 763 | # some coverage. It is not a platform specific bug. |
| 764 | @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()), |
| 765 | "Linux specific") |
| 766 | def test_failed_child_execute_fd_leak(self): |
| 767 | """Test for the fork() failure fd leak reported in issue16327.""" |
| 768 | fd_directory = '/proc/%d/fd' % os.getpid() |
| 769 | fds_before_popen = os.listdir(fd_directory) |
| 770 | with self.assertRaises(PopenTestException): |
| 771 | PopenExecuteChildRaises( |
| 772 | [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE, |
| 773 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 774 | |
| 775 | # NOTE: This test doesn't verify that the real _execute_child |
| 776 | # does not close the file descriptors itself on the way out |
| 777 | # during an exception. Code inspection has confirmed that. |
| 778 | |
| 779 | fds_after_exception = os.listdir(fd_directory) |
| 780 | self.assertEqual(fds_before_popen, fds_after_exception) |
| 781 | |
| 782 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 783 | # context manager |
| 784 | class _SuppressCoreFiles(object): |
| 785 | """Try to prevent core files from being created.""" |
| 786 | old_limit = None |
| 787 | |
| 788 | def __enter__(self): |
| 789 | """Try to save previous ulimit, then set it to (0, 0).""" |
Benjamin Peterson | 8b59c23 | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 790 | if resource is not None: |
| 791 | try: |
| 792 | self.old_limit = resource.getrlimit(resource.RLIMIT_CORE) |
| 793 | resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) |
| 794 | except (ValueError, resource.error): |
| 795 | pass |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 796 | |
Ronald Oussoren | 21b44e0 | 2010-07-23 12:26:30 +0000 | [diff] [blame] | 797 | if sys.platform == 'darwin': |
| 798 | # Check if the 'Crash Reporter' on OSX was configured |
| 799 | # in 'Developer' mode and warn that it will get triggered |
| 800 | # when it is. |
| 801 | # |
| 802 | # This assumes that this context manager is used in tests |
| 803 | # that might trigger the next manager. |
| 804 | value = subprocess.Popen(['/usr/bin/defaults', 'read', |
| 805 | 'com.apple.CrashReporter', 'DialogType'], |
| 806 | stdout=subprocess.PIPE).communicate()[0] |
| 807 | if value.strip() == b'developer': |
| 808 | print "this tests triggers the Crash Reporter, that is intentional" |
| 809 | sys.stdout.flush() |
| 810 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 811 | def __exit__(self, *args): |
| 812 | """Return core file behavior to default.""" |
| 813 | if self.old_limit is None: |
| 814 | return |
Benjamin Peterson | 8b59c23 | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 815 | if resource is not None: |
| 816 | try: |
| 817 | resource.setrlimit(resource.RLIMIT_CORE, self.old_limit) |
| 818 | except (ValueError, resource.error): |
| 819 | pass |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 820 | |
Victor Stinner | b78fed9 | 2011-07-05 14:50:35 +0200 | [diff] [blame] | 821 | @unittest.skipUnless(hasattr(signal, 'SIGALRM'), |
| 822 | "Requires signal.SIGALRM") |
Victor Stinner | e790131 | 2011-07-05 14:08:01 +0200 | [diff] [blame] | 823 | def test_communicate_eintr(self): |
| 824 | # Issue #12493: communicate() should handle EINTR |
| 825 | def handler(signum, frame): |
| 826 | pass |
| 827 | old_handler = signal.signal(signal.SIGALRM, handler) |
| 828 | self.addCleanup(signal.signal, signal.SIGALRM, old_handler) |
| 829 | |
| 830 | # the process is running for 2 seconds |
| 831 | args = [sys.executable, "-c", 'import time; time.sleep(2)'] |
| 832 | for stream in ('stdout', 'stderr'): |
| 833 | kw = {stream: subprocess.PIPE} |
| 834 | with subprocess.Popen(args, **kw) as process: |
| 835 | signal.alarm(1) |
| 836 | # communicate() will be interrupted by SIGALRM |
| 837 | process.communicate() |
| 838 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 839 | |
Florent Xicluna | bab22a7 | 2010-03-04 19:40:48 +0000 | [diff] [blame] | 840 | @unittest.skipIf(mswindows, "POSIX specific tests") |
Florent Xicluna | fc4d6d7 | 2010-03-23 14:36:45 +0000 | [diff] [blame] | 841 | class POSIXProcessTestCase(BaseTestCase): |
Florent Xicluna | ab5e17f | 2010-03-04 21:31:58 +0000 | [diff] [blame] | 842 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 843 | def test_exceptions(self): |
| 844 | # caught & re-raised exceptions |
| 845 | with self.assertRaises(OSError) as c: |
| 846 | p = subprocess.Popen([sys.executable, "-c", ""], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 847 | cwd="/this/path/does/not/exist") |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 848 | # The attribute child_traceback should contain "os.chdir" somewhere. |
| 849 | self.assertIn("os.chdir", c.exception.child_traceback) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 850 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 851 | def test_run_abort(self): |
| 852 | # returncode handles signal termination |
| 853 | with _SuppressCoreFiles(): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 854 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 855 | "import os; os.abort()"]) |
| 856 | p.wait() |
| 857 | self.assertEqual(-p.returncode, signal.SIGABRT) |
| 858 | |
| 859 | def test_preexec(self): |
| 860 | # preexec function |
| 861 | p = subprocess.Popen([sys.executable, "-c", |
| 862 | "import sys, os;" |
| 863 | "sys.stdout.write(os.getenv('FRUIT'))"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 864 | stdout=subprocess.PIPE, |
| 865 | preexec_fn=lambda: os.putenv("FRUIT", "apple")) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 866 | self.addCleanup(p.stdout.close) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 867 | self.assertEqual(p.stdout.read(), "apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 868 | |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 869 | class _TestExecuteChildPopen(subprocess.Popen): |
| 870 | """Used to test behavior at the end of _execute_child.""" |
| 871 | def __init__(self, testcase, *args, **kwargs): |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 872 | self._testcase = testcase |
| 873 | subprocess.Popen.__init__(self, *args, **kwargs) |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 874 | |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 875 | def _execute_child( |
| 876 | self, args, executable, preexec_fn, close_fds, cwd, env, |
Antoine Pitrou | 33fc744 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 877 | universal_newlines, startupinfo, creationflags, shell, to_close, |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 878 | p2cread, p2cwrite, |
| 879 | c2pread, c2pwrite, |
| 880 | errread, errwrite): |
| 881 | try: |
| 882 | subprocess.Popen._execute_child( |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 883 | self, args, executable, preexec_fn, close_fds, |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 884 | cwd, env, universal_newlines, |
Antoine Pitrou | 33fc744 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 885 | startupinfo, creationflags, shell, to_close, |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 886 | p2cread, p2cwrite, |
| 887 | c2pread, c2pwrite, |
| 888 | errread, errwrite) |
| 889 | finally: |
| 890 | # Open a bunch of file descriptors and verify that |
| 891 | # none of them are the same as the ones the Popen |
| 892 | # instance is using for stdin/stdout/stderr. |
| 893 | devzero_fds = [os.open("/dev/zero", os.O_RDONLY) |
| 894 | for _ in range(8)] |
| 895 | try: |
| 896 | for fd in devzero_fds: |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 897 | self._testcase.assertNotIn( |
| 898 | fd, (p2cwrite, c2pread, errread)) |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 899 | finally: |
Richard Oudkerk | 045e457 | 2013-06-10 16:27:45 +0100 | [diff] [blame] | 900 | for fd in devzero_fds: |
| 901 | os.close(fd) |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 902 | |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 903 | @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.") |
| 904 | def test_preexec_errpipe_does_not_double_close_pipes(self): |
| 905 | """Issue16140: Don't double close pipes on preexec error.""" |
| 906 | |
| 907 | def raise_it(): |
| 908 | raise RuntimeError("force the _execute_child() errpipe_data path.") |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 909 | |
| 910 | with self.assertRaises(RuntimeError): |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 911 | self._TestExecuteChildPopen( |
| 912 | self, [sys.executable, "-c", "pass"], |
| 913 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 914 | stderr=subprocess.PIPE, preexec_fn=raise_it) |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 915 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 916 | def test_args_string(self): |
| 917 | # args is a string |
Berker Peksag | b7c3515 | 2015-09-28 15:37:57 +0300 | [diff] [blame] | 918 | f, fname = tempfile.mkstemp() |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 919 | os.write(f, "#!/bin/sh\n") |
| 920 | os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 921 | sys.executable) |
| 922 | os.close(f) |
| 923 | os.chmod(fname, 0o700) |
| 924 | p = subprocess.Popen(fname) |
| 925 | p.wait() |
| 926 | os.remove(fname) |
| 927 | self.assertEqual(p.returncode, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 928 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 929 | def test_invalid_args(self): |
| 930 | # invalid arguments should raise ValueError |
| 931 | self.assertRaises(ValueError, subprocess.call, |
| 932 | [sys.executable, "-c", |
| 933 | "import sys; sys.exit(47)"], |
| 934 | startupinfo=47) |
| 935 | self.assertRaises(ValueError, subprocess.call, |
| 936 | [sys.executable, "-c", |
| 937 | "import sys; sys.exit(47)"], |
| 938 | creationflags=47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 939 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 940 | def test_shell_sequence(self): |
| 941 | # Run command through the shell (sequence) |
| 942 | newenv = os.environ.copy() |
| 943 | newenv["FRUIT"] = "apple" |
| 944 | p = subprocess.Popen(["echo $FRUIT"], shell=1, |
| 945 | stdout=subprocess.PIPE, |
| 946 | env=newenv) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 947 | self.addCleanup(p.stdout.close) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 948 | self.assertEqual(p.stdout.read().strip(), "apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 949 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 950 | def test_shell_string(self): |
| 951 | # Run command through the shell (string) |
| 952 | newenv = os.environ.copy() |
| 953 | newenv["FRUIT"] = "apple" |
| 954 | p = subprocess.Popen("echo $FRUIT", shell=1, |
| 955 | stdout=subprocess.PIPE, |
| 956 | env=newenv) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 957 | self.addCleanup(p.stdout.close) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 958 | self.assertEqual(p.stdout.read().strip(), "apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 959 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 960 | def test_call_string(self): |
| 961 | # call() function with string argument on UNIX |
Berker Peksag | b7c3515 | 2015-09-28 15:37:57 +0300 | [diff] [blame] | 962 | f, fname = tempfile.mkstemp() |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 963 | os.write(f, "#!/bin/sh\n") |
| 964 | os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 965 | sys.executable) |
| 966 | os.close(f) |
| 967 | os.chmod(fname, 0700) |
| 968 | rc = subprocess.call(fname) |
| 969 | os.remove(fname) |
| 970 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 971 | |
Stefan Krah | e9a6a7d | 2010-07-19 14:41:08 +0000 | [diff] [blame] | 972 | def test_specific_shell(self): |
| 973 | # Issue #9265: Incorrect name passed as arg[0]. |
| 974 | shells = [] |
| 975 | for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']: |
| 976 | for name in ['bash', 'ksh']: |
| 977 | sh = os.path.join(prefix, name) |
| 978 | if os.path.isfile(sh): |
| 979 | shells.append(sh) |
| 980 | if not shells: # Will probably work for any shell but csh. |
| 981 | self.skipTest("bash or ksh required for this test") |
| 982 | sh = '/bin/sh' |
| 983 | if os.path.isfile(sh) and not os.path.islink(sh): |
| 984 | # Test will fail if /bin/sh is a symlink to csh. |
| 985 | shells.append(sh) |
| 986 | for sh in shells: |
| 987 | p = subprocess.Popen("echo $0", executable=sh, shell=True, |
| 988 | stdout=subprocess.PIPE) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 989 | self.addCleanup(p.stdout.close) |
Stefan Krah | e9a6a7d | 2010-07-19 14:41:08 +0000 | [diff] [blame] | 990 | self.assertEqual(p.stdout.read().strip(), sh) |
| 991 | |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 992 | def _kill_process(self, method, *args): |
Florent Xicluna | cecef39 | 2010-03-05 19:31:21 +0000 | [diff] [blame] | 993 | # Do not inherit file handles from the parent. |
| 994 | # It should fix failures on some platforms. |
Antoine Pitrou | a6166da | 2010-09-20 11:20:44 +0000 | [diff] [blame] | 995 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 996 | import sys, time |
| 997 | sys.stdout.write('x\\n') |
| 998 | sys.stdout.flush() |
| 999 | time.sleep(30) |
| 1000 | """], |
| 1001 | close_fds=True, |
| 1002 | stdin=subprocess.PIPE, |
| 1003 | stdout=subprocess.PIPE, |
| 1004 | stderr=subprocess.PIPE) |
| 1005 | # Wait for the interpreter to be completely initialized before |
| 1006 | # sending any signal. |
| 1007 | p.stdout.read(1) |
| 1008 | getattr(p, method)(*args) |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1009 | return p |
| 1010 | |
Charles-François Natali | ef2bd67 | 2013-01-12 16:52:20 +0100 | [diff] [blame] | 1011 | @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')), |
| 1012 | "Due to known OS bug (issue #16762)") |
Antoine Pitrou | f60845b | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1013 | def _kill_dead_process(self, method, *args): |
| 1014 | # Do not inherit file handles from the parent. |
| 1015 | # It should fix failures on some platforms. |
| 1016 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1017 | import sys, time |
| 1018 | sys.stdout.write('x\\n') |
| 1019 | sys.stdout.flush() |
| 1020 | """], |
| 1021 | close_fds=True, |
| 1022 | stdin=subprocess.PIPE, |
| 1023 | stdout=subprocess.PIPE, |
| 1024 | stderr=subprocess.PIPE) |
| 1025 | # Wait for the interpreter to be completely initialized before |
| 1026 | # sending any signal. |
| 1027 | p.stdout.read(1) |
| 1028 | # The process should end after this |
| 1029 | time.sleep(1) |
| 1030 | # This shouldn't raise even though the child is now dead |
| 1031 | getattr(p, method)(*args) |
| 1032 | p.communicate() |
| 1033 | |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1034 | def test_send_signal(self): |
| 1035 | p = self._kill_process('send_signal', signal.SIGINT) |
Florent Xicluna | fc4d6d7 | 2010-03-23 14:36:45 +0000 | [diff] [blame] | 1036 | _, stderr = p.communicate() |
Florent Xicluna | 3c919cf | 2010-03-23 19:19:16 +0000 | [diff] [blame] | 1037 | self.assertIn('KeyboardInterrupt', stderr) |
Florent Xicluna | 446ff14 | 2010-03-23 15:05:30 +0000 | [diff] [blame] | 1038 | self.assertNotEqual(p.wait(), 0) |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 1039 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1040 | def test_kill(self): |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1041 | p = self._kill_process('kill') |
Florent Xicluna | 446ff14 | 2010-03-23 15:05:30 +0000 | [diff] [blame] | 1042 | _, stderr = p.communicate() |
| 1043 | self.assertStderrEqual(stderr, '') |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1044 | self.assertEqual(p.wait(), -signal.SIGKILL) |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 1045 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1046 | def test_terminate(self): |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1047 | p = self._kill_process('terminate') |
Florent Xicluna | 446ff14 | 2010-03-23 15:05:30 +0000 | [diff] [blame] | 1048 | _, stderr = p.communicate() |
| 1049 | self.assertStderrEqual(stderr, '') |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1050 | self.assertEqual(p.wait(), -signal.SIGTERM) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1051 | |
Antoine Pitrou | f60845b | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1052 | def test_send_signal_dead(self): |
| 1053 | # Sending a signal to a dead process |
| 1054 | self._kill_dead_process('send_signal', signal.SIGINT) |
| 1055 | |
| 1056 | def test_kill_dead(self): |
| 1057 | # Killing a dead process |
| 1058 | self._kill_dead_process('kill') |
| 1059 | |
| 1060 | def test_terminate_dead(self): |
| 1061 | # Terminating a dead process |
| 1062 | self._kill_dead_process('terminate') |
| 1063 | |
Antoine Pitrou | 91ce0d9 | 2011-01-03 18:45:09 +0000 | [diff] [blame] | 1064 | def check_close_std_fds(self, fds): |
| 1065 | # Issue #9905: test that subprocess pipes still work properly with |
| 1066 | # some standard fds closed |
| 1067 | stdin = 0 |
| 1068 | newfds = [] |
| 1069 | for a in fds: |
| 1070 | b = os.dup(a) |
| 1071 | newfds.append(b) |
| 1072 | if a == 0: |
| 1073 | stdin = b |
| 1074 | try: |
| 1075 | for fd in fds: |
| 1076 | os.close(fd) |
| 1077 | out, err = subprocess.Popen([sys.executable, "-c", |
| 1078 | 'import sys;' |
| 1079 | 'sys.stdout.write("apple");' |
| 1080 | 'sys.stdout.flush();' |
| 1081 | 'sys.stderr.write("orange")'], |
| 1082 | stdin=stdin, |
| 1083 | stdout=subprocess.PIPE, |
| 1084 | stderr=subprocess.PIPE).communicate() |
| 1085 | err = test_support.strip_python_stderr(err) |
| 1086 | self.assertEqual((out, err), (b'apple', b'orange')) |
| 1087 | finally: |
| 1088 | for b, a in zip(newfds, fds): |
| 1089 | os.dup2(b, a) |
| 1090 | for b in newfds: |
| 1091 | os.close(b) |
| 1092 | |
| 1093 | def test_close_fd_0(self): |
| 1094 | self.check_close_std_fds([0]) |
| 1095 | |
| 1096 | def test_close_fd_1(self): |
| 1097 | self.check_close_std_fds([1]) |
| 1098 | |
| 1099 | def test_close_fd_2(self): |
| 1100 | self.check_close_std_fds([2]) |
| 1101 | |
| 1102 | def test_close_fds_0_1(self): |
| 1103 | self.check_close_std_fds([0, 1]) |
| 1104 | |
| 1105 | def test_close_fds_0_2(self): |
| 1106 | self.check_close_std_fds([0, 2]) |
| 1107 | |
| 1108 | def test_close_fds_1_2(self): |
| 1109 | self.check_close_std_fds([1, 2]) |
| 1110 | |
| 1111 | def test_close_fds_0_1_2(self): |
| 1112 | # Issue #10806: test that subprocess pipes still work properly with |
| 1113 | # all standard fds closed. |
| 1114 | self.check_close_std_fds([0, 1, 2]) |
| 1115 | |
Ross Lagerwall | d8e3901 | 2011-07-27 18:54:53 +0200 | [diff] [blame] | 1116 | def check_swap_fds(self, stdin_no, stdout_no, stderr_no): |
| 1117 | # open up some temporary files |
Berker Peksag | b7c3515 | 2015-09-28 15:37:57 +0300 | [diff] [blame] | 1118 | temps = [tempfile.mkstemp() for i in range(3)] |
Ross Lagerwall | d8e3901 | 2011-07-27 18:54:53 +0200 | [diff] [blame] | 1119 | temp_fds = [fd for fd, fname in temps] |
| 1120 | try: |
| 1121 | # unlink the files -- we won't need to reopen them |
| 1122 | for fd, fname in temps: |
| 1123 | os.unlink(fname) |
| 1124 | |
| 1125 | # save a copy of the standard file descriptors |
| 1126 | saved_fds = [os.dup(fd) for fd in range(3)] |
| 1127 | try: |
| 1128 | # duplicate the temp files over the standard fd's 0, 1, 2 |
| 1129 | for fd, temp_fd in enumerate(temp_fds): |
| 1130 | os.dup2(temp_fd, fd) |
| 1131 | |
| 1132 | # write some data to what will become stdin, and rewind |
| 1133 | os.write(stdin_no, b"STDIN") |
| 1134 | os.lseek(stdin_no, 0, 0) |
| 1135 | |
| 1136 | # now use those files in the given order, so that subprocess |
| 1137 | # has to rearrange them in the child |
| 1138 | p = subprocess.Popen([sys.executable, "-c", |
| 1139 | 'import sys; got = sys.stdin.read();' |
| 1140 | 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'], |
| 1141 | stdin=stdin_no, |
| 1142 | stdout=stdout_no, |
| 1143 | stderr=stderr_no) |
| 1144 | p.wait() |
| 1145 | |
| 1146 | for fd in temp_fds: |
| 1147 | os.lseek(fd, 0, 0) |
| 1148 | |
| 1149 | out = os.read(stdout_no, 1024) |
| 1150 | err = test_support.strip_python_stderr(os.read(stderr_no, 1024)) |
| 1151 | finally: |
| 1152 | for std, saved in enumerate(saved_fds): |
| 1153 | os.dup2(saved, std) |
| 1154 | os.close(saved) |
| 1155 | |
| 1156 | self.assertEqual(out, b"got STDIN") |
| 1157 | self.assertEqual(err, b"err") |
| 1158 | |
| 1159 | finally: |
| 1160 | for fd in temp_fds: |
| 1161 | os.close(fd) |
| 1162 | |
| 1163 | # When duping fds, if there arises a situation where one of the fds is |
| 1164 | # either 0, 1 or 2, it is possible that it is overwritten (#12607). |
| 1165 | # This tests all combinations of this. |
| 1166 | def test_swap_fds(self): |
| 1167 | self.check_swap_fds(0, 1, 2) |
| 1168 | self.check_swap_fds(0, 2, 1) |
| 1169 | self.check_swap_fds(1, 0, 2) |
| 1170 | self.check_swap_fds(1, 2, 0) |
| 1171 | self.check_swap_fds(2, 0, 1) |
| 1172 | self.check_swap_fds(2, 1, 0) |
| 1173 | |
Gregory P. Smith | 312efbc | 2010-12-14 15:02:53 +0000 | [diff] [blame] | 1174 | def test_wait_when_sigchild_ignored(self): |
| 1175 | # NOTE: sigchild_ignore.py may not be an effective test on all OSes. |
| 1176 | sigchild_ignore = test_support.findfile("sigchild_ignore.py", |
| 1177 | subdir="subprocessdata") |
| 1178 | p = subprocess.Popen([sys.executable, sigchild_ignore], |
| 1179 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 1180 | stdout, stderr = p.communicate() |
| 1181 | self.assertEqual(0, p.returncode, "sigchild_ignore.py exited" |
| 1182 | " non-zero with this error:\n%s" % stderr) |
| 1183 | |
Charles-François Natali | 100df0f | 2011-08-18 17:56:02 +0200 | [diff] [blame] | 1184 | def test_zombie_fast_process_del(self): |
| 1185 | # Issue #12650: on Unix, if Popen.__del__() was called before the |
| 1186 | # process exited, it wouldn't be added to subprocess._active, and would |
| 1187 | # remain a zombie. |
| 1188 | # spawn a Popen, and delete its reference before it exits |
| 1189 | p = subprocess.Popen([sys.executable, "-c", |
| 1190 | 'import sys, time;' |
| 1191 | 'time.sleep(0.2)'], |
| 1192 | stdout=subprocess.PIPE, |
| 1193 | stderr=subprocess.PIPE) |
Nadeem Vawda | 8605936 | 2011-08-19 05:22:24 +0200 | [diff] [blame] | 1194 | self.addCleanup(p.stdout.close) |
| 1195 | self.addCleanup(p.stderr.close) |
Charles-François Natali | 100df0f | 2011-08-18 17:56:02 +0200 | [diff] [blame] | 1196 | ident = id(p) |
| 1197 | pid = p.pid |
| 1198 | del p |
| 1199 | # check that p is in the active processes list |
| 1200 | self.assertIn(ident, [id(o) for o in subprocess._active]) |
| 1201 | |
Charles-François Natali | 100df0f | 2011-08-18 17:56:02 +0200 | [diff] [blame] | 1202 | def test_leak_fast_process_del_killed(self): |
| 1203 | # Issue #12650: on Unix, if Popen.__del__() was called before the |
| 1204 | # process exited, and the process got killed by a signal, it would never |
| 1205 | # be removed from subprocess._active, which triggered a FD and memory |
| 1206 | # leak. |
| 1207 | # spawn a Popen, delete its reference and kill it |
| 1208 | p = subprocess.Popen([sys.executable, "-c", |
| 1209 | 'import time;' |
| 1210 | 'time.sleep(3)'], |
| 1211 | stdout=subprocess.PIPE, |
| 1212 | stderr=subprocess.PIPE) |
Nadeem Vawda | 8605936 | 2011-08-19 05:22:24 +0200 | [diff] [blame] | 1213 | self.addCleanup(p.stdout.close) |
| 1214 | self.addCleanup(p.stderr.close) |
Charles-François Natali | 100df0f | 2011-08-18 17:56:02 +0200 | [diff] [blame] | 1215 | ident = id(p) |
| 1216 | pid = p.pid |
| 1217 | del p |
| 1218 | os.kill(pid, signal.SIGKILL) |
| 1219 | # check that p is in the active processes list |
| 1220 | self.assertIn(ident, [id(o) for o in subprocess._active]) |
| 1221 | |
| 1222 | # let some time for the process to exit, and create a new Popen: this |
| 1223 | # should trigger the wait() of p |
| 1224 | time.sleep(0.2) |
| 1225 | with self.assertRaises(EnvironmentError) as c: |
| 1226 | with subprocess.Popen(['nonexisting_i_hope'], |
| 1227 | stdout=subprocess.PIPE, |
| 1228 | stderr=subprocess.PIPE) as proc: |
| 1229 | pass |
| 1230 | # p should have been wait()ed on, and removed from the _active list |
| 1231 | self.assertRaises(OSError, os.waitpid, pid, 0) |
| 1232 | self.assertNotIn(ident, [id(o) for o in subprocess._active]) |
| 1233 | |
Charles-François Natali | 2a34eb3 | 2011-08-25 21:20:54 +0200 | [diff] [blame] | 1234 | def test_pipe_cloexec(self): |
| 1235 | # Issue 12786: check that the communication pipes' FDs are set CLOEXEC, |
| 1236 | # and are not inherited by another child process. |
| 1237 | p1 = subprocess.Popen([sys.executable, "-c", |
| 1238 | 'import os;' |
| 1239 | 'os.read(0, 1)' |
| 1240 | ], |
| 1241 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1242 | stderr=subprocess.PIPE) |
| 1243 | |
| 1244 | p2 = subprocess.Popen([sys.executable, "-c", """if True: |
| 1245 | import os, errno, sys |
| 1246 | for fd in %r: |
| 1247 | try: |
| 1248 | os.close(fd) |
| 1249 | except OSError as e: |
| 1250 | if e.errno != errno.EBADF: |
| 1251 | raise |
| 1252 | else: |
| 1253 | sys.exit(1) |
| 1254 | sys.exit(0) |
| 1255 | """ % [f.fileno() for f in (p1.stdin, p1.stdout, |
| 1256 | p1.stderr)] |
| 1257 | ], |
| 1258 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1259 | stderr=subprocess.PIPE, close_fds=False) |
| 1260 | p1.communicate('foo') |
| 1261 | _, stderr = p2.communicate() |
| 1262 | |
| 1263 | self.assertEqual(p2.returncode, 0, "Unexpected error: " + repr(stderr)) |
| 1264 | |
Gregory P. Smith | f0739cb | 2017-01-22 22:38:28 -0800 | [diff] [blame] | 1265 | _libc_file_extensions = { |
| 1266 | 'Linux': 'so.6', |
| 1267 | 'Darwin': 'dylib', |
| 1268 | } |
| 1269 | @unittest.skipIf(not ctypes, 'ctypes module required.') |
| 1270 | @unittest.skipIf(platform.uname()[0] not in _libc_file_extensions, |
| 1271 | 'Test requires a libc this code can load with ctypes.') |
| 1272 | @unittest.skipIf(not sys.executable, 'Test requires sys.executable.') |
| 1273 | def test_child_terminated_in_stopped_state(self): |
| 1274 | """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335.""" |
| 1275 | PTRACE_TRACEME = 0 # From glibc and MacOS (PT_TRACE_ME). |
| 1276 | libc_name = 'libc.' + self._libc_file_extensions[platform.uname()[0]] |
| 1277 | libc = ctypes.CDLL(libc_name) |
| 1278 | if not hasattr(libc, 'ptrace'): |
| 1279 | raise unittest.SkipTest('ptrace() required.') |
| 1280 | test_ptrace = subprocess.Popen( |
| 1281 | [sys.executable, '-c', """if True: |
| 1282 | import ctypes |
| 1283 | libc = ctypes.CDLL({libc_name!r}) |
| 1284 | libc.ptrace({PTRACE_TRACEME}, 0, 0) |
| 1285 | """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME) |
| 1286 | ]) |
| 1287 | if test_ptrace.wait() != 0: |
| 1288 | raise unittest.SkipTest('ptrace() failed - unable to test.') |
| 1289 | child = subprocess.Popen( |
| 1290 | [sys.executable, '-c', """if True: |
| 1291 | import ctypes |
| 1292 | libc = ctypes.CDLL({libc_name!r}) |
| 1293 | libc.ptrace({PTRACE_TRACEME}, 0, 0) |
| 1294 | libc.printf(ctypes.c_char_p(0xdeadbeef)) # Crash the process. |
| 1295 | """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME) |
| 1296 | ]) |
| 1297 | try: |
| 1298 | returncode = child.wait() |
| 1299 | except Exception as e: |
| 1300 | child.kill() # Clean up the hung stopped process. |
| 1301 | raise e |
| 1302 | self.assertNotEqual(0, returncode) |
| 1303 | self.assertLess(returncode, 0) # signal death, likely SIGSEGV. |
| 1304 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1305 | |
Florent Xicluna | bab22a7 | 2010-03-04 19:40:48 +0000 | [diff] [blame] | 1306 | @unittest.skipUnless(mswindows, "Windows specific tests") |
Florent Xicluna | fc4d6d7 | 2010-03-23 14:36:45 +0000 | [diff] [blame] | 1307 | class Win32ProcessTestCase(BaseTestCase): |
Florent Xicluna | ab5e17f | 2010-03-04 21:31:58 +0000 | [diff] [blame] | 1308 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1309 | def test_startupinfo(self): |
| 1310 | # startupinfo argument |
| 1311 | # We uses hardcoded constants, because we do not want to |
| 1312 | # depend on win32all. |
| 1313 | STARTF_USESHOWWINDOW = 1 |
| 1314 | SW_MAXIMIZE = 3 |
| 1315 | startupinfo = subprocess.STARTUPINFO() |
| 1316 | startupinfo.dwFlags = STARTF_USESHOWWINDOW |
| 1317 | startupinfo.wShowWindow = SW_MAXIMIZE |
| 1318 | # Since Python is a console process, it won't be affected |
| 1319 | # by wShowWindow, but the argument should be silently |
| 1320 | # ignored |
| 1321 | subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1322 | startupinfo=startupinfo) |
| 1323 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1324 | def test_creationflags(self): |
| 1325 | # creationflags argument |
| 1326 | CREATE_NEW_CONSOLE = 16 |
| 1327 | sys.stderr.write(" a DOS box should flash briefly ...\n") |
| 1328 | subprocess.call(sys.executable + |
| 1329 | ' -c "import time; time.sleep(0.25)"', |
| 1330 | creationflags=CREATE_NEW_CONSOLE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1331 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1332 | def test_invalid_args(self): |
| 1333 | # invalid arguments should raise ValueError |
| 1334 | self.assertRaises(ValueError, subprocess.call, |
| 1335 | [sys.executable, "-c", |
| 1336 | "import sys; sys.exit(47)"], |
| 1337 | preexec_fn=lambda: 1) |
| 1338 | self.assertRaises(ValueError, subprocess.call, |
| 1339 | [sys.executable, "-c", |
| 1340 | "import sys; sys.exit(47)"], |
| 1341 | stdout=subprocess.PIPE, |
| 1342 | close_fds=True) |
| 1343 | |
| 1344 | def test_close_fds(self): |
| 1345 | # close file descriptors |
| 1346 | rc = subprocess.call([sys.executable, "-c", |
| 1347 | "import sys; sys.exit(47)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1348 | close_fds=True) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1349 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1350 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1351 | def test_shell_sequence(self): |
| 1352 | # Run command through the shell (sequence) |
| 1353 | newenv = os.environ.copy() |
| 1354 | newenv["FRUIT"] = "physalis" |
| 1355 | p = subprocess.Popen(["set"], shell=1, |
| 1356 | stdout=subprocess.PIPE, |
| 1357 | env=newenv) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 1358 | self.addCleanup(p.stdout.close) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1359 | self.assertIn("physalis", p.stdout.read()) |
Peter Astrand | 81a191b | 2007-05-26 22:18:20 +0000 | [diff] [blame] | 1360 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1361 | def test_shell_string(self): |
| 1362 | # Run command through the shell (string) |
| 1363 | newenv = os.environ.copy() |
| 1364 | newenv["FRUIT"] = "physalis" |
| 1365 | p = subprocess.Popen("set", shell=1, |
| 1366 | stdout=subprocess.PIPE, |
| 1367 | env=newenv) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 1368 | self.addCleanup(p.stdout.close) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1369 | self.assertIn("physalis", p.stdout.read()) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1370 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1371 | def test_call_string(self): |
| 1372 | # call() function with string argument on Windows |
| 1373 | rc = subprocess.call(sys.executable + |
| 1374 | ' -c "import sys; sys.exit(47)"') |
| 1375 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1376 | |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1377 | def _kill_process(self, method, *args): |
Florent Xicluna | 400efc2 | 2010-03-07 17:12:23 +0000 | [diff] [blame] | 1378 | # Some win32 buildbot raises EOFError if stdin is inherited |
Antoine Pitrou | dee0097 | 2010-09-24 19:00:29 +0000 | [diff] [blame] | 1379 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1380 | import sys, time |
| 1381 | sys.stdout.write('x\\n') |
| 1382 | sys.stdout.flush() |
| 1383 | time.sleep(30) |
| 1384 | """], |
| 1385 | stdin=subprocess.PIPE, |
| 1386 | stdout=subprocess.PIPE, |
| 1387 | stderr=subprocess.PIPE) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 1388 | self.addCleanup(p.stdout.close) |
| 1389 | self.addCleanup(p.stderr.close) |
| 1390 | self.addCleanup(p.stdin.close) |
Antoine Pitrou | dee0097 | 2010-09-24 19:00:29 +0000 | [diff] [blame] | 1391 | # Wait for the interpreter to be completely initialized before |
| 1392 | # sending any signal. |
| 1393 | p.stdout.read(1) |
| 1394 | getattr(p, method)(*args) |
Florent Xicluna | 446ff14 | 2010-03-23 15:05:30 +0000 | [diff] [blame] | 1395 | _, stderr = p.communicate() |
| 1396 | self.assertStderrEqual(stderr, '') |
Antoine Pitrou | dee0097 | 2010-09-24 19:00:29 +0000 | [diff] [blame] | 1397 | returncode = p.wait() |
Florent Xicluna | faf1753 | 2010-03-08 10:59:33 +0000 | [diff] [blame] | 1398 | self.assertNotEqual(returncode, 0) |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1399 | |
Antoine Pitrou | f60845b | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1400 | def _kill_dead_process(self, method, *args): |
| 1401 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1402 | import sys, time |
| 1403 | sys.stdout.write('x\\n') |
| 1404 | sys.stdout.flush() |
| 1405 | sys.exit(42) |
| 1406 | """], |
| 1407 | stdin=subprocess.PIPE, |
| 1408 | stdout=subprocess.PIPE, |
| 1409 | stderr=subprocess.PIPE) |
| 1410 | self.addCleanup(p.stdout.close) |
| 1411 | self.addCleanup(p.stderr.close) |
| 1412 | self.addCleanup(p.stdin.close) |
| 1413 | # Wait for the interpreter to be completely initialized before |
| 1414 | # sending any signal. |
| 1415 | p.stdout.read(1) |
| 1416 | # The process should end after this |
| 1417 | time.sleep(1) |
| 1418 | # This shouldn't raise even though the child is now dead |
| 1419 | getattr(p, method)(*args) |
| 1420 | _, stderr = p.communicate() |
| 1421 | self.assertStderrEqual(stderr, b'') |
| 1422 | rc = p.wait() |
| 1423 | self.assertEqual(rc, 42) |
| 1424 | |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1425 | def test_send_signal(self): |
| 1426 | self._kill_process('send_signal', signal.SIGTERM) |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 1427 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1428 | def test_kill(self): |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1429 | self._kill_process('kill') |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 1430 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1431 | def test_terminate(self): |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1432 | self._kill_process('terminate') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1433 | |
Antoine Pitrou | f60845b | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1434 | def test_send_signal_dead(self): |
| 1435 | self._kill_dead_process('send_signal', signal.SIGTERM) |
| 1436 | |
| 1437 | def test_kill_dead(self): |
| 1438 | self._kill_dead_process('kill') |
| 1439 | |
| 1440 | def test_terminate_dead(self): |
| 1441 | self._kill_dead_process('terminate') |
| 1442 | |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1443 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1444 | @unittest.skipUnless(getattr(subprocess, '_has_poll', False), |
| 1445 | "poll system call not supported") |
| 1446 | class ProcessTestCaseNoPoll(ProcessTestCase): |
| 1447 | def setUp(self): |
| 1448 | subprocess._has_poll = False |
| 1449 | ProcessTestCase.setUp(self) |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1450 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1451 | def tearDown(self): |
| 1452 | subprocess._has_poll = True |
| 1453 | ProcessTestCase.tearDown(self) |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1454 | |
| 1455 | |
Gregory P. Smith | cce211f | 2010-03-01 00:05:08 +0000 | [diff] [blame] | 1456 | class HelperFunctionTests(unittest.TestCase): |
Gregory P. Smith | c1baf4a | 2010-03-01 02:53:24 +0000 | [diff] [blame] | 1457 | @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows") |
Gregory P. Smith | cce211f | 2010-03-01 00:05:08 +0000 | [diff] [blame] | 1458 | def test_eintr_retry_call(self): |
| 1459 | record_calls = [] |
| 1460 | def fake_os_func(*args): |
| 1461 | record_calls.append(args) |
| 1462 | if len(record_calls) == 2: |
| 1463 | raise OSError(errno.EINTR, "fake interrupted system call") |
| 1464 | return tuple(reversed(args)) |
| 1465 | |
| 1466 | self.assertEqual((999, 256), |
| 1467 | subprocess._eintr_retry_call(fake_os_func, 256, 999)) |
| 1468 | self.assertEqual([(256, 999)], record_calls) |
| 1469 | # This time there will be an EINTR so it will loop once. |
| 1470 | self.assertEqual((666,), |
| 1471 | subprocess._eintr_retry_call(fake_os_func, 666)) |
| 1472 | self.assertEqual([(256, 999), (666,), (666,)], record_calls) |
| 1473 | |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 1474 | @unittest.skipUnless(mswindows, "mswindows only") |
| 1475 | class CommandsWithSpaces (BaseTestCase): |
| 1476 | |
| 1477 | def setUp(self): |
| 1478 | super(CommandsWithSpaces, self).setUp() |
Berker Peksag | b7c3515 | 2015-09-28 15:37:57 +0300 | [diff] [blame] | 1479 | f, fname = tempfile.mkstemp(".py", "te st") |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 1480 | self.fname = fname.lower () |
| 1481 | os.write(f, b"import sys;" |
| 1482 | b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))" |
| 1483 | ) |
| 1484 | os.close(f) |
| 1485 | |
| 1486 | def tearDown(self): |
| 1487 | os.remove(self.fname) |
| 1488 | super(CommandsWithSpaces, self).tearDown() |
| 1489 | |
| 1490 | def with_spaces(self, *args, **kwargs): |
| 1491 | kwargs['stdout'] = subprocess.PIPE |
| 1492 | p = subprocess.Popen(*args, **kwargs) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 1493 | self.addCleanup(p.stdout.close) |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 1494 | self.assertEqual( |
| 1495 | p.stdout.read ().decode("mbcs"), |
| 1496 | "2 [%r, 'ab cd']" % self.fname |
| 1497 | ) |
| 1498 | |
| 1499 | def test_shell_string_with_spaces(self): |
| 1500 | # call() function with string argument with spaces on Windows |
Brian Curtin | e8c4920 | 2010-08-13 21:01:52 +0000 | [diff] [blame] | 1501 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 1502 | "ab cd"), shell=1) |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 1503 | |
| 1504 | def test_shell_sequence_with_spaces(self): |
| 1505 | # call() function with sequence argument with spaces on Windows |
Brian Curtin | e8c4920 | 2010-08-13 21:01:52 +0000 | [diff] [blame] | 1506 | self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1) |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 1507 | |
| 1508 | def test_noshell_string_with_spaces(self): |
| 1509 | # call() function with string argument with spaces on Windows |
| 1510 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 1511 | "ab cd")) |
| 1512 | |
| 1513 | def test_noshell_sequence_with_spaces(self): |
| 1514 | # call() function with sequence argument with spaces on Windows |
| 1515 | self.with_spaces([sys.executable, self.fname, "ab cd"]) |
| 1516 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1517 | def test_main(): |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1518 | unit_tests = (ProcessTestCase, |
| 1519 | POSIXProcessTestCase, |
| 1520 | Win32ProcessTestCase, |
Gregory P. Smith | cce211f | 2010-03-01 00:05:08 +0000 | [diff] [blame] | 1521 | ProcessTestCaseNoPoll, |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 1522 | HelperFunctionTests, |
| 1523 | CommandsWithSpaces) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1524 | |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1525 | test_support.run_unittest(*unit_tests) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1526 | test_support.reap_children() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1527 | |
| 1528 | if __name__ == "__main__": |
| 1529 | test_main() |