Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1 | import unittest |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 2 | from test import script_helper |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 3 | from test import support |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 4 | import subprocess |
| 5 | import sys |
| 6 | import signal |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 7 | import io |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 8 | import locale |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 9 | import os |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 10 | import errno |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 11 | import tempfile |
| 12 | import time |
Tim Peters | 3761e8d | 2004-10-13 04:07:12 +0000 | [diff] [blame] | 13 | import re |
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 |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 19 | import textwrap |
Benjamin Peterson | 964561b | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 20 | |
| 21 | try: |
| 22 | import resource |
| 23 | except ImportError: |
| 24 | resource = None |
| 25 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 26 | mswindows = (sys.platform == "win32") |
| 27 | |
| 28 | # |
| 29 | # Depends on the following external programs: Python |
| 30 | # |
| 31 | |
| 32 | if mswindows: |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 33 | SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), ' |
| 34 | 'os.O_BINARY);') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 35 | else: |
| 36 | SETBINARY = '' |
| 37 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 38 | |
| 39 | try: |
| 40 | mkstemp = tempfile.mkstemp |
| 41 | except AttributeError: |
| 42 | # tempfile.mkstemp is not available |
| 43 | def mkstemp(): |
| 44 | """Replacement for mkstemp, calling mktemp.""" |
| 45 | fname = tempfile.mktemp() |
| 46 | return os.open(fname, os.O_RDWR|os.O_CREAT), fname |
| 47 | |
Tim Peters | 3761e8d | 2004-10-13 04:07:12 +0000 | [diff] [blame] | 48 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 49 | class BaseTestCase(unittest.TestCase): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 50 | def setUp(self): |
| 51 | # Try to minimize the number of children we have so this test |
| 52 | # doesn't crash on some buildbots (Alphas in particular). |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 53 | support.reap_children() |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 54 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 55 | def tearDown(self): |
| 56 | for inst in subprocess._active: |
| 57 | inst.wait() |
| 58 | subprocess._cleanup() |
| 59 | self.assertFalse(subprocess._active, "subprocess._active not empty") |
| 60 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 61 | def assertStderrEqual(self, stderr, expected, msg=None): |
| 62 | # In a debug build, stuff like "[6580 refs]" is printed to stderr at |
| 63 | # shutdown time. That frustrates tests trying to check stderr produced |
| 64 | # from a spawned Python process. |
Antoine Pitrou | 62f68ed | 2010-08-04 11:48:56 +0000 | [diff] [blame] | 65 | actual = support.strip_python_stderr(stderr) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 66 | # strip_python_stderr also strips whitespace, so we do too. |
| 67 | expected = expected.strip() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 68 | self.assertEqual(actual, expected, msg) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 69 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 70 | |
| 71 | class ProcessTestCase(BaseTestCase): |
| 72 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 73 | def test_call_seq(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 74 | # call() function with sequence argument |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 75 | rc = subprocess.call([sys.executable, "-c", |
| 76 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 77 | self.assertEqual(rc, 47) |
| 78 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 79 | def test_call_timeout(self): |
| 80 | # call() function with timeout argument; we want to test that the child |
| 81 | # process gets killed when the timeout expires. If the child isn't |
| 82 | # killed, this call will deadlock since subprocess.call waits for the |
| 83 | # child. |
| 84 | self.assertRaises(subprocess.TimeoutExpired, subprocess.call, |
| 85 | [sys.executable, "-c", "while True: pass"], |
| 86 | timeout=0.1) |
| 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 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 130 | def test_check_output_timeout(self): |
| 131 | # check_output() function with timeout arg |
| 132 | with self.assertRaises(subprocess.TimeoutExpired) as c: |
| 133 | output = subprocess.check_output( |
| 134 | [sys.executable, "-c", |
Victor Stinner | 149b1c7 | 2011-06-06 23:43:02 +0200 | [diff] [blame] | 135 | "import sys, time\n" |
| 136 | "sys.stdout.write('BDFL')\n" |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 137 | "sys.stdout.flush()\n" |
Victor Stinner | 149b1c7 | 2011-06-06 23:43:02 +0200 | [diff] [blame] | 138 | "time.sleep(3600)"], |
Reid Kleckner | da9ac72 | 2011-03-16 17:08:21 -0400 | [diff] [blame] | 139 | # Some heavily loaded buildbots (sparc Debian 3.x) require |
| 140 | # this much time to start and print. |
| 141 | timeout=3) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 142 | self.fail("Expected TimeoutExpired.") |
| 143 | self.assertEqual(c.exception.output, b'BDFL') |
| 144 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 145 | def test_call_kwargs(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 146 | # call() function with keyword args |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 147 | newenv = os.environ.copy() |
| 148 | newenv["FRUIT"] = "banana" |
| 149 | rc = subprocess.call([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 150 | 'import sys, os;' |
| 151 | 'sys.exit(os.getenv("FRUIT")=="banana")'], |
| 152 | env=newenv) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 153 | self.assertEqual(rc, 1) |
| 154 | |
Victor Stinner | 87b9bc3 | 2011-06-01 00:57:47 +0200 | [diff] [blame] | 155 | def test_invalid_args(self): |
| 156 | # Popen() called with invalid arguments should raise TypeError |
| 157 | # but Popen.__del__ should not complain (issue #12085) |
| 158 | with support.captured_stderr() as s: |
| 159 | self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1) |
| 160 | argcount = subprocess.Popen.__init__.__code__.co_argcount |
| 161 | too_many_args = [0] * (argcount + 1) |
| 162 | self.assertRaises(TypeError, subprocess.Popen, *too_many_args) |
| 163 | self.assertEqual(s.getvalue(), '') |
| 164 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 165 | def test_stdin_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 166 | # .stdin is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 167 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 168 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 169 | self.addCleanup(p.stdout.close) |
| 170 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 171 | p.wait() |
| 172 | self.assertEqual(p.stdin, None) |
| 173 | |
| 174 | def test_stdout_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 175 | # .stdout is None when not redirected |
Tim Peters | 29b6b4f | 2004-10-13 03:43:40 +0000 | [diff] [blame] | 176 | p = subprocess.Popen([sys.executable, "-c", |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 177 | 'print(" this bit of output is from a ' |
Tim Peters | 4052fe5 | 2004-10-13 03:29:54 +0000 | [diff] [blame] | 178 | 'test of stdout in a different ' |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 179 | 'process ...")'], |
Tim Peters | 4052fe5 | 2004-10-13 03:29:54 +0000 | [diff] [blame] | 180 | stdin=subprocess.PIPE, stderr=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 181 | self.addCleanup(p.stdin.close) |
| 182 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 183 | p.wait() |
| 184 | self.assertEqual(p.stdout, None) |
| 185 | |
| 186 | def test_stderr_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 187 | # .stderr is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 188 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 189 | stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 190 | self.addCleanup(p.stdout.close) |
| 191 | self.addCleanup(p.stdin.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 192 | p.wait() |
| 193 | self.assertEqual(p.stderr, None) |
| 194 | |
Chris Jerdonek | 776cb19 | 2012-10-08 15:56:43 -0700 | [diff] [blame] | 195 | def _assert_python(self, pre_args, **kwargs): |
| 196 | # We include sys.exit() to prevent the test runner from hanging |
| 197 | # whenever python is found. |
| 198 | args = pre_args + ["import sys; sys.exit(47)"] |
| 199 | p = subprocess.Popen(args, **kwargs) |
| 200 | p.wait() |
| 201 | self.assertEqual(47, p.returncode) |
| 202 | |
Chris Jerdonek | 2d051b8 | 2012-10-08 17:53:46 -0700 | [diff] [blame] | 203 | # TODO: make this test work on Linux. |
| 204 | # This may be failing on Linux because of issue #7774. |
| 205 | @unittest.skipIf(sys.platform not in ('win32', 'darwin'), |
| 206 | "possible bug using executable argument on Linux") |
Chris Jerdonek | 776cb19 | 2012-10-08 15:56:43 -0700 | [diff] [blame] | 207 | def test_executable(self): |
| 208 | # Check that the executable argument works. |
| 209 | self._assert_python(["doesnotexist", "-c"], executable=sys.executable) |
| 210 | |
| 211 | def test_executable_takes_precedence(self): |
| 212 | # Check that the executable argument takes precedence over args[0]. |
| 213 | # |
| 214 | # Verify first that the call succeeds without the executable arg. |
| 215 | pre_args = [sys.executable, "-c"] |
| 216 | self._assert_python(pre_args) |
| 217 | self.assertRaises(FileNotFoundError, self._assert_python, pre_args, |
| 218 | executable="doesnotexist") |
| 219 | |
| 220 | @unittest.skipIf(mswindows, "executable argument replaces shell") |
| 221 | def test_executable_replaces_shell(self): |
| 222 | # Check that the executable argument replaces the default shell |
| 223 | # when shell=True. |
| 224 | self._assert_python([], executable=sys.executable, shell=True) |
| 225 | |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 226 | # For use in the test_cwd* tests below. |
| 227 | def _normalize_cwd(self, cwd): |
| 228 | # Normalize an expected cwd (for Tru64 support). |
| 229 | # We can't use os.path.realpath since it doesn't expand Tru64 {memb} |
| 230 | # strings. See bug #1063571. |
| 231 | original_cwd = os.getcwd() |
| 232 | os.chdir(cwd) |
| 233 | cwd = os.getcwd() |
| 234 | os.chdir(original_cwd) |
| 235 | return cwd |
| 236 | |
| 237 | # For use in the test_cwd* tests below. |
| 238 | def _split_python_path(self): |
| 239 | # Return normalized (python_dir, python_base). |
| 240 | python_path = os.path.realpath(sys.executable) |
| 241 | return os.path.split(python_path) |
| 242 | |
| 243 | # For use in the test_cwd* tests below. |
| 244 | def _assert_cwd(self, expected_cwd, python_arg, **kwargs): |
| 245 | # Invoke Python via Popen, and assert that (1) the call succeeds, |
| 246 | # and that (2) the current working directory of the child process |
| 247 | # matches *expected_cwd*. |
| 248 | p = subprocess.Popen([python_arg, "-c", |
| 249 | "import os, sys; " |
| 250 | "sys.stdout.write(os.getcwd()); " |
| 251 | "sys.exit(47)"], |
| 252 | stdout=subprocess.PIPE, |
| 253 | **kwargs) |
| 254 | self.addCleanup(p.stdout.close) |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 255 | p.wait() |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 256 | self.assertEqual(47, p.returncode) |
| 257 | normcase = os.path.normcase |
| 258 | self.assertEqual(normcase(expected_cwd), |
| 259 | normcase(p.stdout.read().decode("utf-8"))) |
| 260 | |
| 261 | def test_cwd(self): |
| 262 | # Check that cwd changes the cwd for the child process. |
| 263 | temp_dir = tempfile.gettempdir() |
| 264 | temp_dir = self._normalize_cwd(temp_dir) |
| 265 | self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir) |
| 266 | |
Chris Jerdonek | c2cd626 | 2012-09-30 09:45:00 -0700 | [diff] [blame] | 267 | @unittest.skipIf(mswindows, "pending resolution of issue #15533") |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 268 | def test_cwd_with_relative_arg(self): |
| 269 | # Check that Popen looks for args[0] relative to cwd if args[0] |
| 270 | # is relative. |
| 271 | python_dir, python_base = self._split_python_path() |
| 272 | rel_python = os.path.join(os.curdir, python_base) |
| 273 | with support.temp_cwd() as wrong_dir: |
| 274 | # Before calling with the correct cwd, confirm that the call fails |
| 275 | # without cwd and with the wrong cwd. |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 276 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 277 | [rel_python]) |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 278 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 279 | [rel_python], cwd=wrong_dir) |
| 280 | python_dir = self._normalize_cwd(python_dir) |
| 281 | self._assert_cwd(python_dir, rel_python, cwd=python_dir) |
| 282 | |
Chris Jerdonek | c2cd626 | 2012-09-30 09:45:00 -0700 | [diff] [blame] | 283 | @unittest.skipIf(mswindows, "pending resolution of issue #15533") |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 284 | def test_cwd_with_relative_executable(self): |
| 285 | # Check that Popen looks for executable relative to cwd if executable |
| 286 | # is relative (and that executable takes precedence over args[0]). |
| 287 | python_dir, python_base = self._split_python_path() |
| 288 | rel_python = os.path.join(os.curdir, python_base) |
| 289 | doesntexist = "somethingyoudonthave" |
| 290 | with support.temp_cwd() as wrong_dir: |
| 291 | # Before calling with the correct cwd, confirm that the call fails |
| 292 | # without cwd and with the wrong cwd. |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 293 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 294 | [doesntexist], executable=rel_python) |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 295 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 296 | [doesntexist], executable=rel_python, |
| 297 | cwd=wrong_dir) |
| 298 | python_dir = self._normalize_cwd(python_dir) |
| 299 | self._assert_cwd(python_dir, doesntexist, executable=rel_python, |
| 300 | cwd=python_dir) |
| 301 | |
| 302 | def test_cwd_with_absolute_arg(self): |
| 303 | # Check that Popen can find the executable when the cwd is wrong |
| 304 | # if args[0] is an absolute path. |
| 305 | python_dir, python_base = self._split_python_path() |
| 306 | abs_python = os.path.join(python_dir, python_base) |
| 307 | rel_python = os.path.join(os.curdir, python_base) |
| 308 | with script_helper.temp_dir() as wrong_dir: |
| 309 | # Before calling with an absolute path, confirm that using a |
| 310 | # relative path fails. |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 311 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 312 | [rel_python], cwd=wrong_dir) |
| 313 | wrong_dir = self._normalize_cwd(wrong_dir) |
| 314 | self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir) |
| 315 | |
Vinay Sajip | 7ded1f0 | 2012-05-26 03:45:29 +0100 | [diff] [blame] | 316 | @unittest.skipIf(sys.base_prefix != sys.prefix, |
| 317 | 'Test is not venv-compatible') |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 318 | def test_executable_with_cwd(self): |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 319 | python_dir, python_base = self._split_python_path() |
| 320 | python_dir = self._normalize_cwd(python_dir) |
| 321 | self._assert_cwd(python_dir, "somethingyoudonthave", |
| 322 | executable=sys.executable, cwd=python_dir) |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 323 | |
Vinay Sajip | 7ded1f0 | 2012-05-26 03:45:29 +0100 | [diff] [blame] | 324 | @unittest.skipIf(sys.base_prefix != sys.prefix, |
| 325 | 'Test is not venv-compatible') |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 326 | @unittest.skipIf(sysconfig.is_python_build(), |
| 327 | "need an installed Python. See #7774") |
| 328 | def test_executable_without_cwd(self): |
| 329 | # For a normal installation, it should work without 'cwd' |
| 330 | # argument. For test runs in the build directory, see #7774. |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 331 | self._assert_cwd('', "somethingyoudonthave", executable=sys.executable) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 332 | |
| 333 | def test_stdin_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 334 | # stdin redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 335 | p = subprocess.Popen([sys.executable, "-c", |
| 336 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 337 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 338 | p.stdin.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 339 | p.stdin.close() |
| 340 | p.wait() |
| 341 | self.assertEqual(p.returncode, 1) |
| 342 | |
| 343 | def test_stdin_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 344 | # stdin is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 345 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 346 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 347 | d = tf.fileno() |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 348 | os.write(d, b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 349 | os.lseek(d, 0, 0) |
| 350 | p = subprocess.Popen([sys.executable, "-c", |
| 351 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 352 | stdin=d) |
| 353 | p.wait() |
| 354 | self.assertEqual(p.returncode, 1) |
| 355 | |
| 356 | def test_stdin_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 357 | # stdin is set to open file object |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 358 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 359 | self.addCleanup(tf.close) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 360 | tf.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 361 | tf.seek(0) |
| 362 | p = subprocess.Popen([sys.executable, "-c", |
| 363 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 364 | stdin=tf) |
| 365 | p.wait() |
| 366 | self.assertEqual(p.returncode, 1) |
| 367 | |
| 368 | def test_stdout_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 369 | # stdout redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 370 | p = subprocess.Popen([sys.executable, "-c", |
| 371 | 'import sys; sys.stdout.write("orange")'], |
| 372 | stdout=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 373 | self.addCleanup(p.stdout.close) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 374 | self.assertEqual(p.stdout.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 375 | |
| 376 | def test_stdout_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 377 | # stdout is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 378 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 379 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 380 | d = tf.fileno() |
| 381 | p = subprocess.Popen([sys.executable, "-c", |
| 382 | 'import sys; sys.stdout.write("orange")'], |
| 383 | stdout=d) |
| 384 | p.wait() |
| 385 | os.lseek(d, 0, 0) |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 386 | self.assertEqual(os.read(d, 1024), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 387 | |
| 388 | def test_stdout_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 389 | # stdout is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 390 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 391 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 392 | p = subprocess.Popen([sys.executable, "-c", |
| 393 | 'import sys; sys.stdout.write("orange")'], |
| 394 | stdout=tf) |
| 395 | p.wait() |
| 396 | tf.seek(0) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 397 | self.assertEqual(tf.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 398 | |
| 399 | def test_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 400 | # stderr redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 401 | p = subprocess.Popen([sys.executable, "-c", |
| 402 | 'import sys; sys.stderr.write("strawberry")'], |
| 403 | stderr=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 404 | self.addCleanup(p.stderr.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 405 | self.assertStderrEqual(p.stderr.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 406 | |
| 407 | def test_stderr_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 408 | # stderr is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 409 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 410 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 411 | d = tf.fileno() |
| 412 | p = subprocess.Popen([sys.executable, "-c", |
| 413 | 'import sys; sys.stderr.write("strawberry")'], |
| 414 | stderr=d) |
| 415 | p.wait() |
| 416 | os.lseek(d, 0, 0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 417 | self.assertStderrEqual(os.read(d, 1024), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 418 | |
| 419 | def test_stderr_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 420 | # stderr is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 421 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 422 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 423 | p = subprocess.Popen([sys.executable, "-c", |
| 424 | 'import sys; sys.stderr.write("strawberry")'], |
| 425 | stderr=tf) |
| 426 | p.wait() |
| 427 | tf.seek(0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 428 | self.assertStderrEqual(tf.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 429 | |
| 430 | def test_stdout_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 431 | # capture stdout and stderr to the same pipe |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 432 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 433 | 'import sys;' |
| 434 | 'sys.stdout.write("apple");' |
| 435 | 'sys.stdout.flush();' |
| 436 | 'sys.stderr.write("orange")'], |
| 437 | stdout=subprocess.PIPE, |
| 438 | stderr=subprocess.STDOUT) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 439 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 440 | self.assertStderrEqual(p.stdout.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 441 | |
| 442 | def test_stdout_stderr_file(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 443 | # capture stdout and stderr to the same open file |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 444 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 445 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 446 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 447 | 'import sys;' |
| 448 | 'sys.stdout.write("apple");' |
| 449 | 'sys.stdout.flush();' |
| 450 | 'sys.stderr.write("orange")'], |
| 451 | stdout=tf, |
| 452 | stderr=tf) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 453 | p.wait() |
| 454 | tf.seek(0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 455 | self.assertStderrEqual(tf.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 456 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 457 | def test_stdout_filedes_of_stdout(self): |
| 458 | # stdout is set to 1 (#1531862). |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 459 | cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))" |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 460 | rc = subprocess.call([sys.executable, "-c", cmd], stdout=1) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 461 | self.assertEqual(rc, 2) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 462 | |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 463 | def test_stdout_devnull(self): |
| 464 | p = subprocess.Popen([sys.executable, "-c", |
| 465 | 'for i in range(10240):' |
| 466 | 'print("x" * 1024)'], |
| 467 | stdout=subprocess.DEVNULL) |
| 468 | p.wait() |
| 469 | self.assertEqual(p.stdout, None) |
| 470 | |
| 471 | def test_stderr_devnull(self): |
| 472 | p = subprocess.Popen([sys.executable, "-c", |
| 473 | 'import sys\n' |
| 474 | 'for i in range(10240):' |
| 475 | 'sys.stderr.write("x" * 1024)'], |
| 476 | stderr=subprocess.DEVNULL) |
| 477 | p.wait() |
| 478 | self.assertEqual(p.stderr, None) |
| 479 | |
| 480 | def test_stdin_devnull(self): |
| 481 | p = subprocess.Popen([sys.executable, "-c", |
| 482 | 'import sys;' |
| 483 | 'sys.stdin.read(1)'], |
| 484 | stdin=subprocess.DEVNULL) |
| 485 | p.wait() |
| 486 | self.assertEqual(p.stdin, None) |
| 487 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 488 | def test_env(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 489 | newenv = os.environ.copy() |
| 490 | newenv["FRUIT"] = "orange" |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 491 | with subprocess.Popen([sys.executable, "-c", |
| 492 | 'import sys,os;' |
| 493 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 494 | stdout=subprocess.PIPE, |
| 495 | env=newenv) as p: |
| 496 | stdout, stderr = p.communicate() |
| 497 | self.assertEqual(stdout, b"orange") |
| 498 | |
Victor Stinner | 62d5118 | 2011-06-23 01:02:25 +0200 | [diff] [blame] | 499 | # Windows requires at least the SYSTEMROOT environment variable to start |
| 500 | # Python |
| 501 | @unittest.skipIf(sys.platform == 'win32', |
| 502 | 'cannot test an empty env on Windows') |
Victor Stinner | 237e5cb | 2011-06-22 21:28:43 +0200 | [diff] [blame] | 503 | @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None, |
Victor Stinner | 372309a | 2011-06-21 21:59:06 +0200 | [diff] [blame] | 504 | 'the python library cannot be loaded ' |
| 505 | 'with an empty environment') |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 506 | def test_empty_env(self): |
| 507 | with subprocess.Popen([sys.executable, "-c", |
| 508 | 'import os; ' |
Victor Stinner | 372309a | 2011-06-21 21:59:06 +0200 | [diff] [blame] | 509 | 'print(list(os.environ.keys()))'], |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 510 | stdout=subprocess.PIPE, |
| 511 | env={}) as p: |
| 512 | stdout, stderr = p.communicate() |
Victor Stinner | 237e5cb | 2011-06-22 21:28:43 +0200 | [diff] [blame] | 513 | self.assertIn(stdout.strip(), |
| 514 | (b"[]", |
| 515 | # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty |
| 516 | # environment |
| 517 | b"['__CF_USER_TEXT_ENCODING']")) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 518 | |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 519 | def test_communicate_stdin(self): |
| 520 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 521 | 'import sys;' |
| 522 | 'sys.exit(sys.stdin.read() == "pear")'], |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 523 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 524 | p.communicate(b"pear") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 525 | self.assertEqual(p.returncode, 1) |
| 526 | |
| 527 | def test_communicate_stdout(self): |
| 528 | p = subprocess.Popen([sys.executable, "-c", |
| 529 | 'import sys; sys.stdout.write("pineapple")'], |
| 530 | stdout=subprocess.PIPE) |
| 531 | (stdout, stderr) = p.communicate() |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 532 | self.assertEqual(stdout, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 533 | self.assertEqual(stderr, None) |
| 534 | |
| 535 | def test_communicate_stderr(self): |
| 536 | p = subprocess.Popen([sys.executable, "-c", |
| 537 | 'import sys; sys.stderr.write("pineapple")'], |
| 538 | stderr=subprocess.PIPE) |
| 539 | (stdout, stderr) = p.communicate() |
| 540 | self.assertEqual(stdout, None) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 541 | self.assertStderrEqual(stderr, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 542 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 543 | def test_communicate(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 544 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 545 | 'import sys,os;' |
| 546 | 'sys.stderr.write("pineapple");' |
| 547 | 'sys.stdout.write(sys.stdin.read())'], |
| 548 | stdin=subprocess.PIPE, |
| 549 | stdout=subprocess.PIPE, |
| 550 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 551 | self.addCleanup(p.stdout.close) |
| 552 | self.addCleanup(p.stderr.close) |
| 553 | self.addCleanup(p.stdin.close) |
Georg Brandl | 1abcbf8 | 2008-07-01 19:28:43 +0000 | [diff] [blame] | 554 | (stdout, stderr) = p.communicate(b"banana") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 555 | self.assertEqual(stdout, b"banana") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 556 | self.assertStderrEqual(stderr, b"pineapple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 557 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 558 | def test_communicate_timeout(self): |
| 559 | p = subprocess.Popen([sys.executable, "-c", |
| 560 | 'import sys,os,time;' |
| 561 | 'sys.stderr.write("pineapple\\n");' |
| 562 | 'time.sleep(1);' |
| 563 | 'sys.stderr.write("pear\\n");' |
| 564 | 'sys.stdout.write(sys.stdin.read())'], |
| 565 | universal_newlines=True, |
| 566 | stdin=subprocess.PIPE, |
| 567 | stdout=subprocess.PIPE, |
| 568 | stderr=subprocess.PIPE) |
| 569 | self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana", |
| 570 | timeout=0.3) |
| 571 | # Make sure we can keep waiting for it, and that we get the whole output |
| 572 | # after it completes. |
| 573 | (stdout, stderr) = p.communicate() |
| 574 | self.assertEqual(stdout, "banana") |
| 575 | self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n") |
| 576 | |
| 577 | def test_communicate_timeout_large_ouput(self): |
Ross Lagerwall | 003c7a3 | 2012-02-12 09:02:01 +0200 | [diff] [blame] | 578 | # Test an expiring timeout while the child is outputting lots of data. |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 579 | p = subprocess.Popen([sys.executable, "-c", |
| 580 | 'import sys,os,time;' |
| 581 | 'sys.stdout.write("a" * (64 * 1024));' |
| 582 | 'time.sleep(0.2);' |
| 583 | 'sys.stdout.write("a" * (64 * 1024));' |
| 584 | 'time.sleep(0.2);' |
| 585 | 'sys.stdout.write("a" * (64 * 1024));' |
| 586 | 'time.sleep(0.2);' |
| 587 | 'sys.stdout.write("a" * (64 * 1024));'], |
| 588 | stdout=subprocess.PIPE) |
| 589 | self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4) |
| 590 | (stdout, _) = p.communicate() |
| 591 | self.assertEqual(len(stdout), 4 * 64 * 1024) |
| 592 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 593 | # Test for the fd leak reported in http://bugs.python.org/issue2791. |
| 594 | def test_communicate_pipe_fd_leak(self): |
Victor Stinner | 667d4b5 | 2010-12-25 22:40:32 +0000 | [diff] [blame] | 595 | for stdin_pipe in (False, True): |
| 596 | for stdout_pipe in (False, True): |
| 597 | for stderr_pipe in (False, True): |
| 598 | options = {} |
| 599 | if stdin_pipe: |
| 600 | options['stdin'] = subprocess.PIPE |
| 601 | if stdout_pipe: |
| 602 | options['stdout'] = subprocess.PIPE |
| 603 | if stderr_pipe: |
| 604 | options['stderr'] = subprocess.PIPE |
| 605 | if not options: |
| 606 | continue |
| 607 | p = subprocess.Popen((sys.executable, "-c", "pass"), **options) |
| 608 | p.communicate() |
| 609 | if p.stdin is not None: |
| 610 | self.assertTrue(p.stdin.closed) |
| 611 | if p.stdout is not None: |
| 612 | self.assertTrue(p.stdout.closed) |
| 613 | if p.stderr is not None: |
| 614 | self.assertTrue(p.stderr.closed) |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 615 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 616 | def test_communicate_returns(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 617 | # communicate() should return None if no redirection is active |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 618 | p = subprocess.Popen([sys.executable, "-c", |
| 619 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 620 | (stdout, stderr) = p.communicate() |
| 621 | self.assertEqual(stdout, None) |
| 622 | self.assertEqual(stderr, None) |
| 623 | |
| 624 | def test_communicate_pipe_buf(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 625 | # communicate() with writes larger than pipe_buf |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 626 | # This test will probably deadlock rather than fail, if |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 627 | # communicate() does not work properly. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 628 | x, y = os.pipe() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 629 | os.close(x) |
| 630 | os.close(y) |
| 631 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 632 | 'import sys,os;' |
| 633 | 'sys.stdout.write(sys.stdin.read(47));' |
Charles-François Natali | 2d51721 | 2011-05-29 16:36:44 +0200 | [diff] [blame] | 634 | 'sys.stderr.write("x" * %d);' |
| 635 | 'sys.stdout.write(sys.stdin.read())' % |
| 636 | support.PIPE_MAX_SIZE], |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 637 | stdin=subprocess.PIPE, |
| 638 | stdout=subprocess.PIPE, |
| 639 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 640 | self.addCleanup(p.stdout.close) |
| 641 | self.addCleanup(p.stderr.close) |
| 642 | self.addCleanup(p.stdin.close) |
Charles-François Natali | 2d51721 | 2011-05-29 16:36:44 +0200 | [diff] [blame] | 643 | string_to_write = b"a" * support.PIPE_MAX_SIZE |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 644 | (stdout, stderr) = p.communicate(string_to_write) |
| 645 | self.assertEqual(stdout, string_to_write) |
| 646 | |
| 647 | def test_writes_before_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 648 | # stdin.write before communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 649 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 650 | 'import sys,os;' |
| 651 | 'sys.stdout.write(sys.stdin.read())'], |
| 652 | stdin=subprocess.PIPE, |
| 653 | stdout=subprocess.PIPE, |
| 654 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 655 | self.addCleanup(p.stdout.close) |
| 656 | self.addCleanup(p.stderr.close) |
| 657 | self.addCleanup(p.stdin.close) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 658 | p.stdin.write(b"banana") |
| 659 | (stdout, stderr) = p.communicate(b"split") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 660 | self.assertEqual(stdout, b"bananasplit") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 661 | self.assertStderrEqual(stderr, b"") |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 662 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 663 | def test_universal_newlines(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 664 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 665 | 'import sys,os;' + SETBINARY + |
Antoine Pitrou | ec2d269 | 2012-08-05 00:23:40 +0200 | [diff] [blame] | 666 | 'buf = sys.stdout.buffer;' |
| 667 | 'buf.write(sys.stdin.readline().encode());' |
| 668 | 'buf.flush();' |
| 669 | 'buf.write(b"line2\\n");' |
| 670 | 'buf.flush();' |
| 671 | 'buf.write(sys.stdin.read().encode());' |
| 672 | 'buf.flush();' |
| 673 | 'buf.write(b"line4\\n");' |
| 674 | 'buf.flush();' |
| 675 | 'buf.write(b"line5\\r\\n");' |
| 676 | 'buf.flush();' |
| 677 | 'buf.write(b"line6\\r");' |
| 678 | 'buf.flush();' |
| 679 | 'buf.write(b"\\nline7");' |
| 680 | 'buf.flush();' |
| 681 | 'buf.write(b"\\nline8");'], |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 682 | stdin=subprocess.PIPE, |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 683 | stdout=subprocess.PIPE, |
| 684 | universal_newlines=1) |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 685 | p.stdin.write("line1\n") |
| 686 | self.assertEqual(p.stdout.readline(), "line1\n") |
| 687 | p.stdin.write("line3\n") |
| 688 | p.stdin.close() |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 689 | self.addCleanup(p.stdout.close) |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 690 | self.assertEqual(p.stdout.readline(), |
| 691 | "line2\n") |
| 692 | self.assertEqual(p.stdout.read(6), |
| 693 | "line3\n") |
| 694 | self.assertEqual(p.stdout.read(), |
| 695 | "line4\nline5\nline6\nline7\nline8") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 696 | |
| 697 | def test_universal_newlines_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 698 | # universal newlines through communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 699 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 700 | 'import sys,os;' + SETBINARY + |
Antoine Pitrou | ec2d269 | 2012-08-05 00:23:40 +0200 | [diff] [blame] | 701 | 'buf = sys.stdout.buffer;' |
| 702 | 'buf.write(b"line2\\n");' |
| 703 | 'buf.flush();' |
| 704 | 'buf.write(b"line4\\n");' |
| 705 | 'buf.flush();' |
| 706 | 'buf.write(b"line5\\r\\n");' |
| 707 | 'buf.flush();' |
| 708 | 'buf.write(b"line6\\r");' |
| 709 | 'buf.flush();' |
| 710 | 'buf.write(b"\\nline7");' |
| 711 | 'buf.flush();' |
| 712 | 'buf.write(b"\\nline8");'], |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 713 | stderr=subprocess.PIPE, |
| 714 | stdout=subprocess.PIPE, |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 715 | universal_newlines=1) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 716 | self.addCleanup(p.stdout.close) |
| 717 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 718 | (stdout, stderr) = p.communicate() |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 719 | self.assertEqual(stdout, |
| 720 | "line2\nline4\nline5\nline6\nline7\nline8") |
| 721 | |
| 722 | def test_universal_newlines_communicate_stdin(self): |
| 723 | # universal newlines through communicate(), with only stdin |
| 724 | p = subprocess.Popen([sys.executable, "-c", |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 725 | 'import sys,os;' + SETBINARY + textwrap.dedent(''' |
| 726 | s = sys.stdin.readline() |
| 727 | assert s == "line1\\n", repr(s) |
| 728 | s = sys.stdin.read() |
| 729 | assert s == "line3\\n", repr(s) |
| 730 | ''')], |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 731 | stdin=subprocess.PIPE, |
| 732 | universal_newlines=1) |
| 733 | (stdout, stderr) = p.communicate("line1\nline3\n") |
| 734 | self.assertEqual(p.returncode, 0) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 735 | |
Andrew Svetlov | f376507 | 2012-08-14 18:35:17 +0300 | [diff] [blame] | 736 | def test_universal_newlines_communicate_input_none(self): |
| 737 | # Test communicate(input=None) with universal newlines. |
| 738 | # |
| 739 | # We set stdout to PIPE because, as of this writing, a different |
| 740 | # code path is tested when the number of pipes is zero or one. |
| 741 | p = subprocess.Popen([sys.executable, "-c", "pass"], |
| 742 | stdin=subprocess.PIPE, |
| 743 | stdout=subprocess.PIPE, |
| 744 | universal_newlines=True) |
| 745 | p.communicate() |
| 746 | self.assertEqual(p.returncode, 0) |
| 747 | |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 748 | def test_universal_newlines_communicate_stdin_stdout_stderr(self): |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 749 | # universal newlines through communicate(), with stdin, stdout, stderr |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 750 | p = subprocess.Popen([sys.executable, "-c", |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 751 | 'import sys,os;' + SETBINARY + textwrap.dedent(''' |
| 752 | s = sys.stdin.buffer.readline() |
| 753 | sys.stdout.buffer.write(s) |
| 754 | sys.stdout.buffer.write(b"line2\\r") |
| 755 | sys.stderr.buffer.write(b"eline2\\n") |
| 756 | s = sys.stdin.buffer.read() |
| 757 | sys.stdout.buffer.write(s) |
| 758 | sys.stdout.buffer.write(b"line4\\n") |
| 759 | sys.stdout.buffer.write(b"line5\\r\\n") |
| 760 | sys.stderr.buffer.write(b"eline6\\r") |
| 761 | sys.stderr.buffer.write(b"eline7\\r\\nz") |
| 762 | ''')], |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 763 | stdin=subprocess.PIPE, |
| 764 | stderr=subprocess.PIPE, |
| 765 | stdout=subprocess.PIPE, |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 766 | universal_newlines=True) |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 767 | self.addCleanup(p.stdout.close) |
| 768 | self.addCleanup(p.stderr.close) |
| 769 | (stdout, stderr) = p.communicate("line1\nline3\n") |
| 770 | self.assertEqual(p.returncode, 0) |
Andrew Svetlov | 943c5b3 | 2012-08-16 20:17:47 +0300 | [diff] [blame] | 771 | self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout) |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 772 | # Python debug build push something like "[42442 refs]\n" |
| 773 | # to stderr at exit of subprocess. |
Andrew Svetlov | 943c5b3 | 2012-08-16 20:17:47 +0300 | [diff] [blame] | 774 | # Don't use assertStderrEqual because it strips CR and LF from output. |
| 775 | self.assertTrue(stderr.startswith("eline2\neline6\neline7\n")) |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 776 | |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 777 | def test_universal_newlines_communicate_encodings(self): |
| 778 | # Check that universal newlines mode works for various encodings, |
| 779 | # in particular for encodings in the UTF-16 and UTF-32 families. |
| 780 | # See issue #15595. |
| 781 | # |
| 782 | # UTF-16 and UTF-32-BE are sufficient to check both with BOM and |
| 783 | # without, and UTF-16 and UTF-32. |
| 784 | for encoding in ['utf-16', 'utf-32-be']: |
| 785 | old_getpreferredencoding = locale.getpreferredencoding |
| 786 | # Indirectly via io.TextIOWrapper, Popen() defaults to |
| 787 | # locale.getpreferredencoding(False) and earlier in Python 3.2 to |
| 788 | # locale.getpreferredencoding(). |
| 789 | def getpreferredencoding(do_setlocale=True): |
| 790 | return encoding |
| 791 | code = ("import sys; " |
| 792 | r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" % |
| 793 | encoding) |
| 794 | args = [sys.executable, '-c', code] |
| 795 | try: |
| 796 | locale.getpreferredencoding = getpreferredencoding |
| 797 | # We set stdin to be non-None because, as of this writing, |
| 798 | # a different code path is used when the number of pipes is |
| 799 | # zero or one. |
| 800 | popen = subprocess.Popen(args, universal_newlines=True, |
| 801 | stdin=subprocess.PIPE, |
| 802 | stdout=subprocess.PIPE) |
| 803 | stdout, stderr = popen.communicate(input='') |
| 804 | finally: |
| 805 | locale.getpreferredencoding = old_getpreferredencoding |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 806 | self.assertEqual(stdout, '1\n2\n3\n4') |
| 807 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 808 | def test_no_leaking(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 809 | # Make sure we leak no resources |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 810 | if not mswindows: |
Peter Astrand | f7f1bb7 | 2005-03-03 20:47:37 +0000 | [diff] [blame] | 811 | max_handles = 1026 # too much for most UNIX systems |
| 812 | else: |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 813 | max_handles = 2050 # too much for (at least some) Windows setups |
| 814 | handles = [] |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 815 | tmpdir = tempfile.mkdtemp() |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 816 | try: |
| 817 | for i in range(max_handles): |
| 818 | try: |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 819 | tmpfile = os.path.join(tmpdir, support.TESTFN) |
| 820 | handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT)) |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 821 | except OSError as e: |
| 822 | if e.errno != errno.EMFILE: |
| 823 | raise |
| 824 | break |
| 825 | else: |
| 826 | self.skipTest("failed to reach the file descriptor limit " |
| 827 | "(tried %d)" % max_handles) |
| 828 | # Close a couple of them (should be enough for a subprocess) |
| 829 | for i in range(10): |
| 830 | os.close(handles.pop()) |
| 831 | # Loop creating some subprocesses. If one of them leaks some fds, |
| 832 | # the next loop iteration will fail by reaching the max fd limit. |
| 833 | for i in range(15): |
| 834 | p = subprocess.Popen([sys.executable, "-c", |
| 835 | "import sys;" |
| 836 | "sys.stdout.write(sys.stdin.read())"], |
| 837 | stdin=subprocess.PIPE, |
| 838 | stdout=subprocess.PIPE, |
| 839 | stderr=subprocess.PIPE) |
| 840 | data = p.communicate(b"lime")[0] |
| 841 | self.assertEqual(data, b"lime") |
| 842 | finally: |
| 843 | for h in handles: |
| 844 | os.close(h) |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 845 | shutil.rmtree(tmpdir) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 846 | |
| 847 | def test_list2cmdline(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 848 | self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']), |
| 849 | '"a b c" d e') |
| 850 | self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']), |
| 851 | 'ab\\"c \\ d') |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 852 | self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']), |
| 853 | 'ab\\"c " \\\\" d') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 854 | self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']), |
| 855 | 'a\\\\\\b "de fg" h') |
| 856 | self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']), |
| 857 | 'a\\\\\\"b c d') |
| 858 | self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']), |
| 859 | '"a\\\\b c" d e') |
| 860 | self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']), |
| 861 | '"a\\\\b\\ c" d e') |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 862 | self.assertEqual(subprocess.list2cmdline(['ab', '']), |
| 863 | 'ab ""') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 864 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 865 | def test_poll(self): |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 866 | p = subprocess.Popen([sys.executable, "-c", |
Ross Lagerwall | e7ad419 | 2012-02-22 06:02:07 +0200 | [diff] [blame] | 867 | "import os; os.read(0, 1)"], |
| 868 | stdin=subprocess.PIPE) |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 869 | self.addCleanup(p.stdin.close) |
| 870 | self.assertIsNone(p.poll()) |
| 871 | os.write(p.stdin.fileno(), b'A') |
| 872 | p.wait() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 873 | # Subsequent invocations should just return the returncode |
| 874 | self.assertEqual(p.poll(), 0) |
| 875 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 876 | def test_wait(self): |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 877 | p = subprocess.Popen([sys.executable, "-c", "pass"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 878 | self.assertEqual(p.wait(), 0) |
| 879 | # Subsequent invocations should just return the returncode |
| 880 | self.assertEqual(p.wait(), 0) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 881 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 882 | def test_wait_timeout(self): |
| 883 | p = subprocess.Popen([sys.executable, |
Reid Kleckner | 93479cc | 2011-03-14 19:32:41 -0400 | [diff] [blame] | 884 | "-c", "import time; time.sleep(0.1)"]) |
Reid Kleckner | 2b228f0 | 2011-03-16 16:57:54 -0400 | [diff] [blame] | 885 | with self.assertRaises(subprocess.TimeoutExpired) as c: |
| 886 | p.wait(timeout=0.01) |
| 887 | self.assertIn("0.01", str(c.exception)) # For coverage of __str__. |
Reid Kleckner | da9ac72 | 2011-03-16 17:08:21 -0400 | [diff] [blame] | 888 | # Some heavily loaded buildbots (sparc Debian 3.x) require this much |
| 889 | # time to start. |
| 890 | self.assertEqual(p.wait(timeout=3), 0) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 891 | |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 892 | def test_invalid_bufsize(self): |
| 893 | # an invalid type of the bufsize argument should raise |
| 894 | # TypeError. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 895 | with self.assertRaises(TypeError): |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 896 | subprocess.Popen([sys.executable, "-c", "pass"], "orange") |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 897 | |
Guido van Rossum | 46a05a7 | 2007-06-07 21:56:45 +0000 | [diff] [blame] | 898 | def test_bufsize_is_none(self): |
| 899 | # bufsize=None should be the same as bufsize=0. |
| 900 | p = subprocess.Popen([sys.executable, "-c", "pass"], None) |
| 901 | self.assertEqual(p.wait(), 0) |
| 902 | # Again with keyword arg |
| 903 | p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None) |
| 904 | self.assertEqual(p.wait(), 0) |
| 905 | |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 906 | def test_leaking_fds_on_error(self): |
| 907 | # see bug #5179: Popen leaks file descriptors to PIPEs if |
| 908 | # the child fails to execute; this will eventually exhaust |
| 909 | # the maximum number of open fds. 1024 seems a very common |
| 910 | # value for that limit, but Windows has 2048, so we loop |
| 911 | # 1024 times (each call leaked two fds). |
| 912 | for i in range(1024): |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 913 | # Windows raises IOError. Others raise OSError. |
| 914 | with self.assertRaises(EnvironmentError) as c: |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 915 | subprocess.Popen(['nonexisting_i_hope'], |
| 916 | stdout=subprocess.PIPE, |
| 917 | stderr=subprocess.PIPE) |
R David Murray | 384069c | 2011-03-13 22:26:53 -0400 | [diff] [blame] | 918 | # ignore errors that indicate the command was not found |
R David Murray | 6924bd7 | 2011-03-13 22:48:55 -0400 | [diff] [blame] | 919 | if c.exception.errno not in (errno.ENOENT, errno.EACCES): |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 920 | raise c.exception |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 921 | |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 922 | def test_issue8780(self): |
| 923 | # Ensure that stdout is inherited from the parent |
| 924 | # if stdout=PIPE is not used |
| 925 | code = ';'.join(( |
| 926 | 'import subprocess, sys', |
| 927 | 'retcode = subprocess.call(' |
| 928 | "[sys.executable, '-c', 'print(\"Hello World!\")'])", |
| 929 | 'assert retcode == 0')) |
| 930 | output = subprocess.check_output([sys.executable, '-c', code]) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 931 | self.assertTrue(output.startswith(b'Hello World!'), ascii(output)) |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 932 | |
Tim Golden | af5ac39 | 2010-08-06 13:03:56 +0000 | [diff] [blame] | 933 | def test_handles_closed_on_exception(self): |
| 934 | # If CreateProcess exits with an error, ensure the |
| 935 | # duplicate output handles are released |
| 936 | ifhandle, ifname = mkstemp() |
| 937 | ofhandle, ofname = mkstemp() |
| 938 | efhandle, efname = mkstemp() |
| 939 | try: |
| 940 | subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle, |
| 941 | stderr=efhandle) |
| 942 | except OSError: |
| 943 | os.close(ifhandle) |
| 944 | os.remove(ifname) |
| 945 | os.close(ofhandle) |
| 946 | os.remove(ofname) |
| 947 | os.close(efhandle) |
| 948 | os.remove(efname) |
| 949 | self.assertFalse(os.path.exists(ifname)) |
| 950 | self.assertFalse(os.path.exists(ofname)) |
| 951 | self.assertFalse(os.path.exists(efname)) |
| 952 | |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 953 | def test_communicate_epipe(self): |
| 954 | # Issue 10963: communicate() should hide EPIPE |
| 955 | p = subprocess.Popen([sys.executable, "-c", 'pass'], |
| 956 | stdin=subprocess.PIPE, |
| 957 | stdout=subprocess.PIPE, |
| 958 | stderr=subprocess.PIPE) |
| 959 | self.addCleanup(p.stdout.close) |
| 960 | self.addCleanup(p.stderr.close) |
| 961 | self.addCleanup(p.stdin.close) |
| 962 | p.communicate(b"x" * 2**20) |
| 963 | |
| 964 | def test_communicate_epipe_only_stdin(self): |
| 965 | # Issue 10963: communicate() should hide EPIPE |
| 966 | p = subprocess.Popen([sys.executable, "-c", 'pass'], |
| 967 | stdin=subprocess.PIPE) |
| 968 | self.addCleanup(p.stdin.close) |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 969 | p.wait() |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 970 | p.communicate(b"x" * 2**20) |
| 971 | |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 972 | @unittest.skipUnless(hasattr(signal, 'SIGUSR1'), |
| 973 | "Requires signal.SIGUSR1") |
| 974 | @unittest.skipUnless(hasattr(os, 'kill'), |
| 975 | "Requires os.kill") |
| 976 | @unittest.skipUnless(hasattr(os, 'getppid'), |
| 977 | "Requires os.getppid") |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 978 | def test_communicate_eintr(self): |
| 979 | # Issue #12493: communicate() should handle EINTR |
| 980 | def handler(signum, frame): |
| 981 | pass |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 982 | old_handler = signal.signal(signal.SIGUSR1, handler) |
| 983 | self.addCleanup(signal.signal, signal.SIGUSR1, old_handler) |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 984 | |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 985 | args = [sys.executable, "-c", |
| 986 | 'import os, signal;' |
| 987 | 'os.kill(os.getppid(), signal.SIGUSR1)'] |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 988 | for stream in ('stdout', 'stderr'): |
| 989 | kw = {stream: subprocess.PIPE} |
| 990 | with subprocess.Popen(args, **kw) as process: |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 991 | # communicate() will be interrupted by SIGUSR1 |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 992 | process.communicate() |
| 993 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 994 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 995 | # context manager |
| 996 | class _SuppressCoreFiles(object): |
| 997 | """Try to prevent core files from being created.""" |
| 998 | old_limit = None |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 999 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1000 | def __enter__(self): |
| 1001 | """Try to save previous ulimit, then set it to (0, 0).""" |
Benjamin Peterson | 964561b | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 1002 | if resource is not None: |
| 1003 | try: |
| 1004 | self.old_limit = resource.getrlimit(resource.RLIMIT_CORE) |
| 1005 | resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) |
| 1006 | except (ValueError, resource.error): |
| 1007 | pass |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1008 | |
Ronald Oussoren | 102d11a | 2010-07-23 09:50:05 +0000 | [diff] [blame] | 1009 | if sys.platform == 'darwin': |
| 1010 | # Check if the 'Crash Reporter' on OSX was configured |
| 1011 | # in 'Developer' mode and warn that it will get triggered |
| 1012 | # when it is. |
| 1013 | # |
| 1014 | # This assumes that this context manager is used in tests |
| 1015 | # that might trigger the next manager. |
| 1016 | value = subprocess.Popen(['/usr/bin/defaults', 'read', |
| 1017 | 'com.apple.CrashReporter', 'DialogType'], |
| 1018 | stdout=subprocess.PIPE).communicate()[0] |
| 1019 | if value.strip() == b'developer': |
| 1020 | print("this tests triggers the Crash Reporter, " |
| 1021 | "that is intentional", end='') |
| 1022 | sys.stdout.flush() |
| 1023 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1024 | def __exit__(self, *args): |
| 1025 | """Return core file behavior to default.""" |
| 1026 | if self.old_limit is None: |
| 1027 | return |
Benjamin Peterson | 964561b | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 1028 | if resource is not None: |
| 1029 | try: |
| 1030 | resource.setrlimit(resource.RLIMIT_CORE, self.old_limit) |
| 1031 | except (ValueError, resource.error): |
| 1032 | pass |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1033 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1034 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1035 | @unittest.skipIf(mswindows, "POSIX specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1036 | class POSIXProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1037 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1038 | def test_exceptions(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1039 | nonexistent_dir = "/_this/pa.th/does/not/exist" |
| 1040 | try: |
| 1041 | os.chdir(nonexistent_dir) |
| 1042 | except OSError as e: |
| 1043 | # This avoids hard coding the errno value or the OS perror() |
| 1044 | # string and instead capture the exception that we want to see |
| 1045 | # below for comparison. |
| 1046 | desired_exception = e |
Benjamin Peterson | 5f78040 | 2010-11-20 18:07:52 +0000 | [diff] [blame] | 1047 | desired_exception.strerror += ': ' + repr(sys.executable) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1048 | else: |
| 1049 | self.fail("chdir to nonexistant directory %s succeeded." % |
| 1050 | nonexistent_dir) |
| 1051 | |
| 1052 | # Error in the child re-raised in the parent. |
| 1053 | try: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1054 | p = subprocess.Popen([sys.executable, "-c", ""], |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1055 | cwd=nonexistent_dir) |
| 1056 | except OSError as e: |
| 1057 | # Test that the child process chdir failure actually makes |
| 1058 | # it up to the parent process as the correct exception. |
| 1059 | self.assertEqual(desired_exception.errno, e.errno) |
| 1060 | self.assertEqual(desired_exception.strerror, e.strerror) |
| 1061 | else: |
| 1062 | self.fail("Expected OSError: %s" % desired_exception) |
| 1063 | |
| 1064 | def test_restore_signals(self): |
| 1065 | # Code coverage for both values of restore_signals to make sure it |
| 1066 | # at least does not blow up. |
| 1067 | # A test for behavior would be complex. Contributions welcome. |
| 1068 | subprocess.call([sys.executable, "-c", ""], restore_signals=True) |
| 1069 | subprocess.call([sys.executable, "-c", ""], restore_signals=False) |
| 1070 | |
| 1071 | def test_start_new_session(self): |
| 1072 | # For code coverage of calling setsid(). We don't care if we get an |
| 1073 | # EPERM error from it depending on the test execution environment, that |
| 1074 | # still indicates that it was called. |
| 1075 | try: |
| 1076 | output = subprocess.check_output( |
| 1077 | [sys.executable, "-c", |
| 1078 | "import os; print(os.getpgid(os.getpid()))"], |
| 1079 | start_new_session=True) |
| 1080 | except OSError as e: |
| 1081 | if e.errno != errno.EPERM: |
| 1082 | raise |
| 1083 | else: |
| 1084 | parent_pgid = os.getpgid(os.getpid()) |
| 1085 | child_pgid = int(output) |
| 1086 | self.assertNotEqual(parent_pgid, child_pgid) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1087 | |
| 1088 | def test_run_abort(self): |
| 1089 | # returncode handles signal termination |
| 1090 | with _SuppressCoreFiles(): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1091 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1092 | 'import os; os.abort()']) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1093 | p.wait() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1094 | self.assertEqual(-p.returncode, signal.SIGABRT) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1095 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1096 | def test_preexec(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1097 | # DISCLAIMER: Setting environment variables is *not* a good use |
| 1098 | # of a preexec_fn. This is merely a test. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1099 | p = subprocess.Popen([sys.executable, "-c", |
| 1100 | 'import sys,os;' |
| 1101 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 1102 | stdout=subprocess.PIPE, |
| 1103 | preexec_fn=lambda: os.putenv("FRUIT", "apple")) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 1104 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1105 | self.assertEqual(p.stdout.read(), b"apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1106 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1107 | def test_preexec_exception(self): |
| 1108 | def raise_it(): |
| 1109 | raise ValueError("What if two swallows carried a coconut?") |
| 1110 | try: |
| 1111 | p = subprocess.Popen([sys.executable, "-c", ""], |
| 1112 | preexec_fn=raise_it) |
| 1113 | except RuntimeError as e: |
| 1114 | self.assertTrue( |
| 1115 | subprocess._posixsubprocess, |
| 1116 | "Expected a ValueError from the preexec_fn") |
| 1117 | except ValueError as e: |
| 1118 | self.assertIn("coconut", e.args[0]) |
| 1119 | else: |
| 1120 | self.fail("Exception raised by preexec_fn did not make it " |
| 1121 | "to the parent process.") |
| 1122 | |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 1123 | def test_preexec_gc_module_failure(self): |
| 1124 | # This tests the code that disables garbage collection if the child |
| 1125 | # process will execute any Python. |
| 1126 | def raise_runtime_error(): |
| 1127 | raise RuntimeError("this shouldn't escape") |
| 1128 | enabled = gc.isenabled() |
| 1129 | orig_gc_disable = gc.disable |
| 1130 | orig_gc_isenabled = gc.isenabled |
| 1131 | try: |
| 1132 | gc.disable() |
| 1133 | self.assertFalse(gc.isenabled()) |
| 1134 | subprocess.call([sys.executable, '-c', ''], |
| 1135 | preexec_fn=lambda: None) |
| 1136 | self.assertFalse(gc.isenabled(), |
| 1137 | "Popen enabled gc when it shouldn't.") |
| 1138 | |
| 1139 | gc.enable() |
| 1140 | self.assertTrue(gc.isenabled()) |
| 1141 | subprocess.call([sys.executable, '-c', ''], |
| 1142 | preexec_fn=lambda: None) |
| 1143 | self.assertTrue(gc.isenabled(), "Popen left gc disabled.") |
| 1144 | |
| 1145 | gc.disable = raise_runtime_error |
| 1146 | self.assertRaises(RuntimeError, subprocess.Popen, |
| 1147 | [sys.executable, '-c', ''], |
| 1148 | preexec_fn=lambda: None) |
| 1149 | |
| 1150 | del gc.isenabled # force an AttributeError |
| 1151 | self.assertRaises(AttributeError, subprocess.Popen, |
| 1152 | [sys.executable, '-c', ''], |
| 1153 | preexec_fn=lambda: None) |
| 1154 | finally: |
| 1155 | gc.disable = orig_gc_disable |
| 1156 | gc.isenabled = orig_gc_isenabled |
| 1157 | if not enabled: |
| 1158 | gc.disable() |
| 1159 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1160 | def test_args_string(self): |
| 1161 | # args is a string |
| 1162 | fd, fname = mkstemp() |
| 1163 | # reopen in text mode |
Victor Stinner | f6782ac | 2010-10-16 23:46:43 +0000 | [diff] [blame] | 1164 | with open(fd, "w", errors="surrogateescape") as fobj: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1165 | fobj.write("#!/bin/sh\n") |
| 1166 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 1167 | sys.executable) |
| 1168 | os.chmod(fname, 0o700) |
| 1169 | p = subprocess.Popen(fname) |
| 1170 | p.wait() |
| 1171 | os.remove(fname) |
| 1172 | self.assertEqual(p.returncode, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1173 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1174 | def test_invalid_args(self): |
| 1175 | # invalid arguments should raise ValueError |
| 1176 | self.assertRaises(ValueError, subprocess.call, |
| 1177 | [sys.executable, "-c", |
| 1178 | "import sys; sys.exit(47)"], |
| 1179 | startupinfo=47) |
| 1180 | self.assertRaises(ValueError, subprocess.call, |
| 1181 | [sys.executable, "-c", |
| 1182 | "import sys; sys.exit(47)"], |
| 1183 | creationflags=47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1184 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1185 | def test_shell_sequence(self): |
| 1186 | # Run command through the shell (sequence) |
| 1187 | newenv = os.environ.copy() |
| 1188 | newenv["FRUIT"] = "apple" |
| 1189 | p = subprocess.Popen(["echo $FRUIT"], shell=1, |
| 1190 | stdout=subprocess.PIPE, |
| 1191 | env=newenv) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 1192 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1193 | 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] | 1194 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1195 | def test_shell_string(self): |
| 1196 | # Run command through the shell (string) |
| 1197 | newenv = os.environ.copy() |
| 1198 | newenv["FRUIT"] = "apple" |
| 1199 | p = subprocess.Popen("echo $FRUIT", shell=1, |
| 1200 | stdout=subprocess.PIPE, |
| 1201 | env=newenv) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 1202 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1203 | 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] | 1204 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1205 | def test_call_string(self): |
| 1206 | # call() function with string argument on UNIX |
| 1207 | fd, fname = mkstemp() |
| 1208 | # reopen in text mode |
Victor Stinner | f6782ac | 2010-10-16 23:46:43 +0000 | [diff] [blame] | 1209 | with open(fd, "w", errors="surrogateescape") as fobj: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1210 | fobj.write("#!/bin/sh\n") |
| 1211 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 1212 | sys.executable) |
| 1213 | os.chmod(fname, 0o700) |
| 1214 | rc = subprocess.call(fname) |
| 1215 | os.remove(fname) |
| 1216 | self.assertEqual(rc, 47) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1217 | |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 1218 | def test_specific_shell(self): |
| 1219 | # Issue #9265: Incorrect name passed as arg[0]. |
| 1220 | shells = [] |
| 1221 | for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']: |
| 1222 | for name in ['bash', 'ksh']: |
| 1223 | sh = os.path.join(prefix, name) |
| 1224 | if os.path.isfile(sh): |
| 1225 | shells.append(sh) |
| 1226 | if not shells: # Will probably work for any shell but csh. |
| 1227 | self.skipTest("bash or ksh required for this test") |
| 1228 | sh = '/bin/sh' |
| 1229 | if os.path.isfile(sh) and not os.path.islink(sh): |
| 1230 | # Test will fail if /bin/sh is a symlink to csh. |
| 1231 | shells.append(sh) |
| 1232 | for sh in shells: |
| 1233 | p = subprocess.Popen("echo $0", executable=sh, shell=True, |
| 1234 | stdout=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 1235 | self.addCleanup(p.stdout.close) |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 1236 | self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii')) |
| 1237 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1238 | def _kill_process(self, method, *args): |
Florent Xicluna | 1d8ee3a | 2010-03-05 20:26:54 +0000 | [diff] [blame] | 1239 | # Do not inherit file handles from the parent. |
| 1240 | # It should fix failures on some platforms. |
Antoine Pitrou | 3d8580f | 2010-09-20 01:33:21 +0000 | [diff] [blame] | 1241 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1242 | import sys, time |
| 1243 | sys.stdout.write('x\\n') |
| 1244 | sys.stdout.flush() |
| 1245 | time.sleep(30) |
| 1246 | """], |
| 1247 | close_fds=True, |
| 1248 | stdin=subprocess.PIPE, |
| 1249 | stdout=subprocess.PIPE, |
| 1250 | stderr=subprocess.PIPE) |
| 1251 | # Wait for the interpreter to be completely initialized before |
| 1252 | # sending any signal. |
| 1253 | p.stdout.read(1) |
| 1254 | getattr(p, method)(*args) |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1255 | return p |
| 1256 | |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1257 | def _kill_dead_process(self, method, *args): |
| 1258 | # Do not inherit file handles from the parent. |
| 1259 | # It should fix failures on some platforms. |
| 1260 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1261 | import sys, time |
| 1262 | sys.stdout.write('x\\n') |
| 1263 | sys.stdout.flush() |
| 1264 | """], |
| 1265 | close_fds=True, |
| 1266 | stdin=subprocess.PIPE, |
| 1267 | stdout=subprocess.PIPE, |
| 1268 | stderr=subprocess.PIPE) |
| 1269 | # Wait for the interpreter to be completely initialized before |
| 1270 | # sending any signal. |
| 1271 | p.stdout.read(1) |
| 1272 | # The process should end after this |
| 1273 | time.sleep(1) |
| 1274 | # This shouldn't raise even though the child is now dead |
| 1275 | getattr(p, method)(*args) |
| 1276 | p.communicate() |
| 1277 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1278 | def test_send_signal(self): |
| 1279 | p = self._kill_process('send_signal', signal.SIGINT) |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1280 | _, stderr = p.communicate() |
| 1281 | self.assertIn(b'KeyboardInterrupt', stderr) |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1282 | self.assertNotEqual(p.wait(), 0) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1283 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1284 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1285 | p = self._kill_process('kill') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1286 | _, stderr = p.communicate() |
| 1287 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1288 | self.assertEqual(p.wait(), -signal.SIGKILL) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1289 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1290 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1291 | p = self._kill_process('terminate') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1292 | _, stderr = p.communicate() |
| 1293 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1294 | self.assertEqual(p.wait(), -signal.SIGTERM) |
| 1295 | |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1296 | def test_send_signal_dead(self): |
| 1297 | # Sending a signal to a dead process |
| 1298 | self._kill_dead_process('send_signal', signal.SIGINT) |
| 1299 | |
| 1300 | def test_kill_dead(self): |
| 1301 | # Killing a dead process |
| 1302 | self._kill_dead_process('kill') |
| 1303 | |
| 1304 | def test_terminate_dead(self): |
| 1305 | # Terminating a dead process |
| 1306 | self._kill_dead_process('terminate') |
| 1307 | |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 1308 | def check_close_std_fds(self, fds): |
| 1309 | # Issue #9905: test that subprocess pipes still work properly with |
| 1310 | # some standard fds closed |
| 1311 | stdin = 0 |
| 1312 | newfds = [] |
| 1313 | for a in fds: |
| 1314 | b = os.dup(a) |
| 1315 | newfds.append(b) |
| 1316 | if a == 0: |
| 1317 | stdin = b |
| 1318 | try: |
| 1319 | for fd in fds: |
| 1320 | os.close(fd) |
| 1321 | out, err = subprocess.Popen([sys.executable, "-c", |
| 1322 | 'import sys;' |
| 1323 | 'sys.stdout.write("apple");' |
| 1324 | 'sys.stdout.flush();' |
| 1325 | 'sys.stderr.write("orange")'], |
| 1326 | stdin=stdin, |
| 1327 | stdout=subprocess.PIPE, |
| 1328 | stderr=subprocess.PIPE).communicate() |
| 1329 | err = support.strip_python_stderr(err) |
| 1330 | self.assertEqual((out, err), (b'apple', b'orange')) |
| 1331 | finally: |
| 1332 | for b, a in zip(newfds, fds): |
| 1333 | os.dup2(b, a) |
| 1334 | for b in newfds: |
| 1335 | os.close(b) |
| 1336 | |
| 1337 | def test_close_fd_0(self): |
| 1338 | self.check_close_std_fds([0]) |
| 1339 | |
| 1340 | def test_close_fd_1(self): |
| 1341 | self.check_close_std_fds([1]) |
| 1342 | |
| 1343 | def test_close_fd_2(self): |
| 1344 | self.check_close_std_fds([2]) |
| 1345 | |
| 1346 | def test_close_fds_0_1(self): |
| 1347 | self.check_close_std_fds([0, 1]) |
| 1348 | |
| 1349 | def test_close_fds_0_2(self): |
| 1350 | self.check_close_std_fds([0, 2]) |
| 1351 | |
| 1352 | def test_close_fds_1_2(self): |
| 1353 | self.check_close_std_fds([1, 2]) |
| 1354 | |
| 1355 | def test_close_fds_0_1_2(self): |
| 1356 | # Issue #10806: test that subprocess pipes still work properly with |
| 1357 | # all standard fds closed. |
| 1358 | self.check_close_std_fds([0, 1, 2]) |
| 1359 | |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 1360 | def test_remapping_std_fds(self): |
| 1361 | # open up some temporary files |
| 1362 | temps = [mkstemp() for i in range(3)] |
| 1363 | try: |
| 1364 | temp_fds = [fd for fd, fname in temps] |
| 1365 | |
| 1366 | # unlink the files -- we won't need to reopen them |
| 1367 | for fd, fname in temps: |
| 1368 | os.unlink(fname) |
| 1369 | |
| 1370 | # write some data to what will become stdin, and rewind |
| 1371 | os.write(temp_fds[1], b"STDIN") |
| 1372 | os.lseek(temp_fds[1], 0, 0) |
| 1373 | |
| 1374 | # move the standard file descriptors out of the way |
| 1375 | saved_fds = [os.dup(fd) for fd in range(3)] |
| 1376 | try: |
| 1377 | # duplicate the file objects over the standard fd's |
| 1378 | for fd, temp_fd in enumerate(temp_fds): |
| 1379 | os.dup2(temp_fd, fd) |
| 1380 | |
| 1381 | # now use those files in the "wrong" order, so that subprocess |
| 1382 | # has to rearrange them in the child |
| 1383 | p = subprocess.Popen([sys.executable, "-c", |
| 1384 | 'import sys; got = sys.stdin.read();' |
| 1385 | 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'], |
| 1386 | stdin=temp_fds[1], |
| 1387 | stdout=temp_fds[2], |
| 1388 | stderr=temp_fds[0]) |
| 1389 | p.wait() |
| 1390 | finally: |
| 1391 | # restore the original fd's underneath sys.stdin, etc. |
| 1392 | for std, saved in enumerate(saved_fds): |
| 1393 | os.dup2(saved, std) |
| 1394 | os.close(saved) |
| 1395 | |
| 1396 | for fd in temp_fds: |
| 1397 | os.lseek(fd, 0, 0) |
| 1398 | |
| 1399 | out = os.read(temp_fds[2], 1024) |
| 1400 | err = support.strip_python_stderr(os.read(temp_fds[0], 1024)) |
| 1401 | self.assertEqual(out, b"got STDIN") |
| 1402 | self.assertEqual(err, b"err") |
| 1403 | |
| 1404 | finally: |
| 1405 | for fd in temp_fds: |
| 1406 | os.close(fd) |
| 1407 | |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 1408 | def check_swap_fds(self, stdin_no, stdout_no, stderr_no): |
| 1409 | # open up some temporary files |
| 1410 | temps = [mkstemp() for i in range(3)] |
| 1411 | temp_fds = [fd for fd, fname in temps] |
| 1412 | try: |
| 1413 | # unlink the files -- we won't need to reopen them |
| 1414 | for fd, fname in temps: |
| 1415 | os.unlink(fname) |
| 1416 | |
| 1417 | # save a copy of the standard file descriptors |
| 1418 | saved_fds = [os.dup(fd) for fd in range(3)] |
| 1419 | try: |
| 1420 | # duplicate the temp files over the standard fd's 0, 1, 2 |
| 1421 | for fd, temp_fd in enumerate(temp_fds): |
| 1422 | os.dup2(temp_fd, fd) |
| 1423 | |
| 1424 | # write some data to what will become stdin, and rewind |
| 1425 | os.write(stdin_no, b"STDIN") |
| 1426 | os.lseek(stdin_no, 0, 0) |
| 1427 | |
| 1428 | # now use those files in the given order, so that subprocess |
| 1429 | # has to rearrange them in the child |
| 1430 | p = subprocess.Popen([sys.executable, "-c", |
| 1431 | 'import sys; got = sys.stdin.read();' |
| 1432 | 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'], |
| 1433 | stdin=stdin_no, |
| 1434 | stdout=stdout_no, |
| 1435 | stderr=stderr_no) |
| 1436 | p.wait() |
| 1437 | |
| 1438 | for fd in temp_fds: |
| 1439 | os.lseek(fd, 0, 0) |
| 1440 | |
| 1441 | out = os.read(stdout_no, 1024) |
| 1442 | err = support.strip_python_stderr(os.read(stderr_no, 1024)) |
| 1443 | finally: |
| 1444 | for std, saved in enumerate(saved_fds): |
| 1445 | os.dup2(saved, std) |
| 1446 | os.close(saved) |
| 1447 | |
| 1448 | self.assertEqual(out, b"got STDIN") |
| 1449 | self.assertEqual(err, b"err") |
| 1450 | |
| 1451 | finally: |
| 1452 | for fd in temp_fds: |
| 1453 | os.close(fd) |
| 1454 | |
| 1455 | # When duping fds, if there arises a situation where one of the fds is |
| 1456 | # either 0, 1 or 2, it is possible that it is overwritten (#12607). |
| 1457 | # This tests all combinations of this. |
| 1458 | def test_swap_fds(self): |
| 1459 | self.check_swap_fds(0, 1, 2) |
| 1460 | self.check_swap_fds(0, 2, 1) |
| 1461 | self.check_swap_fds(1, 0, 2) |
| 1462 | self.check_swap_fds(1, 2, 0) |
| 1463 | self.check_swap_fds(2, 0, 1) |
| 1464 | self.check_swap_fds(2, 1, 0) |
| 1465 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1466 | def test_surrogates_error_message(self): |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 1467 | def prepare(): |
| 1468 | raise ValueError("surrogate:\uDCff") |
| 1469 | |
| 1470 | try: |
| 1471 | subprocess.call( |
| 1472 | [sys.executable, "-c", "pass"], |
| 1473 | preexec_fn=prepare) |
| 1474 | except ValueError as err: |
| 1475 | # Pure Python implementations keeps the message |
| 1476 | self.assertIsNone(subprocess._posixsubprocess) |
| 1477 | self.assertEqual(str(err), "surrogate:\uDCff") |
| 1478 | except RuntimeError as err: |
| 1479 | # _posixsubprocess uses a default message |
| 1480 | self.assertIsNotNone(subprocess._posixsubprocess) |
| 1481 | self.assertEqual(str(err), "Exception occurred in preexec_fn.") |
| 1482 | else: |
| 1483 | self.fail("Expected ValueError or RuntimeError") |
| 1484 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1485 | def test_undecodable_env(self): |
| 1486 | for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')): |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1487 | # test str with surrogates |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 1488 | script = "import os; print(ascii(os.getenv(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1489 | env = os.environ.copy() |
| 1490 | env[key] = value |
Victor Stinner | 89f3ad1 | 2010-10-14 10:43:31 +0000 | [diff] [blame] | 1491 | # Use C locale to get ascii for the locale encoding to force |
| 1492 | # surrogate-escaping of \xFF in the child process; otherwise it can |
| 1493 | # be decoded as-is if the default locale is latin-1. |
Victor Stinner | ebc78d2 | 2010-10-14 10:38:17 +0000 | [diff] [blame] | 1494 | env['LC_ALL'] = 'C' |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1495 | stdout = subprocess.check_output( |
| 1496 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1497 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1498 | stdout = stdout.rstrip(b'\n\r') |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1499 | self.assertEqual(stdout.decode('ascii'), ascii(value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1500 | |
| 1501 | # test bytes |
| 1502 | key = key.encode("ascii", "surrogateescape") |
| 1503 | value = value.encode("ascii", "surrogateescape") |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 1504 | script = "import os; print(ascii(os.getenvb(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1505 | env = os.environ.copy() |
| 1506 | env[key] = value |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1507 | stdout = subprocess.check_output( |
| 1508 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1509 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1510 | stdout = stdout.rstrip(b'\n\r') |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1511 | self.assertEqual(stdout.decode('ascii'), ascii(value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1512 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1513 | def test_bytes_program(self): |
| 1514 | abs_program = os.fsencode(sys.executable) |
| 1515 | path, program = os.path.split(sys.executable) |
| 1516 | program = os.fsencode(program) |
| 1517 | |
| 1518 | # absolute bytes path |
| 1519 | exitcode = subprocess.call([abs_program, "-c", "pass"]) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1520 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1521 | |
Victor Stinner | 7b3b20a | 2011-03-03 12:54:05 +0000 | [diff] [blame] | 1522 | # absolute bytes path as a string |
| 1523 | cmd = b"'" + abs_program + b"' -c pass" |
| 1524 | exitcode = subprocess.call(cmd, shell=True) |
| 1525 | self.assertEqual(exitcode, 0) |
| 1526 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 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 | 112bb3a | 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" % |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 1710 | stderr.decode('utf-8')) |
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 | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 1957 | class HelperFunctionTests(unittest.TestCase): |
Gregory P. Smith | af6d3b8 | 2010-03-01 02:56:44 +0000 | [diff] [blame] | 1958 | @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows") |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 1959 | def test_eintr_retry_call(self): |
| 1960 | record_calls = [] |
| 1961 | def fake_os_func(*args): |
| 1962 | record_calls.append(args) |
| 1963 | if len(record_calls) == 2: |
| 1964 | raise OSError(errno.EINTR, "fake interrupted system call") |
| 1965 | return tuple(reversed(args)) |
| 1966 | |
| 1967 | self.assertEqual((999, 256), |
| 1968 | subprocess._eintr_retry_call(fake_os_func, 256, 999)) |
| 1969 | self.assertEqual([(256, 999)], record_calls) |
| 1970 | # This time there will be an EINTR so it will loop once. |
| 1971 | self.assertEqual((666,), |
| 1972 | subprocess._eintr_retry_call(fake_os_func, 666)) |
| 1973 | self.assertEqual([(256, 999), (666,), (666,)], record_calls) |
| 1974 | |
| 1975 | |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 1976 | @unittest.skipUnless(mswindows, "Windows-specific tests") |
| 1977 | class CommandsWithSpaces (BaseTestCase): |
| 1978 | |
| 1979 | def setUp(self): |
| 1980 | super().setUp() |
| 1981 | f, fname = mkstemp(".py", "te st") |
| 1982 | self.fname = fname.lower () |
| 1983 | os.write(f, b"import sys;" |
| 1984 | b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))" |
| 1985 | ) |
| 1986 | os.close(f) |
| 1987 | |
| 1988 | def tearDown(self): |
| 1989 | os.remove(self.fname) |
| 1990 | super().tearDown() |
| 1991 | |
| 1992 | def with_spaces(self, *args, **kwargs): |
| 1993 | kwargs['stdout'] = subprocess.PIPE |
| 1994 | p = subprocess.Popen(*args, **kwargs) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 1995 | self.addCleanup(p.stdout.close) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 1996 | self.assertEqual( |
| 1997 | p.stdout.read ().decode("mbcs"), |
| 1998 | "2 [%r, 'ab cd']" % self.fname |
| 1999 | ) |
| 2000 | |
| 2001 | def test_shell_string_with_spaces(self): |
| 2002 | # call() function with string argument with spaces on Windows |
Brian Curtin | d835cf1 | 2010-08-13 20:42:57 +0000 | [diff] [blame] | 2003 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 2004 | "ab cd"), shell=1) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 2005 | |
| 2006 | def test_shell_sequence_with_spaces(self): |
| 2007 | # call() function with sequence argument with spaces on Windows |
Brian Curtin | d835cf1 | 2010-08-13 20:42:57 +0000 | [diff] [blame] | 2008 | self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 2009 | |
| 2010 | def test_noshell_string_with_spaces(self): |
| 2011 | # call() function with string argument with spaces on Windows |
| 2012 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 2013 | "ab cd")) |
| 2014 | |
| 2015 | def test_noshell_sequence_with_spaces(self): |
| 2016 | # call() function with sequence argument with spaces on Windows |
| 2017 | self.with_spaces([sys.executable, self.fname, "ab cd"]) |
| 2018 | |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2019 | |
Georg Brandl | a86b262 | 2012-02-20 21:34:57 +0100 | [diff] [blame] | 2020 | class ContextManagerTests(BaseTestCase): |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2021 | |
| 2022 | def test_pipe(self): |
| 2023 | with subprocess.Popen([sys.executable, "-c", |
| 2024 | "import sys;" |
| 2025 | "sys.stdout.write('stdout');" |
| 2026 | "sys.stderr.write('stderr');"], |
| 2027 | stdout=subprocess.PIPE, |
| 2028 | stderr=subprocess.PIPE) as proc: |
| 2029 | self.assertEqual(proc.stdout.read(), b"stdout") |
| 2030 | self.assertStderrEqual(proc.stderr.read(), b"stderr") |
| 2031 | |
| 2032 | self.assertTrue(proc.stdout.closed) |
| 2033 | self.assertTrue(proc.stderr.closed) |
| 2034 | |
| 2035 | def test_returncode(self): |
| 2036 | with subprocess.Popen([sys.executable, "-c", |
| 2037 | "import sys; sys.exit(100)"]) as proc: |
Gregory P. Smith | 6b65745 | 2011-05-11 21:42:08 -0700 | [diff] [blame] | 2038 | pass |
| 2039 | # __exit__ calls wait(), so the returncode should be set |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2040 | self.assertEqual(proc.returncode, 100) |
| 2041 | |
| 2042 | def test_communicate_stdin(self): |
| 2043 | with subprocess.Popen([sys.executable, "-c", |
| 2044 | "import sys;" |
| 2045 | "sys.exit(sys.stdin.read() == 'context')"], |
| 2046 | stdin=subprocess.PIPE) as proc: |
| 2047 | proc.communicate(b"context") |
| 2048 | self.assertEqual(proc.returncode, 1) |
| 2049 | |
| 2050 | def test_invalid_args(self): |
| 2051 | with self.assertRaises(EnvironmentError) as c: |
| 2052 | with subprocess.Popen(['nonexisting_i_hope'], |
| 2053 | stdout=subprocess.PIPE, |
| 2054 | stderr=subprocess.PIPE) as proc: |
| 2055 | pass |
| 2056 | |
| 2057 | if c.exception.errno != errno.ENOENT: # ignore "no such file" |
| 2058 | raise c.exception |
| 2059 | |
| 2060 | |
Gregory P. Smith | 3b4652e | 2011-03-15 15:43:39 -0400 | [diff] [blame] | 2061 | def test_main(): |
| 2062 | unit_tests = (ProcessTestCase, |
| 2063 | POSIXProcessTestCase, |
| 2064 | Win32ProcessTestCase, |
Gregory P. Smith | 3b4652e | 2011-03-15 15:43:39 -0400 | [diff] [blame] | 2065 | CommandTests, |
| 2066 | ProcessTestCaseNoPoll, |
| 2067 | HelperFunctionTests, |
| 2068 | CommandsWithSpaces, |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 2069 | ContextManagerTests, |
| 2070 | ) |
Gregory P. Smith | 3b4652e | 2011-03-15 15:43:39 -0400 | [diff] [blame] | 2071 | |
| 2072 | support.run_unittest(*unit_tests) |
| 2073 | support.reap_children() |
| 2074 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2075 | if __name__ == "__main__": |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 2076 | unittest.main() |