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