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 | |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 388 | def test_communicate_stdin(self): |
| 389 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 390 | 'import sys;' |
| 391 | 'sys.exit(sys.stdin.read() == "pear")'], |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 392 | stdin=subprocess.PIPE) |
| 393 | p.communicate("pear") |
| 394 | self.assertEqual(p.returncode, 1) |
| 395 | |
| 396 | def test_communicate_stdout(self): |
| 397 | p = subprocess.Popen([sys.executable, "-c", |
| 398 | 'import sys; sys.stdout.write("pineapple")'], |
| 399 | stdout=subprocess.PIPE) |
| 400 | (stdout, stderr) = p.communicate() |
| 401 | self.assertEqual(stdout, "pineapple") |
| 402 | self.assertEqual(stderr, None) |
| 403 | |
| 404 | def test_communicate_stderr(self): |
| 405 | p = subprocess.Popen([sys.executable, "-c", |
| 406 | 'import sys; sys.stderr.write("pineapple")'], |
| 407 | stderr=subprocess.PIPE) |
| 408 | (stdout, stderr) = p.communicate() |
| 409 | self.assertEqual(stdout, None) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 410 | self.assertStderrEqual(stderr, "pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 411 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 412 | def test_communicate(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 413 | p = subprocess.Popen([sys.executable, "-c", |
Gregory P. Smith | 4036fd4 | 2008-05-26 20:22:14 +0000 | [diff] [blame] | 414 | 'import sys,os;' |
| 415 | 'sys.stderr.write("pineapple");' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 416 | 'sys.stdout.write(sys.stdin.read())'], |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 417 | stdin=subprocess.PIPE, |
| 418 | stdout=subprocess.PIPE, |
| 419 | stderr=subprocess.PIPE) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 420 | self.addCleanup(p.stdout.close) |
| 421 | self.addCleanup(p.stderr.close) |
| 422 | self.addCleanup(p.stdin.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 423 | (stdout, stderr) = p.communicate("banana") |
| 424 | self.assertEqual(stdout, "banana") |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 425 | self.assertStderrEqual(stderr, "pineapple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 426 | |
Gregory P. Smith | 4036fd4 | 2008-05-26 20:22:14 +0000 | [diff] [blame] | 427 | # This test is Linux specific for simplicity to at least have |
| 428 | # some coverage. It is not a platform specific bug. |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 429 | @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()), |
| 430 | "Linux specific") |
| 431 | # Test for the fd leak reported in http://bugs.python.org/issue2791. |
| 432 | def test_communicate_pipe_fd_leak(self): |
| 433 | fd_directory = '/proc/%d/fd' % os.getpid() |
| 434 | num_fds_before_popen = len(os.listdir(fd_directory)) |
Martin Panter | ad6a99c | 2016-09-10 10:38:22 +0000 | [diff] [blame] | 435 | p = subprocess.Popen([sys.executable, "-c", "print('')"], |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 436 | stdout=subprocess.PIPE) |
| 437 | p.communicate() |
| 438 | num_fds_after_communicate = len(os.listdir(fd_directory)) |
| 439 | del p |
| 440 | num_fds_after_destruction = len(os.listdir(fd_directory)) |
| 441 | self.assertEqual(num_fds_before_popen, num_fds_after_destruction) |
| 442 | self.assertEqual(num_fds_before_popen, num_fds_after_communicate) |
Gregory P. Smith | 4036fd4 | 2008-05-26 20:22:14 +0000 | [diff] [blame] | 443 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 444 | def test_communicate_returns(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 445 | # communicate() should return None if no redirection is active |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 446 | p = subprocess.Popen([sys.executable, "-c", |
| 447 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 448 | (stdout, stderr) = p.communicate() |
| 449 | self.assertEqual(stdout, None) |
| 450 | self.assertEqual(stderr, None) |
| 451 | |
| 452 | def test_communicate_pipe_buf(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 453 | # communicate() with writes larger than pipe_buf |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 454 | # This test will probably deadlock rather than fail, if |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 455 | # communicate() does not work properly. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 456 | x, y = os.pipe() |
| 457 | if mswindows: |
| 458 | pipe_buf = 512 |
| 459 | else: |
| 460 | pipe_buf = os.fpathconf(x, "PC_PIPE_BUF") |
| 461 | os.close(x) |
| 462 | os.close(y) |
| 463 | p = subprocess.Popen([sys.executable, "-c", |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 464 | 'import sys,os;' |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 465 | 'sys.stdout.write(sys.stdin.read(47));' |
| 466 | 'sys.stderr.write("xyz"*%d);' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 467 | 'sys.stdout.write(sys.stdin.read())' % pipe_buf], |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 468 | stdin=subprocess.PIPE, |
| 469 | stdout=subprocess.PIPE, |
| 470 | stderr=subprocess.PIPE) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 471 | self.addCleanup(p.stdout.close) |
| 472 | self.addCleanup(p.stderr.close) |
| 473 | self.addCleanup(p.stdin.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 474 | string_to_write = "abc"*pipe_buf |
| 475 | (stdout, stderr) = p.communicate(string_to_write) |
| 476 | self.assertEqual(stdout, string_to_write) |
| 477 | |
| 478 | def test_writes_before_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 479 | # stdin.write before communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 480 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 481 | 'import sys,os;' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 482 | 'sys.stdout.write(sys.stdin.read())'], |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 483 | stdin=subprocess.PIPE, |
| 484 | stdout=subprocess.PIPE, |
| 485 | stderr=subprocess.PIPE) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 486 | self.addCleanup(p.stdout.close) |
| 487 | self.addCleanup(p.stderr.close) |
| 488 | self.addCleanup(p.stdin.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 489 | p.stdin.write("banana") |
| 490 | (stdout, stderr) = p.communicate("split") |
| 491 | self.assertEqual(stdout, "bananasplit") |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 492 | self.assertStderrEqual(stderr, "") |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 493 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 494 | def test_universal_newlines(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 495 | p = subprocess.Popen([sys.executable, "-c", |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 496 | 'import sys,os;' + SETBINARY + |
| 497 | 'sys.stdout.write("line1\\n");' |
| 498 | 'sys.stdout.flush();' |
| 499 | 'sys.stdout.write("line2\\r");' |
| 500 | 'sys.stdout.flush();' |
| 501 | 'sys.stdout.write("line3\\r\\n");' |
| 502 | 'sys.stdout.flush();' |
| 503 | 'sys.stdout.write("line4\\r");' |
| 504 | 'sys.stdout.flush();' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 505 | 'sys.stdout.write("\\nline5");' |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 506 | 'sys.stdout.flush();' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 507 | 'sys.stdout.write("\\nline6");'], |
| 508 | stdout=subprocess.PIPE, |
| 509 | universal_newlines=1) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 510 | self.addCleanup(p.stdout.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 511 | stdout = p.stdout.read() |
Neal Norwitz | a6d01ce | 2006-05-02 06:23:22 +0000 | [diff] [blame] | 512 | if hasattr(file, 'newlines'): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 513 | # Interpreter with universal newline support |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 514 | self.assertEqual(stdout, |
| 515 | "line1\nline2\nline3\nline4\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 516 | else: |
| 517 | # Interpreter without universal newline support |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 518 | self.assertEqual(stdout, |
| 519 | "line1\nline2\rline3\r\nline4\r\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 520 | |
| 521 | def test_universal_newlines_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 522 | # universal newlines through communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 523 | p = subprocess.Popen([sys.executable, "-c", |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 524 | 'import sys,os;' + SETBINARY + |
| 525 | 'sys.stdout.write("line1\\n");' |
| 526 | 'sys.stdout.flush();' |
| 527 | 'sys.stdout.write("line2\\r");' |
| 528 | 'sys.stdout.flush();' |
| 529 | 'sys.stdout.write("line3\\r\\n");' |
| 530 | 'sys.stdout.flush();' |
| 531 | 'sys.stdout.write("line4\\r");' |
| 532 | 'sys.stdout.flush();' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 533 | 'sys.stdout.write("\\nline5");' |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 534 | 'sys.stdout.flush();' |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 535 | 'sys.stdout.write("\\nline6");'], |
| 536 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 537 | universal_newlines=1) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 538 | self.addCleanup(p.stdout.close) |
| 539 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 540 | (stdout, stderr) = p.communicate() |
Neal Norwitz | a6d01ce | 2006-05-02 06:23:22 +0000 | [diff] [blame] | 541 | if hasattr(file, 'newlines'): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 542 | # Interpreter with universal newline support |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 543 | self.assertEqual(stdout, |
| 544 | "line1\nline2\nline3\nline4\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 545 | else: |
| 546 | # Interpreter without universal newline support |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 547 | self.assertEqual(stdout, |
| 548 | "line1\nline2\rline3\r\nline4\r\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 549 | |
| 550 | def test_no_leaking(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 551 | # Make sure we leak no resources |
Antoine Pitrou | b0b3bff | 2010-09-18 22:42:30 +0000 | [diff] [blame] | 552 | if not mswindows: |
Peter Astrand | f7f1bb7 | 2005-03-03 20:47:37 +0000 | [diff] [blame] | 553 | max_handles = 1026 # too much for most UNIX systems |
| 554 | else: |
Antoine Pitrou | b0b3bff | 2010-09-18 22:42:30 +0000 | [diff] [blame] | 555 | max_handles = 2050 # too much for (at least some) Windows setups |
| 556 | handles = [] |
| 557 | try: |
| 558 | for i in range(max_handles): |
| 559 | try: |
| 560 | handles.append(os.open(test_support.TESTFN, |
| 561 | os.O_WRONLY | os.O_CREAT)) |
| 562 | except OSError as e: |
| 563 | if e.errno != errno.EMFILE: |
| 564 | raise |
| 565 | break |
| 566 | else: |
| 567 | self.skipTest("failed to reach the file descriptor limit " |
| 568 | "(tried %d)" % max_handles) |
| 569 | # Close a couple of them (should be enough for a subprocess) |
| 570 | for i in range(10): |
| 571 | os.close(handles.pop()) |
| 572 | # Loop creating some subprocesses. If one of them leaks some fds, |
| 573 | # the next loop iteration will fail by reaching the max fd limit. |
| 574 | for i in range(15): |
| 575 | p = subprocess.Popen([sys.executable, "-c", |
| 576 | "import sys;" |
| 577 | "sys.stdout.write(sys.stdin.read())"], |
| 578 | stdin=subprocess.PIPE, |
| 579 | stdout=subprocess.PIPE, |
| 580 | stderr=subprocess.PIPE) |
| 581 | data = p.communicate(b"lime")[0] |
| 582 | self.assertEqual(data, b"lime") |
| 583 | finally: |
| 584 | for h in handles: |
| 585 | os.close(h) |
Mark Dickinson | 313dc9b | 2012-10-07 15:41:38 +0100 | [diff] [blame] | 586 | test_support.unlink(test_support.TESTFN) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 587 | |
| 588 | def test_list2cmdline(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 589 | self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']), |
| 590 | '"a b c" d e') |
| 591 | self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']), |
| 592 | 'ab\\"c \\ d') |
Gregory P. Smith | e047e6d | 2008-01-19 20:49:02 +0000 | [diff] [blame] | 593 | self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']), |
| 594 | 'ab\\"c " \\\\" d') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 595 | self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']), |
| 596 | 'a\\\\\\b "de fg" h') |
| 597 | self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']), |
| 598 | 'a\\\\\\"b c d') |
| 599 | self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']), |
| 600 | '"a\\\\b c" d e') |
| 601 | self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']), |
| 602 | '"a\\\\b\\ c" d e') |
Peter Astrand | 10514a7 | 2007-01-13 22:35:35 +0000 | [diff] [blame] | 603 | self.assertEqual(subprocess.list2cmdline(['ab', '']), |
| 604 | 'ab ""') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 605 | |
| 606 | |
| 607 | def test_poll(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 608 | p = subprocess.Popen([sys.executable, |
Tim Peters | 29b6b4f | 2004-10-13 03:43:40 +0000 | [diff] [blame] | 609 | "-c", "import time; time.sleep(1)"]) |
| 610 | count = 0 |
| 611 | while p.poll() is None: |
| 612 | time.sleep(0.1) |
| 613 | count += 1 |
| 614 | # We expect that the poll loop probably went around about 10 times, |
| 615 | # but, based on system scheduling we can't control, it's possible |
| 616 | # poll() never returned None. It "should be" very rare that it |
| 617 | # didn't go around at least twice. |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 618 | self.assertGreaterEqual(count, 2) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 619 | # Subsequent invocations should just return the returncode |
| 620 | self.assertEqual(p.poll(), 0) |
| 621 | |
| 622 | |
| 623 | def test_wait(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 624 | p = subprocess.Popen([sys.executable, |
| 625 | "-c", "import time; time.sleep(2)"]) |
| 626 | self.assertEqual(p.wait(), 0) |
| 627 | # Subsequent invocations should just return the returncode |
| 628 | self.assertEqual(p.wait(), 0) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 629 | |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 630 | |
| 631 | def test_invalid_bufsize(self): |
| 632 | # an invalid type of the bufsize argument should raise |
| 633 | # TypeError. |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 634 | with self.assertRaises(TypeError): |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 635 | subprocess.Popen([sys.executable, "-c", "pass"], "orange") |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 636 | |
Georg Brandl | f3715d2 | 2009-02-14 17:01:36 +0000 | [diff] [blame] | 637 | def test_leaking_fds_on_error(self): |
| 638 | # see bug #5179: Popen leaks file descriptors to PIPEs if |
| 639 | # the child fails to execute; this will eventually exhaust |
| 640 | # the maximum number of open fds. 1024 seems a very common |
| 641 | # value for that limit, but Windows has 2048, so we loop |
| 642 | # 1024 times (each call leaked two fds). |
| 643 | for i in range(1024): |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 644 | # Windows raises IOError. Others raise OSError. |
| 645 | with self.assertRaises(EnvironmentError) as c: |
Georg Brandl | f3715d2 | 2009-02-14 17:01:36 +0000 | [diff] [blame] | 646 | subprocess.Popen(['nonexisting_i_hope'], |
| 647 | stdout=subprocess.PIPE, |
| 648 | stderr=subprocess.PIPE) |
R David Murray | cdd5fc9 | 2011-03-13 22:37:18 -0400 | [diff] [blame] | 649 | # ignore errors that indicate the command was not found |
| 650 | if c.exception.errno not in (errno.ENOENT, errno.EACCES): |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 651 | raise c.exception |
Georg Brandl | f3715d2 | 2009-02-14 17:01:36 +0000 | [diff] [blame] | 652 | |
Antoine Pitrou | 33fc744 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 653 | @unittest.skipIf(threading is None, "threading required") |
| 654 | def test_double_close_on_error(self): |
| 655 | # Issue #18851 |
| 656 | fds = [] |
| 657 | def open_fds(): |
| 658 | for i in range(20): |
| 659 | fds.extend(os.pipe()) |
| 660 | time.sleep(0.001) |
| 661 | t = threading.Thread(target=open_fds) |
| 662 | t.start() |
| 663 | try: |
| 664 | with self.assertRaises(EnvironmentError): |
| 665 | subprocess.Popen(['nonexisting_i_hope'], |
| 666 | stdin=subprocess.PIPE, |
| 667 | stdout=subprocess.PIPE, |
| 668 | stderr=subprocess.PIPE) |
| 669 | finally: |
| 670 | t.join() |
| 671 | exc = None |
| 672 | for fd in fds: |
| 673 | # If a double close occurred, some of those fds will |
| 674 | # already have been closed by mistake, and os.close() |
| 675 | # here will raise. |
| 676 | try: |
| 677 | os.close(fd) |
| 678 | except OSError as e: |
| 679 | exc = e |
| 680 | if exc is not None: |
| 681 | raise exc |
| 682 | |
Tim Golden | 90374f5 | 2010-08-06 13:14:33 +0000 | [diff] [blame] | 683 | def test_handles_closed_on_exception(self): |
| 684 | # If CreateProcess exits with an error, ensure the |
| 685 | # duplicate output handles are released |
Berker Peksag | b7c3515 | 2015-09-28 15:37:57 +0300 | [diff] [blame] | 686 | ifhandle, ifname = tempfile.mkstemp() |
| 687 | ofhandle, ofname = tempfile.mkstemp() |
| 688 | efhandle, efname = tempfile.mkstemp() |
Tim Golden | 90374f5 | 2010-08-06 13:14:33 +0000 | [diff] [blame] | 689 | try: |
| 690 | subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle, |
| 691 | stderr=efhandle) |
| 692 | except OSError: |
| 693 | os.close(ifhandle) |
| 694 | os.remove(ifname) |
| 695 | os.close(ofhandle) |
| 696 | os.remove(ofname) |
| 697 | os.close(efhandle) |
| 698 | os.remove(efname) |
| 699 | self.assertFalse(os.path.exists(ifname)) |
| 700 | self.assertFalse(os.path.exists(ofname)) |
| 701 | self.assertFalse(os.path.exists(efname)) |
| 702 | |
Ross Lagerwall | 104c3f1 | 2011-04-05 15:24:34 +0200 | [diff] [blame] | 703 | def test_communicate_epipe(self): |
| 704 | # Issue 10963: communicate() should hide EPIPE |
| 705 | p = subprocess.Popen([sys.executable, "-c", 'pass'], |
| 706 | stdin=subprocess.PIPE, |
| 707 | stdout=subprocess.PIPE, |
| 708 | stderr=subprocess.PIPE) |
| 709 | self.addCleanup(p.stdout.close) |
| 710 | self.addCleanup(p.stderr.close) |
| 711 | self.addCleanup(p.stdin.close) |
| 712 | p.communicate("x" * 2**20) |
| 713 | |
| 714 | def test_communicate_epipe_only_stdin(self): |
| 715 | # Issue 10963: communicate() should hide EPIPE |
| 716 | p = subprocess.Popen([sys.executable, "-c", 'pass'], |
| 717 | stdin=subprocess.PIPE) |
| 718 | self.addCleanup(p.stdin.close) |
| 719 | time.sleep(2) |
| 720 | p.communicate("x" * 2**20) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 721 | |
Gregory P. Smith | 9d3b6e9 | 2012-11-10 22:49:03 -0800 | [diff] [blame] | 722 | # This test is Linux-ish specific for simplicity to at least have |
| 723 | # some coverage. It is not a platform specific bug. |
| 724 | @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()), |
| 725 | "Linux specific") |
| 726 | def test_failed_child_execute_fd_leak(self): |
| 727 | """Test for the fork() failure fd leak reported in issue16327.""" |
| 728 | fd_directory = '/proc/%d/fd' % os.getpid() |
| 729 | fds_before_popen = os.listdir(fd_directory) |
| 730 | with self.assertRaises(PopenTestException): |
| 731 | PopenExecuteChildRaises( |
| 732 | [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE, |
| 733 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 734 | |
| 735 | # NOTE: This test doesn't verify that the real _execute_child |
| 736 | # does not close the file descriptors itself on the way out |
| 737 | # during an exception. Code inspection has confirmed that. |
| 738 | |
| 739 | fds_after_exception = os.listdir(fd_directory) |
| 740 | self.assertEqual(fds_before_popen, fds_after_exception) |
| 741 | |
| 742 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 743 | # context manager |
| 744 | class _SuppressCoreFiles(object): |
| 745 | """Try to prevent core files from being created.""" |
| 746 | old_limit = None |
| 747 | |
| 748 | def __enter__(self): |
| 749 | """Try to save previous ulimit, then set it to (0, 0).""" |
Benjamin Peterson | 8b59c23 | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 750 | if resource is not None: |
| 751 | try: |
| 752 | self.old_limit = resource.getrlimit(resource.RLIMIT_CORE) |
| 753 | resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) |
| 754 | except (ValueError, resource.error): |
| 755 | pass |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 756 | |
Ronald Oussoren | 21b44e0 | 2010-07-23 12:26:30 +0000 | [diff] [blame] | 757 | if sys.platform == 'darwin': |
| 758 | # Check if the 'Crash Reporter' on OSX was configured |
| 759 | # in 'Developer' mode and warn that it will get triggered |
| 760 | # when it is. |
| 761 | # |
| 762 | # This assumes that this context manager is used in tests |
| 763 | # that might trigger the next manager. |
| 764 | value = subprocess.Popen(['/usr/bin/defaults', 'read', |
| 765 | 'com.apple.CrashReporter', 'DialogType'], |
| 766 | stdout=subprocess.PIPE).communicate()[0] |
| 767 | if value.strip() == b'developer': |
| 768 | print "this tests triggers the Crash Reporter, that is intentional" |
| 769 | sys.stdout.flush() |
| 770 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 771 | def __exit__(self, *args): |
| 772 | """Return core file behavior to default.""" |
| 773 | if self.old_limit is None: |
| 774 | return |
Benjamin Peterson | 8b59c23 | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 775 | if resource is not None: |
| 776 | try: |
| 777 | resource.setrlimit(resource.RLIMIT_CORE, self.old_limit) |
| 778 | except (ValueError, resource.error): |
| 779 | pass |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 780 | |
Victor Stinner | b78fed9 | 2011-07-05 14:50:35 +0200 | [diff] [blame] | 781 | @unittest.skipUnless(hasattr(signal, 'SIGALRM'), |
| 782 | "Requires signal.SIGALRM") |
Victor Stinner | e790131 | 2011-07-05 14:08:01 +0200 | [diff] [blame] | 783 | def test_communicate_eintr(self): |
| 784 | # Issue #12493: communicate() should handle EINTR |
| 785 | def handler(signum, frame): |
| 786 | pass |
| 787 | old_handler = signal.signal(signal.SIGALRM, handler) |
| 788 | self.addCleanup(signal.signal, signal.SIGALRM, old_handler) |
| 789 | |
| 790 | # the process is running for 2 seconds |
| 791 | args = [sys.executable, "-c", 'import time; time.sleep(2)'] |
| 792 | for stream in ('stdout', 'stderr'): |
| 793 | kw = {stream: subprocess.PIPE} |
| 794 | with subprocess.Popen(args, **kw) as process: |
| 795 | signal.alarm(1) |
| 796 | # communicate() will be interrupted by SIGALRM |
| 797 | process.communicate() |
| 798 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 799 | |
Florent Xicluna | bab22a7 | 2010-03-04 19:40:48 +0000 | [diff] [blame] | 800 | @unittest.skipIf(mswindows, "POSIX specific tests") |
Florent Xicluna | fc4d6d7 | 2010-03-23 14:36:45 +0000 | [diff] [blame] | 801 | class POSIXProcessTestCase(BaseTestCase): |
Florent Xicluna | ab5e17f | 2010-03-04 21:31:58 +0000 | [diff] [blame] | 802 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 803 | def test_exceptions(self): |
| 804 | # caught & re-raised exceptions |
| 805 | with self.assertRaises(OSError) as c: |
| 806 | p = subprocess.Popen([sys.executable, "-c", ""], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 807 | cwd="/this/path/does/not/exist") |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 808 | # The attribute child_traceback should contain "os.chdir" somewhere. |
| 809 | self.assertIn("os.chdir", c.exception.child_traceback) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 810 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 811 | def test_run_abort(self): |
| 812 | # returncode handles signal termination |
| 813 | with _SuppressCoreFiles(): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 814 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 815 | "import os; os.abort()"]) |
| 816 | p.wait() |
| 817 | self.assertEqual(-p.returncode, signal.SIGABRT) |
| 818 | |
| 819 | def test_preexec(self): |
| 820 | # preexec function |
| 821 | p = subprocess.Popen([sys.executable, "-c", |
| 822 | "import sys, os;" |
| 823 | "sys.stdout.write(os.getenv('FRUIT'))"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 824 | stdout=subprocess.PIPE, |
| 825 | preexec_fn=lambda: os.putenv("FRUIT", "apple")) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 826 | self.addCleanup(p.stdout.close) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 827 | self.assertEqual(p.stdout.read(), "apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 828 | |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 829 | class _TestExecuteChildPopen(subprocess.Popen): |
| 830 | """Used to test behavior at the end of _execute_child.""" |
| 831 | def __init__(self, testcase, *args, **kwargs): |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 832 | self._testcase = testcase |
| 833 | subprocess.Popen.__init__(self, *args, **kwargs) |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 834 | |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 835 | def _execute_child( |
| 836 | self, args, executable, preexec_fn, close_fds, cwd, env, |
Antoine Pitrou | 33fc744 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 837 | universal_newlines, startupinfo, creationflags, shell, to_close, |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 838 | p2cread, p2cwrite, |
| 839 | c2pread, c2pwrite, |
| 840 | errread, errwrite): |
| 841 | try: |
| 842 | subprocess.Popen._execute_child( |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 843 | self, args, executable, preexec_fn, close_fds, |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 844 | cwd, env, universal_newlines, |
Antoine Pitrou | 33fc744 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 845 | startupinfo, creationflags, shell, to_close, |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 846 | p2cread, p2cwrite, |
| 847 | c2pread, c2pwrite, |
| 848 | errread, errwrite) |
| 849 | finally: |
| 850 | # Open a bunch of file descriptors and verify that |
| 851 | # none of them are the same as the ones the Popen |
| 852 | # instance is using for stdin/stdout/stderr. |
| 853 | devzero_fds = [os.open("/dev/zero", os.O_RDONLY) |
| 854 | for _ in range(8)] |
| 855 | try: |
| 856 | for fd in devzero_fds: |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 857 | self._testcase.assertNotIn( |
| 858 | fd, (p2cwrite, c2pread, errread)) |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 859 | finally: |
Richard Oudkerk | 045e457 | 2013-06-10 16:27:45 +0100 | [diff] [blame] | 860 | for fd in devzero_fds: |
| 861 | os.close(fd) |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 862 | |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 863 | @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.") |
| 864 | def test_preexec_errpipe_does_not_double_close_pipes(self): |
| 865 | """Issue16140: Don't double close pipes on preexec error.""" |
| 866 | |
| 867 | def raise_it(): |
| 868 | raise RuntimeError("force the _execute_child() errpipe_data path.") |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 869 | |
| 870 | with self.assertRaises(RuntimeError): |
Gregory P. Smith | f047ba8 | 2012-11-11 09:49:02 -0800 | [diff] [blame] | 871 | self._TestExecuteChildPopen( |
| 872 | self, [sys.executable, "-c", "pass"], |
| 873 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 874 | stderr=subprocess.PIPE, preexec_fn=raise_it) |
Gregory P. Smith | 211248b | 2012-11-11 02:00:49 -0800 | [diff] [blame] | 875 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 876 | def test_args_string(self): |
| 877 | # args is a string |
Berker Peksag | b7c3515 | 2015-09-28 15:37:57 +0300 | [diff] [blame] | 878 | f, fname = tempfile.mkstemp() |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 879 | os.write(f, "#!/bin/sh\n") |
| 880 | os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 881 | sys.executable) |
| 882 | os.close(f) |
| 883 | os.chmod(fname, 0o700) |
| 884 | p = subprocess.Popen(fname) |
| 885 | p.wait() |
| 886 | os.remove(fname) |
| 887 | self.assertEqual(p.returncode, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 888 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 889 | def test_invalid_args(self): |
| 890 | # invalid arguments should raise ValueError |
| 891 | self.assertRaises(ValueError, subprocess.call, |
| 892 | [sys.executable, "-c", |
| 893 | "import sys; sys.exit(47)"], |
| 894 | startupinfo=47) |
| 895 | self.assertRaises(ValueError, subprocess.call, |
| 896 | [sys.executable, "-c", |
| 897 | "import sys; sys.exit(47)"], |
| 898 | creationflags=47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 899 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 900 | def test_shell_sequence(self): |
| 901 | # Run command through the shell (sequence) |
| 902 | newenv = os.environ.copy() |
| 903 | newenv["FRUIT"] = "apple" |
| 904 | p = subprocess.Popen(["echo $FRUIT"], shell=1, |
| 905 | stdout=subprocess.PIPE, |
| 906 | env=newenv) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 907 | self.addCleanup(p.stdout.close) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 908 | self.assertEqual(p.stdout.read().strip(), "apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 909 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 910 | def test_shell_string(self): |
| 911 | # Run command through the shell (string) |
| 912 | newenv = os.environ.copy() |
| 913 | newenv["FRUIT"] = "apple" |
| 914 | p = subprocess.Popen("echo $FRUIT", shell=1, |
| 915 | stdout=subprocess.PIPE, |
| 916 | env=newenv) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 917 | self.addCleanup(p.stdout.close) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 918 | self.assertEqual(p.stdout.read().strip(), "apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 919 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 920 | def test_call_string(self): |
| 921 | # call() function with string argument on UNIX |
Berker Peksag | b7c3515 | 2015-09-28 15:37:57 +0300 | [diff] [blame] | 922 | f, fname = tempfile.mkstemp() |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 923 | os.write(f, "#!/bin/sh\n") |
| 924 | os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 925 | sys.executable) |
| 926 | os.close(f) |
| 927 | os.chmod(fname, 0700) |
| 928 | rc = subprocess.call(fname) |
| 929 | os.remove(fname) |
| 930 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 931 | |
Stefan Krah | e9a6a7d | 2010-07-19 14:41:08 +0000 | [diff] [blame] | 932 | def test_specific_shell(self): |
| 933 | # Issue #9265: Incorrect name passed as arg[0]. |
| 934 | shells = [] |
| 935 | for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']: |
| 936 | for name in ['bash', 'ksh']: |
| 937 | sh = os.path.join(prefix, name) |
| 938 | if os.path.isfile(sh): |
| 939 | shells.append(sh) |
| 940 | if not shells: # Will probably work for any shell but csh. |
| 941 | self.skipTest("bash or ksh required for this test") |
| 942 | sh = '/bin/sh' |
| 943 | if os.path.isfile(sh) and not os.path.islink(sh): |
| 944 | # Test will fail if /bin/sh is a symlink to csh. |
| 945 | shells.append(sh) |
| 946 | for sh in shells: |
| 947 | p = subprocess.Popen("echo $0", executable=sh, shell=True, |
| 948 | stdout=subprocess.PIPE) |
Brian Curtin | d117b56 | 2010-11-05 04:09:09 +0000 | [diff] [blame] | 949 | self.addCleanup(p.stdout.close) |
Stefan Krah | e9a6a7d | 2010-07-19 14:41:08 +0000 | [diff] [blame] | 950 | self.assertEqual(p.stdout.read().strip(), sh) |
| 951 | |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 952 | def _kill_process(self, method, *args): |
Florent Xicluna | cecef39 | 2010-03-05 19:31:21 +0000 | [diff] [blame] | 953 | # Do not inherit file handles from the parent. |
| 954 | # It should fix failures on some platforms. |
Antoine Pitrou | a6166da | 2010-09-20 11:20:44 +0000 | [diff] [blame] | 955 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 956 | import sys, time |
| 957 | sys.stdout.write('x\\n') |
| 958 | sys.stdout.flush() |
| 959 | time.sleep(30) |
| 960 | """], |
| 961 | close_fds=True, |
| 962 | stdin=subprocess.PIPE, |
| 963 | stdout=subprocess.PIPE, |
| 964 | stderr=subprocess.PIPE) |
| 965 | # Wait for the interpreter to be completely initialized before |
| 966 | # sending any signal. |
| 967 | p.stdout.read(1) |
| 968 | getattr(p, method)(*args) |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 969 | return p |
| 970 | |
Charles-François Natali | ef2bd67 | 2013-01-12 16:52:20 +0100 | [diff] [blame] | 971 | @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')), |
| 972 | "Due to known OS bug (issue #16762)") |
Antoine Pitrou | f60845b | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 973 | def _kill_dead_process(self, method, *args): |
| 974 | # Do not inherit file handles from the parent. |
| 975 | # It should fix failures on some platforms. |
| 976 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 977 | import sys, time |
| 978 | sys.stdout.write('x\\n') |
| 979 | sys.stdout.flush() |
| 980 | """], |
| 981 | close_fds=True, |
| 982 | stdin=subprocess.PIPE, |
| 983 | stdout=subprocess.PIPE, |
| 984 | stderr=subprocess.PIPE) |
| 985 | # Wait for the interpreter to be completely initialized before |
| 986 | # sending any signal. |
| 987 | p.stdout.read(1) |
| 988 | # The process should end after this |
| 989 | time.sleep(1) |
| 990 | # This shouldn't raise even though the child is now dead |
| 991 | getattr(p, method)(*args) |
| 992 | p.communicate() |
| 993 | |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 994 | def test_send_signal(self): |
| 995 | p = self._kill_process('send_signal', signal.SIGINT) |
Florent Xicluna | fc4d6d7 | 2010-03-23 14:36:45 +0000 | [diff] [blame] | 996 | _, stderr = p.communicate() |
Florent Xicluna | 3c919cf | 2010-03-23 19:19:16 +0000 | [diff] [blame] | 997 | self.assertIn('KeyboardInterrupt', stderr) |
Florent Xicluna | 446ff14 | 2010-03-23 15:05:30 +0000 | [diff] [blame] | 998 | self.assertNotEqual(p.wait(), 0) |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 999 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1000 | def test_kill(self): |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1001 | p = self._kill_process('kill') |
Florent Xicluna | 446ff14 | 2010-03-23 15:05:30 +0000 | [diff] [blame] | 1002 | _, stderr = p.communicate() |
| 1003 | self.assertStderrEqual(stderr, '') |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1004 | self.assertEqual(p.wait(), -signal.SIGKILL) |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 1005 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1006 | def test_terminate(self): |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1007 | p = self._kill_process('terminate') |
Florent Xicluna | 446ff14 | 2010-03-23 15:05:30 +0000 | [diff] [blame] | 1008 | _, stderr = p.communicate() |
| 1009 | self.assertStderrEqual(stderr, '') |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1010 | self.assertEqual(p.wait(), -signal.SIGTERM) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1011 | |
Antoine Pitrou | f60845b | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1012 | def test_send_signal_dead(self): |
| 1013 | # Sending a signal to a dead process |
| 1014 | self._kill_dead_process('send_signal', signal.SIGINT) |
| 1015 | |
| 1016 | def test_kill_dead(self): |
| 1017 | # Killing a dead process |
| 1018 | self._kill_dead_process('kill') |
| 1019 | |
| 1020 | def test_terminate_dead(self): |
| 1021 | # Terminating a dead process |
| 1022 | self._kill_dead_process('terminate') |
| 1023 | |
Antoine Pitrou | 91ce0d9 | 2011-01-03 18:45:09 +0000 | [diff] [blame] | 1024 | def check_close_std_fds(self, fds): |
| 1025 | # Issue #9905: test that subprocess pipes still work properly with |
| 1026 | # some standard fds closed |
| 1027 | stdin = 0 |
| 1028 | newfds = [] |
| 1029 | for a in fds: |
| 1030 | b = os.dup(a) |
| 1031 | newfds.append(b) |
| 1032 | if a == 0: |
| 1033 | stdin = b |
| 1034 | try: |
| 1035 | for fd in fds: |
| 1036 | os.close(fd) |
| 1037 | out, err = subprocess.Popen([sys.executable, "-c", |
| 1038 | 'import sys;' |
| 1039 | 'sys.stdout.write("apple");' |
| 1040 | 'sys.stdout.flush();' |
| 1041 | 'sys.stderr.write("orange")'], |
| 1042 | stdin=stdin, |
| 1043 | stdout=subprocess.PIPE, |
| 1044 | stderr=subprocess.PIPE).communicate() |
| 1045 | err = test_support.strip_python_stderr(err) |
| 1046 | self.assertEqual((out, err), (b'apple', b'orange')) |
| 1047 | finally: |
| 1048 | for b, a in zip(newfds, fds): |
| 1049 | os.dup2(b, a) |
| 1050 | for b in newfds: |
| 1051 | os.close(b) |
| 1052 | |
| 1053 | def test_close_fd_0(self): |
| 1054 | self.check_close_std_fds([0]) |
| 1055 | |
| 1056 | def test_close_fd_1(self): |
| 1057 | self.check_close_std_fds([1]) |
| 1058 | |
| 1059 | def test_close_fd_2(self): |
| 1060 | self.check_close_std_fds([2]) |
| 1061 | |
| 1062 | def test_close_fds_0_1(self): |
| 1063 | self.check_close_std_fds([0, 1]) |
| 1064 | |
| 1065 | def test_close_fds_0_2(self): |
| 1066 | self.check_close_std_fds([0, 2]) |
| 1067 | |
| 1068 | def test_close_fds_1_2(self): |
| 1069 | self.check_close_std_fds([1, 2]) |
| 1070 | |
| 1071 | def test_close_fds_0_1_2(self): |
| 1072 | # Issue #10806: test that subprocess pipes still work properly with |
| 1073 | # all standard fds closed. |
| 1074 | self.check_close_std_fds([0, 1, 2]) |
| 1075 | |
Ross Lagerwall | d8e3901 | 2011-07-27 18:54:53 +0200 | [diff] [blame] | 1076 | def check_swap_fds(self, stdin_no, stdout_no, stderr_no): |
| 1077 | # open up some temporary files |
Berker Peksag | b7c3515 | 2015-09-28 15:37:57 +0300 | [diff] [blame] | 1078 | temps = [tempfile.mkstemp() for i in range(3)] |
Ross Lagerwall | d8e3901 | 2011-07-27 18:54:53 +0200 | [diff] [blame] | 1079 | temp_fds = [fd for fd, fname in temps] |
| 1080 | try: |
| 1081 | # unlink the files -- we won't need to reopen them |
| 1082 | for fd, fname in temps: |
| 1083 | os.unlink(fname) |
| 1084 | |
| 1085 | # save a copy of the standard file descriptors |
| 1086 | saved_fds = [os.dup(fd) for fd in range(3)] |
| 1087 | try: |
| 1088 | # duplicate the temp files over the standard fd's 0, 1, 2 |
| 1089 | for fd, temp_fd in enumerate(temp_fds): |
| 1090 | os.dup2(temp_fd, fd) |
| 1091 | |
| 1092 | # write some data to what will become stdin, and rewind |
| 1093 | os.write(stdin_no, b"STDIN") |
| 1094 | os.lseek(stdin_no, 0, 0) |
| 1095 | |
| 1096 | # now use those files in the given order, so that subprocess |
| 1097 | # has to rearrange them in the child |
| 1098 | p = subprocess.Popen([sys.executable, "-c", |
| 1099 | 'import sys; got = sys.stdin.read();' |
| 1100 | 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'], |
| 1101 | stdin=stdin_no, |
| 1102 | stdout=stdout_no, |
| 1103 | stderr=stderr_no) |
| 1104 | p.wait() |
| 1105 | |
| 1106 | for fd in temp_fds: |
| 1107 | os.lseek(fd, 0, 0) |
| 1108 | |
| 1109 | out = os.read(stdout_no, 1024) |
| 1110 | err = test_support.strip_python_stderr(os.read(stderr_no, 1024)) |
| 1111 | finally: |
| 1112 | for std, saved in enumerate(saved_fds): |
| 1113 | os.dup2(saved, std) |
| 1114 | os.close(saved) |
| 1115 | |
| 1116 | self.assertEqual(out, b"got STDIN") |
| 1117 | self.assertEqual(err, b"err") |
| 1118 | |
| 1119 | finally: |
| 1120 | for fd in temp_fds: |
| 1121 | os.close(fd) |
| 1122 | |
| 1123 | # When duping fds, if there arises a situation where one of the fds is |
| 1124 | # either 0, 1 or 2, it is possible that it is overwritten (#12607). |
| 1125 | # This tests all combinations of this. |
| 1126 | def test_swap_fds(self): |
| 1127 | self.check_swap_fds(0, 1, 2) |
| 1128 | self.check_swap_fds(0, 2, 1) |
| 1129 | self.check_swap_fds(1, 0, 2) |
| 1130 | self.check_swap_fds(1, 2, 0) |
| 1131 | self.check_swap_fds(2, 0, 1) |
| 1132 | self.check_swap_fds(2, 1, 0) |
| 1133 | |
Gregory P. Smith | 312efbc | 2010-12-14 15:02:53 +0000 | [diff] [blame] | 1134 | def test_wait_when_sigchild_ignored(self): |
| 1135 | # NOTE: sigchild_ignore.py may not be an effective test on all OSes. |
| 1136 | sigchild_ignore = test_support.findfile("sigchild_ignore.py", |
| 1137 | subdir="subprocessdata") |
| 1138 | p = subprocess.Popen([sys.executable, sigchild_ignore], |
| 1139 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 1140 | stdout, stderr = p.communicate() |
| 1141 | self.assertEqual(0, p.returncode, "sigchild_ignore.py exited" |
| 1142 | " non-zero with this error:\n%s" % stderr) |
| 1143 | |
Charles-François Natali | 100df0f | 2011-08-18 17:56:02 +0200 | [diff] [blame] | 1144 | def test_zombie_fast_process_del(self): |
| 1145 | # Issue #12650: on Unix, if Popen.__del__() was called before the |
| 1146 | # process exited, it wouldn't be added to subprocess._active, and would |
| 1147 | # remain a zombie. |
| 1148 | # spawn a Popen, and delete its reference before it exits |
| 1149 | p = subprocess.Popen([sys.executable, "-c", |
| 1150 | 'import sys, time;' |
| 1151 | 'time.sleep(0.2)'], |
| 1152 | stdout=subprocess.PIPE, |
| 1153 | stderr=subprocess.PIPE) |
Nadeem Vawda | 8605936 | 2011-08-19 05:22:24 +0200 | [diff] [blame] | 1154 | self.addCleanup(p.stdout.close) |
| 1155 | self.addCleanup(p.stderr.close) |
Charles-François Natali | 100df0f | 2011-08-18 17:56:02 +0200 | [diff] [blame] | 1156 | ident = id(p) |
| 1157 | pid = p.pid |
| 1158 | del p |
| 1159 | # check that p is in the active processes list |
| 1160 | self.assertIn(ident, [id(o) for o in subprocess._active]) |
| 1161 | |
Charles-François Natali | 100df0f | 2011-08-18 17:56:02 +0200 | [diff] [blame] | 1162 | def test_leak_fast_process_del_killed(self): |
| 1163 | # Issue #12650: on Unix, if Popen.__del__() was called before the |
| 1164 | # process exited, and the process got killed by a signal, it would never |
| 1165 | # be removed from subprocess._active, which triggered a FD and memory |
| 1166 | # leak. |
| 1167 | # spawn a Popen, delete its reference and kill it |
| 1168 | p = subprocess.Popen([sys.executable, "-c", |
| 1169 | 'import time;' |
| 1170 | 'time.sleep(3)'], |
| 1171 | stdout=subprocess.PIPE, |
| 1172 | stderr=subprocess.PIPE) |
Nadeem Vawda | 8605936 | 2011-08-19 05:22:24 +0200 | [diff] [blame] | 1173 | self.addCleanup(p.stdout.close) |
| 1174 | self.addCleanup(p.stderr.close) |
Charles-François Natali | 100df0f | 2011-08-18 17:56:02 +0200 | [diff] [blame] | 1175 | ident = id(p) |
| 1176 | pid = p.pid |
| 1177 | del p |
| 1178 | os.kill(pid, signal.SIGKILL) |
| 1179 | # check that p is in the active processes list |
| 1180 | self.assertIn(ident, [id(o) for o in subprocess._active]) |
| 1181 | |
| 1182 | # let some time for the process to exit, and create a new Popen: this |
| 1183 | # should trigger the wait() of p |
| 1184 | time.sleep(0.2) |
| 1185 | with self.assertRaises(EnvironmentError) as c: |
| 1186 | with subprocess.Popen(['nonexisting_i_hope'], |
| 1187 | stdout=subprocess.PIPE, |
| 1188 | stderr=subprocess.PIPE) as proc: |
| 1189 | pass |
| 1190 | # p should have been wait()ed on, and removed from the _active list |
| 1191 | self.assertRaises(OSError, os.waitpid, pid, 0) |
| 1192 | self.assertNotIn(ident, [id(o) for o in subprocess._active]) |
| 1193 | |
Charles-François Natali | 2a34eb3 | 2011-08-25 21:20:54 +0200 | [diff] [blame] | 1194 | def test_pipe_cloexec(self): |
| 1195 | # Issue 12786: check that the communication pipes' FDs are set CLOEXEC, |
| 1196 | # and are not inherited by another child process. |
| 1197 | p1 = subprocess.Popen([sys.executable, "-c", |
| 1198 | 'import os;' |
| 1199 | 'os.read(0, 1)' |
| 1200 | ], |
| 1201 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1202 | stderr=subprocess.PIPE) |
| 1203 | |
| 1204 | p2 = subprocess.Popen([sys.executable, "-c", """if True: |
| 1205 | import os, errno, sys |
| 1206 | for fd in %r: |
| 1207 | try: |
| 1208 | os.close(fd) |
| 1209 | except OSError as e: |
| 1210 | if e.errno != errno.EBADF: |
| 1211 | raise |
| 1212 | else: |
| 1213 | sys.exit(1) |
| 1214 | sys.exit(0) |
| 1215 | """ % [f.fileno() for f in (p1.stdin, p1.stdout, |
| 1216 | p1.stderr)] |
| 1217 | ], |
| 1218 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1219 | stderr=subprocess.PIPE, close_fds=False) |
| 1220 | p1.communicate('foo') |
| 1221 | _, stderr = p2.communicate() |
| 1222 | |
| 1223 | self.assertEqual(p2.returncode, 0, "Unexpected error: " + repr(stderr)) |
| 1224 | |
Gregory P. Smith | f0739cb | 2017-01-22 22:38:28 -0800 | [diff] [blame^] | 1225 | _libc_file_extensions = { |
| 1226 | 'Linux': 'so.6', |
| 1227 | 'Darwin': 'dylib', |
| 1228 | } |
| 1229 | @unittest.skipIf(not ctypes, 'ctypes module required.') |
| 1230 | @unittest.skipIf(platform.uname()[0] not in _libc_file_extensions, |
| 1231 | 'Test requires a libc this code can load with ctypes.') |
| 1232 | @unittest.skipIf(not sys.executable, 'Test requires sys.executable.') |
| 1233 | def test_child_terminated_in_stopped_state(self): |
| 1234 | """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335.""" |
| 1235 | PTRACE_TRACEME = 0 # From glibc and MacOS (PT_TRACE_ME). |
| 1236 | libc_name = 'libc.' + self._libc_file_extensions[platform.uname()[0]] |
| 1237 | libc = ctypes.CDLL(libc_name) |
| 1238 | if not hasattr(libc, 'ptrace'): |
| 1239 | raise unittest.SkipTest('ptrace() required.') |
| 1240 | test_ptrace = subprocess.Popen( |
| 1241 | [sys.executable, '-c', """if True: |
| 1242 | import ctypes |
| 1243 | libc = ctypes.CDLL({libc_name!r}) |
| 1244 | libc.ptrace({PTRACE_TRACEME}, 0, 0) |
| 1245 | """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME) |
| 1246 | ]) |
| 1247 | if test_ptrace.wait() != 0: |
| 1248 | raise unittest.SkipTest('ptrace() failed - unable to test.') |
| 1249 | child = subprocess.Popen( |
| 1250 | [sys.executable, '-c', """if True: |
| 1251 | import ctypes |
| 1252 | libc = ctypes.CDLL({libc_name!r}) |
| 1253 | libc.ptrace({PTRACE_TRACEME}, 0, 0) |
| 1254 | libc.printf(ctypes.c_char_p(0xdeadbeef)) # Crash the process. |
| 1255 | """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME) |
| 1256 | ]) |
| 1257 | try: |
| 1258 | returncode = child.wait() |
| 1259 | except Exception as e: |
| 1260 | child.kill() # Clean up the hung stopped process. |
| 1261 | raise e |
| 1262 | self.assertNotEqual(0, returncode) |
| 1263 | self.assertLess(returncode, 0) # signal death, likely SIGSEGV. |
| 1264 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1265 | |
Florent Xicluna | bab22a7 | 2010-03-04 19:40:48 +0000 | [diff] [blame] | 1266 | @unittest.skipUnless(mswindows, "Windows specific tests") |
Florent Xicluna | fc4d6d7 | 2010-03-23 14:36:45 +0000 | [diff] [blame] | 1267 | class Win32ProcessTestCase(BaseTestCase): |
Florent Xicluna | ab5e17f | 2010-03-04 21:31:58 +0000 | [diff] [blame] | 1268 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1269 | def test_startupinfo(self): |
| 1270 | # startupinfo argument |
| 1271 | # We uses hardcoded constants, because we do not want to |
| 1272 | # depend on win32all. |
| 1273 | STARTF_USESHOWWINDOW = 1 |
| 1274 | SW_MAXIMIZE = 3 |
| 1275 | startupinfo = subprocess.STARTUPINFO() |
| 1276 | startupinfo.dwFlags = STARTF_USESHOWWINDOW |
| 1277 | startupinfo.wShowWindow = SW_MAXIMIZE |
| 1278 | # Since Python is a console process, it won't be affected |
| 1279 | # by wShowWindow, but the argument should be silently |
| 1280 | # ignored |
| 1281 | subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1282 | startupinfo=startupinfo) |
| 1283 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1284 | def test_creationflags(self): |
| 1285 | # creationflags argument |
| 1286 | CREATE_NEW_CONSOLE = 16 |
| 1287 | sys.stderr.write(" a DOS box should flash briefly ...\n") |
| 1288 | subprocess.call(sys.executable + |
| 1289 | ' -c "import time; time.sleep(0.25)"', |
| 1290 | creationflags=CREATE_NEW_CONSOLE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1291 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1292 | def test_invalid_args(self): |
| 1293 | # invalid arguments should raise ValueError |
| 1294 | self.assertRaises(ValueError, subprocess.call, |
| 1295 | [sys.executable, "-c", |
| 1296 | "import sys; sys.exit(47)"], |
| 1297 | preexec_fn=lambda: 1) |
| 1298 | self.assertRaises(ValueError, subprocess.call, |
| 1299 | [sys.executable, "-c", |
| 1300 | "import sys; sys.exit(47)"], |
| 1301 | stdout=subprocess.PIPE, |
| 1302 | close_fds=True) |
| 1303 | |
| 1304 | def test_close_fds(self): |
| 1305 | # close file descriptors |
| 1306 | rc = subprocess.call([sys.executable, "-c", |
| 1307 | "import sys; sys.exit(47)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1308 | close_fds=True) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1309 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1310 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1311 | def test_shell_sequence(self): |
| 1312 | # Run command through the shell (sequence) |
| 1313 | newenv = os.environ.copy() |
| 1314 | newenv["FRUIT"] = "physalis" |
| 1315 | p = subprocess.Popen(["set"], shell=1, |
| 1316 | stdout=subprocess.PIPE, |
| 1317 | env=newenv) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 1318 | self.addCleanup(p.stdout.close) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1319 | self.assertIn("physalis", p.stdout.read()) |
Peter Astrand | 81a191b | 2007-05-26 22:18:20 +0000 | [diff] [blame] | 1320 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1321 | def test_shell_string(self): |
| 1322 | # Run command through the shell (string) |
| 1323 | newenv = os.environ.copy() |
| 1324 | newenv["FRUIT"] = "physalis" |
| 1325 | p = subprocess.Popen("set", shell=1, |
| 1326 | stdout=subprocess.PIPE, |
| 1327 | env=newenv) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 1328 | self.addCleanup(p.stdout.close) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1329 | self.assertIn("physalis", p.stdout.read()) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1330 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1331 | def test_call_string(self): |
| 1332 | # call() function with string argument on Windows |
| 1333 | rc = subprocess.call(sys.executable + |
| 1334 | ' -c "import sys; sys.exit(47)"') |
| 1335 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1336 | |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1337 | def _kill_process(self, method, *args): |
Florent Xicluna | 400efc2 | 2010-03-07 17:12:23 +0000 | [diff] [blame] | 1338 | # Some win32 buildbot raises EOFError if stdin is inherited |
Antoine Pitrou | dee0097 | 2010-09-24 19:00:29 +0000 | [diff] [blame] | 1339 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1340 | import sys, time |
| 1341 | sys.stdout.write('x\\n') |
| 1342 | sys.stdout.flush() |
| 1343 | time.sleep(30) |
| 1344 | """], |
| 1345 | stdin=subprocess.PIPE, |
| 1346 | stdout=subprocess.PIPE, |
| 1347 | stderr=subprocess.PIPE) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 1348 | self.addCleanup(p.stdout.close) |
| 1349 | self.addCleanup(p.stderr.close) |
| 1350 | self.addCleanup(p.stdin.close) |
Antoine Pitrou | dee0097 | 2010-09-24 19:00:29 +0000 | [diff] [blame] | 1351 | # Wait for the interpreter to be completely initialized before |
| 1352 | # sending any signal. |
| 1353 | p.stdout.read(1) |
| 1354 | getattr(p, method)(*args) |
Florent Xicluna | 446ff14 | 2010-03-23 15:05:30 +0000 | [diff] [blame] | 1355 | _, stderr = p.communicate() |
| 1356 | self.assertStderrEqual(stderr, '') |
Antoine Pitrou | dee0097 | 2010-09-24 19:00:29 +0000 | [diff] [blame] | 1357 | returncode = p.wait() |
Florent Xicluna | faf1753 | 2010-03-08 10:59:33 +0000 | [diff] [blame] | 1358 | self.assertNotEqual(returncode, 0) |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1359 | |
Antoine Pitrou | f60845b | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1360 | def _kill_dead_process(self, method, *args): |
| 1361 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1362 | import sys, time |
| 1363 | sys.stdout.write('x\\n') |
| 1364 | sys.stdout.flush() |
| 1365 | sys.exit(42) |
| 1366 | """], |
| 1367 | stdin=subprocess.PIPE, |
| 1368 | stdout=subprocess.PIPE, |
| 1369 | stderr=subprocess.PIPE) |
| 1370 | self.addCleanup(p.stdout.close) |
| 1371 | self.addCleanup(p.stderr.close) |
| 1372 | self.addCleanup(p.stdin.close) |
| 1373 | # Wait for the interpreter to be completely initialized before |
| 1374 | # sending any signal. |
| 1375 | p.stdout.read(1) |
| 1376 | # The process should end after this |
| 1377 | time.sleep(1) |
| 1378 | # This shouldn't raise even though the child is now dead |
| 1379 | getattr(p, method)(*args) |
| 1380 | _, stderr = p.communicate() |
| 1381 | self.assertStderrEqual(stderr, b'') |
| 1382 | rc = p.wait() |
| 1383 | self.assertEqual(rc, 42) |
| 1384 | |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1385 | def test_send_signal(self): |
| 1386 | self._kill_process('send_signal', signal.SIGTERM) |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 1387 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1388 | def test_kill(self): |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1389 | self._kill_process('kill') |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 1390 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1391 | def test_terminate(self): |
Florent Xicluna | c083864 | 2010-03-07 15:27:39 +0000 | [diff] [blame] | 1392 | self._kill_process('terminate') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1393 | |
Antoine Pitrou | f60845b | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1394 | def test_send_signal_dead(self): |
| 1395 | self._kill_dead_process('send_signal', signal.SIGTERM) |
| 1396 | |
| 1397 | def test_kill_dead(self): |
| 1398 | self._kill_dead_process('kill') |
| 1399 | |
| 1400 | def test_terminate_dead(self): |
| 1401 | self._kill_dead_process('terminate') |
| 1402 | |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1403 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1404 | @unittest.skipUnless(getattr(subprocess, '_has_poll', False), |
| 1405 | "poll system call not supported") |
| 1406 | class ProcessTestCaseNoPoll(ProcessTestCase): |
| 1407 | def setUp(self): |
| 1408 | subprocess._has_poll = False |
| 1409 | ProcessTestCase.setUp(self) |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1410 | |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1411 | def tearDown(self): |
| 1412 | subprocess._has_poll = True |
| 1413 | ProcessTestCase.tearDown(self) |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1414 | |
| 1415 | |
Gregory P. Smith | cce211f | 2010-03-01 00:05:08 +0000 | [diff] [blame] | 1416 | class HelperFunctionTests(unittest.TestCase): |
Gregory P. Smith | c1baf4a | 2010-03-01 02:53:24 +0000 | [diff] [blame] | 1417 | @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows") |
Gregory P. Smith | cce211f | 2010-03-01 00:05:08 +0000 | [diff] [blame] | 1418 | def test_eintr_retry_call(self): |
| 1419 | record_calls = [] |
| 1420 | def fake_os_func(*args): |
| 1421 | record_calls.append(args) |
| 1422 | if len(record_calls) == 2: |
| 1423 | raise OSError(errno.EINTR, "fake interrupted system call") |
| 1424 | return tuple(reversed(args)) |
| 1425 | |
| 1426 | self.assertEqual((999, 256), |
| 1427 | subprocess._eintr_retry_call(fake_os_func, 256, 999)) |
| 1428 | self.assertEqual([(256, 999)], record_calls) |
| 1429 | # This time there will be an EINTR so it will loop once. |
| 1430 | self.assertEqual((666,), |
| 1431 | subprocess._eintr_retry_call(fake_os_func, 666)) |
| 1432 | self.assertEqual([(256, 999), (666,), (666,)], record_calls) |
| 1433 | |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 1434 | @unittest.skipUnless(mswindows, "mswindows only") |
| 1435 | class CommandsWithSpaces (BaseTestCase): |
| 1436 | |
| 1437 | def setUp(self): |
| 1438 | super(CommandsWithSpaces, self).setUp() |
Berker Peksag | b7c3515 | 2015-09-28 15:37:57 +0300 | [diff] [blame] | 1439 | f, fname = tempfile.mkstemp(".py", "te st") |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 1440 | self.fname = fname.lower () |
| 1441 | os.write(f, b"import sys;" |
| 1442 | b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))" |
| 1443 | ) |
| 1444 | os.close(f) |
| 1445 | |
| 1446 | def tearDown(self): |
| 1447 | os.remove(self.fname) |
| 1448 | super(CommandsWithSpaces, self).tearDown() |
| 1449 | |
| 1450 | def with_spaces(self, *args, **kwargs): |
| 1451 | kwargs['stdout'] = subprocess.PIPE |
| 1452 | p = subprocess.Popen(*args, **kwargs) |
Brian Curtin | 7fe045e | 2010-11-05 17:19:38 +0000 | [diff] [blame] | 1453 | self.addCleanup(p.stdout.close) |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 1454 | self.assertEqual( |
| 1455 | p.stdout.read ().decode("mbcs"), |
| 1456 | "2 [%r, 'ab cd']" % self.fname |
| 1457 | ) |
| 1458 | |
| 1459 | def test_shell_string_with_spaces(self): |
| 1460 | # call() function with string argument with spaces on Windows |
Brian Curtin | e8c4920 | 2010-08-13 21:01:52 +0000 | [diff] [blame] | 1461 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 1462 | "ab cd"), shell=1) |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 1463 | |
| 1464 | def test_shell_sequence_with_spaces(self): |
| 1465 | # call() function with sequence argument with spaces on Windows |
Brian Curtin | e8c4920 | 2010-08-13 21:01:52 +0000 | [diff] [blame] | 1466 | self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1) |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 1467 | |
| 1468 | def test_noshell_string_with_spaces(self): |
| 1469 | # call() function with string argument with spaces on Windows |
| 1470 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 1471 | "ab cd")) |
| 1472 | |
| 1473 | def test_noshell_sequence_with_spaces(self): |
| 1474 | # call() function with sequence argument with spaces on Windows |
| 1475 | self.with_spaces([sys.executable, self.fname, "ab cd"]) |
| 1476 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1477 | def test_main(): |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1478 | unit_tests = (ProcessTestCase, |
| 1479 | POSIXProcessTestCase, |
| 1480 | Win32ProcessTestCase, |
Gregory P. Smith | cce211f | 2010-03-01 00:05:08 +0000 | [diff] [blame] | 1481 | ProcessTestCaseNoPoll, |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 1482 | HelperFunctionTests, |
| 1483 | CommandsWithSpaces) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1484 | |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1485 | test_support.run_unittest(*unit_tests) |
Florent Xicluna | 98e3fc3 | 2010-02-27 19:20:50 +0000 | [diff] [blame] | 1486 | test_support.reap_children() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1487 | |
| 1488 | if __name__ == "__main__": |
| 1489 | test_main() |