Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1 | import unittest |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 2 | from test import support |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 3 | import subprocess |
| 4 | import sys |
| 5 | import signal |
Gregory P. Smith | e14e9c2 | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 6 | import io |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 7 | import os |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 8 | import errno |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 9 | import tempfile |
| 10 | import time |
Tim Peters | 3761e8d | 2004-10-13 04:07:12 +0000 | [diff] [blame] | 11 | import re |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 12 | import sysconfig |
Gregory P. Smith | d23047b | 2010-12-04 09:10:44 +0000 | [diff] [blame] | 13 | import warnings |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 14 | import select |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 15 | import shutil |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 16 | try: |
| 17 | import gc |
| 18 | except ImportError: |
| 19 | gc = None |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 20 | |
| 21 | mswindows = (sys.platform == "win32") |
| 22 | |
| 23 | # |
| 24 | # Depends on the following external programs: Python |
| 25 | # |
| 26 | |
| 27 | if mswindows: |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 28 | SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), ' |
| 29 | 'os.O_BINARY);') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 30 | else: |
| 31 | SETBINARY = '' |
| 32 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 33 | |
| 34 | try: |
| 35 | mkstemp = tempfile.mkstemp |
| 36 | except AttributeError: |
| 37 | # tempfile.mkstemp is not available |
| 38 | def mkstemp(): |
| 39 | """Replacement for mkstemp, calling mktemp.""" |
| 40 | fname = tempfile.mktemp() |
| 41 | return os.open(fname, os.O_RDWR|os.O_CREAT), fname |
| 42 | |
Tim Peters | 3761e8d | 2004-10-13 04:07:12 +0000 | [diff] [blame] | 43 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 44 | class BaseTestCase(unittest.TestCase): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 45 | def setUp(self): |
| 46 | # Try to minimize the number of children we have so this test |
| 47 | # doesn't crash on some buildbots (Alphas in particular). |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 48 | support.reap_children() |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 49 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 50 | def tearDown(self): |
| 51 | for inst in subprocess._active: |
| 52 | inst.wait() |
| 53 | subprocess._cleanup() |
| 54 | self.assertFalse(subprocess._active, "subprocess._active not empty") |
| 55 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 56 | def assertStderrEqual(self, stderr, expected, msg=None): |
| 57 | # In a debug build, stuff like "[6580 refs]" is printed to stderr at |
| 58 | # shutdown time. That frustrates tests trying to check stderr produced |
| 59 | # from a spawned Python process. |
Antoine Pitrou | 62f68ed | 2010-08-04 11:48:56 +0000 | [diff] [blame] | 60 | actual = support.strip_python_stderr(stderr) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 61 | self.assertEqual(actual, expected, msg) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 62 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 63 | |
| 64 | class ProcessTestCase(BaseTestCase): |
| 65 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 66 | def test_call_seq(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 67 | # call() function with sequence argument |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 68 | rc = subprocess.call([sys.executable, "-c", |
| 69 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 70 | self.assertEqual(rc, 47) |
| 71 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 72 | def test_check_call_zero(self): |
| 73 | # check_call() function with zero return code |
| 74 | rc = subprocess.check_call([sys.executable, "-c", |
| 75 | "import sys; sys.exit(0)"]) |
| 76 | self.assertEqual(rc, 0) |
| 77 | |
| 78 | def test_check_call_nonzero(self): |
| 79 | # check_call() function with non-zero return code |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 80 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 81 | subprocess.check_call([sys.executable, "-c", |
| 82 | "import sys; sys.exit(47)"]) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 83 | self.assertEqual(c.exception.returncode, 47) |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 84 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 85 | def test_check_output(self): |
| 86 | # check_output() function with zero return code |
| 87 | output = subprocess.check_output( |
| 88 | [sys.executable, "-c", "print('BDFL')"]) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 89 | self.assertIn(b'BDFL', output) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 90 | |
| 91 | def test_check_output_nonzero(self): |
| 92 | # check_call() function with non-zero return code |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 93 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 94 | subprocess.check_output( |
| 95 | [sys.executable, "-c", "import sys; sys.exit(5)"]) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 96 | self.assertEqual(c.exception.returncode, 5) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 97 | |
| 98 | def test_check_output_stderr(self): |
| 99 | # check_output() function stderr redirected to stdout |
| 100 | output = subprocess.check_output( |
| 101 | [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"], |
| 102 | stderr=subprocess.STDOUT) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 103 | self.assertIn(b'BDFL', output) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 104 | |
| 105 | def test_check_output_stdout_arg(self): |
| 106 | # check_output() function stderr redirected to stdout |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 107 | with self.assertRaises(ValueError) as c: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 108 | output = subprocess.check_output( |
| 109 | [sys.executable, "-c", "print('will not be run')"], |
| 110 | stdout=sys.stdout) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 111 | self.fail("Expected ValueError when stdout arg supplied.") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 112 | self.assertIn('stdout', c.exception.args[0]) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 113 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 114 | def test_call_kwargs(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 115 | # call() function with keyword args |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 116 | newenv = os.environ.copy() |
| 117 | newenv["FRUIT"] = "banana" |
| 118 | rc = subprocess.call([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 119 | 'import sys, os;' |
| 120 | 'sys.exit(os.getenv("FRUIT")=="banana")'], |
| 121 | env=newenv) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 122 | self.assertEqual(rc, 1) |
| 123 | |
Victor Stinner | 87b9bc3 | 2011-06-01 00:57:47 +0200 | [diff] [blame] | 124 | def test_invalid_args(self): |
| 125 | # Popen() called with invalid arguments should raise TypeError |
| 126 | # but Popen.__del__ should not complain (issue #12085) |
| 127 | with support.captured_stderr() as s: |
| 128 | self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1) |
| 129 | argcount = subprocess.Popen.__init__.__code__.co_argcount |
| 130 | too_many_args = [0] * (argcount + 1) |
| 131 | self.assertRaises(TypeError, subprocess.Popen, *too_many_args) |
| 132 | self.assertEqual(s.getvalue(), '') |
| 133 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 134 | def test_stdin_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 135 | # .stdin is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 136 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 137 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 138 | self.addCleanup(p.stdout.close) |
| 139 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 140 | p.wait() |
| 141 | self.assertEqual(p.stdin, None) |
| 142 | |
| 143 | def test_stdout_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 144 | # .stdout is None when not redirected |
Tim Peters | 29b6b4f | 2004-10-13 03:43:40 +0000 | [diff] [blame] | 145 | p = subprocess.Popen([sys.executable, "-c", |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 146 | 'print(" this bit of output is from a ' |
Tim Peters | 4052fe5 | 2004-10-13 03:29:54 +0000 | [diff] [blame] | 147 | 'test of stdout in a different ' |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 148 | 'process ...")'], |
Tim Peters | 4052fe5 | 2004-10-13 03:29:54 +0000 | [diff] [blame] | 149 | stdin=subprocess.PIPE, stderr=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 150 | self.addCleanup(p.stdin.close) |
| 151 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 152 | p.wait() |
| 153 | self.assertEqual(p.stdout, None) |
| 154 | |
| 155 | def test_stderr_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 156 | # .stderr is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 157 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 158 | stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 159 | self.addCleanup(p.stdout.close) |
| 160 | self.addCleanup(p.stdin.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 161 | p.wait() |
| 162 | self.assertEqual(p.stderr, None) |
| 163 | |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 164 | def test_executable_with_cwd(self): |
Florent Xicluna | 1d1ab97 | 2010-03-11 01:53:10 +0000 | [diff] [blame] | 165 | python_dir = os.path.dirname(os.path.realpath(sys.executable)) |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 166 | p = subprocess.Popen(["somethingyoudonthave", "-c", |
| 167 | "import sys; sys.exit(47)"], |
| 168 | executable=sys.executable, cwd=python_dir) |
| 169 | p.wait() |
| 170 | self.assertEqual(p.returncode, 47) |
| 171 | |
| 172 | @unittest.skipIf(sysconfig.is_python_build(), |
| 173 | "need an installed Python. See #7774") |
| 174 | def test_executable_without_cwd(self): |
| 175 | # For a normal installation, it should work without 'cwd' |
| 176 | # argument. For test runs in the build directory, see #7774. |
| 177 | p = subprocess.Popen(["somethingyoudonthave", "-c", |
| 178 | "import sys; sys.exit(47)"], |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 179 | executable=sys.executable) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 180 | p.wait() |
| 181 | self.assertEqual(p.returncode, 47) |
| 182 | |
| 183 | def test_stdin_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 184 | # stdin redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 185 | p = subprocess.Popen([sys.executable, "-c", |
| 186 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 187 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 188 | p.stdin.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 189 | p.stdin.close() |
| 190 | p.wait() |
| 191 | self.assertEqual(p.returncode, 1) |
| 192 | |
| 193 | def test_stdin_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 194 | # stdin is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 195 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 196 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 197 | d = tf.fileno() |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 198 | os.write(d, b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 199 | os.lseek(d, 0, 0) |
| 200 | p = subprocess.Popen([sys.executable, "-c", |
| 201 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 202 | stdin=d) |
| 203 | p.wait() |
| 204 | self.assertEqual(p.returncode, 1) |
| 205 | |
| 206 | def test_stdin_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 207 | # stdin is set to open file object |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 208 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 209 | self.addCleanup(tf.close) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 210 | tf.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 211 | tf.seek(0) |
| 212 | p = subprocess.Popen([sys.executable, "-c", |
| 213 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 214 | stdin=tf) |
| 215 | p.wait() |
| 216 | self.assertEqual(p.returncode, 1) |
| 217 | |
| 218 | def test_stdout_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 219 | # stdout redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 220 | p = subprocess.Popen([sys.executable, "-c", |
| 221 | 'import sys; sys.stdout.write("orange")'], |
| 222 | stdout=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 223 | self.addCleanup(p.stdout.close) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 224 | self.assertEqual(p.stdout.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 225 | |
| 226 | def test_stdout_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 227 | # stdout is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 228 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 229 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 230 | d = tf.fileno() |
| 231 | p = subprocess.Popen([sys.executable, "-c", |
| 232 | 'import sys; sys.stdout.write("orange")'], |
| 233 | stdout=d) |
| 234 | p.wait() |
| 235 | os.lseek(d, 0, 0) |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 236 | self.assertEqual(os.read(d, 1024), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 237 | |
| 238 | def test_stdout_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 239 | # stdout is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 240 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 241 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 242 | p = subprocess.Popen([sys.executable, "-c", |
| 243 | 'import sys; sys.stdout.write("orange")'], |
| 244 | stdout=tf) |
| 245 | p.wait() |
| 246 | tf.seek(0) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 247 | self.assertEqual(tf.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 248 | |
| 249 | def test_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 250 | # stderr redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 251 | p = subprocess.Popen([sys.executable, "-c", |
| 252 | 'import sys; sys.stderr.write("strawberry")'], |
| 253 | stderr=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 254 | self.addCleanup(p.stderr.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 255 | self.assertStderrEqual(p.stderr.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 256 | |
| 257 | def test_stderr_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 258 | # stderr is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 259 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 260 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 261 | d = tf.fileno() |
| 262 | p = subprocess.Popen([sys.executable, "-c", |
| 263 | 'import sys; sys.stderr.write("strawberry")'], |
| 264 | stderr=d) |
| 265 | p.wait() |
| 266 | os.lseek(d, 0, 0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 267 | self.assertStderrEqual(os.read(d, 1024), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 268 | |
| 269 | def test_stderr_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 270 | # stderr is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 271 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 272 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 273 | p = subprocess.Popen([sys.executable, "-c", |
| 274 | 'import sys; sys.stderr.write("strawberry")'], |
| 275 | stderr=tf) |
| 276 | p.wait() |
| 277 | tf.seek(0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 278 | self.assertStderrEqual(tf.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 279 | |
| 280 | def test_stdout_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 281 | # capture stdout and stderr to the same pipe |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 282 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 283 | 'import sys;' |
| 284 | 'sys.stdout.write("apple");' |
| 285 | 'sys.stdout.flush();' |
| 286 | 'sys.stderr.write("orange")'], |
| 287 | stdout=subprocess.PIPE, |
| 288 | stderr=subprocess.STDOUT) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 289 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 290 | self.assertStderrEqual(p.stdout.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 291 | |
| 292 | def test_stdout_stderr_file(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 293 | # capture stdout and stderr to the same open file |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 294 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 295 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 296 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 297 | 'import sys;' |
| 298 | 'sys.stdout.write("apple");' |
| 299 | 'sys.stdout.flush();' |
| 300 | 'sys.stderr.write("orange")'], |
| 301 | stdout=tf, |
| 302 | stderr=tf) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 303 | p.wait() |
| 304 | tf.seek(0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 305 | self.assertStderrEqual(tf.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 306 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 307 | def test_stdout_filedes_of_stdout(self): |
| 308 | # stdout is set to 1 (#1531862). |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 309 | 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] | 310 | rc = subprocess.call([sys.executable, "-c", cmd], stdout=1) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 311 | self.assertEqual(rc, 2) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 312 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 313 | def test_cwd(self): |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 314 | tmpdir = tempfile.gettempdir() |
Peter Astrand | 195404f | 2004-11-12 15:51:48 +0000 | [diff] [blame] | 315 | # We cannot use os.path.realpath to canonicalize the path, |
| 316 | # since it doesn't expand Tru64 {memb} strings. See bug 1063571. |
| 317 | cwd = os.getcwd() |
| 318 | os.chdir(tmpdir) |
| 319 | tmpdir = os.getcwd() |
| 320 | os.chdir(cwd) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 321 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 322 | 'import sys,os;' |
| 323 | 'sys.stdout.write(os.getcwd())'], |
| 324 | stdout=subprocess.PIPE, |
| 325 | cwd=tmpdir) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 326 | self.addCleanup(p.stdout.close) |
Fredrik Lundh | 59c0559 | 2004-10-13 06:55:40 +0000 | [diff] [blame] | 327 | normcase = os.path.normcase |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 328 | self.assertEqual(normcase(p.stdout.read().decode("utf-8")), |
| 329 | normcase(tmpdir)) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 330 | |
| 331 | def test_env(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 332 | newenv = os.environ.copy() |
| 333 | newenv["FRUIT"] = "orange" |
| 334 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 335 | 'import sys,os;' |
| 336 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 337 | stdout=subprocess.PIPE, |
| 338 | env=newenv) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 339 | self.addCleanup(p.stdout.close) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 340 | self.assertEqual(p.stdout.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 341 | |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 342 | def test_communicate_stdin(self): |
| 343 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 344 | 'import sys;' |
| 345 | 'sys.exit(sys.stdin.read() == "pear")'], |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 346 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 347 | p.communicate(b"pear") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 348 | self.assertEqual(p.returncode, 1) |
| 349 | |
| 350 | def test_communicate_stdout(self): |
| 351 | p = subprocess.Popen([sys.executable, "-c", |
| 352 | 'import sys; sys.stdout.write("pineapple")'], |
| 353 | stdout=subprocess.PIPE) |
| 354 | (stdout, stderr) = p.communicate() |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 355 | self.assertEqual(stdout, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 356 | self.assertEqual(stderr, None) |
| 357 | |
| 358 | def test_communicate_stderr(self): |
| 359 | p = subprocess.Popen([sys.executable, "-c", |
| 360 | 'import sys; sys.stderr.write("pineapple")'], |
| 361 | stderr=subprocess.PIPE) |
| 362 | (stdout, stderr) = p.communicate() |
| 363 | self.assertEqual(stdout, None) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 364 | self.assertStderrEqual(stderr, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 365 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 366 | def test_communicate(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 367 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 368 | 'import sys,os;' |
| 369 | 'sys.stderr.write("pineapple");' |
| 370 | 'sys.stdout.write(sys.stdin.read())'], |
| 371 | stdin=subprocess.PIPE, |
| 372 | stdout=subprocess.PIPE, |
| 373 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 374 | self.addCleanup(p.stdout.close) |
| 375 | self.addCleanup(p.stderr.close) |
| 376 | self.addCleanup(p.stdin.close) |
Georg Brandl | 1abcbf8 | 2008-07-01 19:28:43 +0000 | [diff] [blame] | 377 | (stdout, stderr) = p.communicate(b"banana") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 378 | self.assertEqual(stdout, b"banana") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 379 | self.assertStderrEqual(stderr, b"pineapple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 380 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 381 | # Test for the fd leak reported in http://bugs.python.org/issue2791. |
| 382 | def test_communicate_pipe_fd_leak(self): |
Victor Stinner | 667d4b5 | 2010-12-25 22:40:32 +0000 | [diff] [blame] | 383 | for stdin_pipe in (False, True): |
| 384 | for stdout_pipe in (False, True): |
| 385 | for stderr_pipe in (False, True): |
| 386 | options = {} |
| 387 | if stdin_pipe: |
| 388 | options['stdin'] = subprocess.PIPE |
| 389 | if stdout_pipe: |
| 390 | options['stdout'] = subprocess.PIPE |
| 391 | if stderr_pipe: |
| 392 | options['stderr'] = subprocess.PIPE |
| 393 | if not options: |
| 394 | continue |
| 395 | p = subprocess.Popen((sys.executable, "-c", "pass"), **options) |
| 396 | p.communicate() |
| 397 | if p.stdin is not None: |
| 398 | self.assertTrue(p.stdin.closed) |
| 399 | if p.stdout is not None: |
| 400 | self.assertTrue(p.stdout.closed) |
| 401 | if p.stderr is not None: |
| 402 | self.assertTrue(p.stderr.closed) |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 403 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 404 | def test_communicate_returns(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 405 | # communicate() should return None if no redirection is active |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 406 | p = subprocess.Popen([sys.executable, "-c", |
| 407 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 408 | (stdout, stderr) = p.communicate() |
| 409 | self.assertEqual(stdout, None) |
| 410 | self.assertEqual(stderr, None) |
| 411 | |
| 412 | def test_communicate_pipe_buf(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 413 | # communicate() with writes larger than pipe_buf |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 414 | # This test will probably deadlock rather than fail, if |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 415 | # communicate() does not work properly. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 416 | x, y = os.pipe() |
| 417 | if mswindows: |
| 418 | pipe_buf = 512 |
| 419 | else: |
| 420 | pipe_buf = os.fpathconf(x, "PC_PIPE_BUF") |
| 421 | os.close(x) |
| 422 | os.close(y) |
| 423 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 424 | 'import sys,os;' |
| 425 | 'sys.stdout.write(sys.stdin.read(47));' |
| 426 | 'sys.stderr.write("xyz"*%d);' |
| 427 | 'sys.stdout.write(sys.stdin.read())' % pipe_buf], |
| 428 | stdin=subprocess.PIPE, |
| 429 | stdout=subprocess.PIPE, |
| 430 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 431 | self.addCleanup(p.stdout.close) |
| 432 | self.addCleanup(p.stderr.close) |
| 433 | self.addCleanup(p.stdin.close) |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 434 | string_to_write = b"abc"*pipe_buf |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 435 | (stdout, stderr) = p.communicate(string_to_write) |
| 436 | self.assertEqual(stdout, string_to_write) |
| 437 | |
| 438 | def test_writes_before_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 439 | # stdin.write before communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 440 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 441 | 'import sys,os;' |
| 442 | 'sys.stdout.write(sys.stdin.read())'], |
| 443 | stdin=subprocess.PIPE, |
| 444 | stdout=subprocess.PIPE, |
| 445 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 446 | self.addCleanup(p.stdout.close) |
| 447 | self.addCleanup(p.stderr.close) |
| 448 | self.addCleanup(p.stdin.close) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 449 | p.stdin.write(b"banana") |
| 450 | (stdout, stderr) = p.communicate(b"split") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 451 | self.assertEqual(stdout, b"bananasplit") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 452 | self.assertStderrEqual(stderr, b"") |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 453 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 454 | def test_universal_newlines(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 455 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 456 | 'import sys,os;' + SETBINARY + |
| 457 | 'sys.stdout.write("line1\\n");' |
| 458 | 'sys.stdout.flush();' |
| 459 | 'sys.stdout.write("line2\\n");' |
| 460 | 'sys.stdout.flush();' |
| 461 | 'sys.stdout.write("line3\\r\\n");' |
| 462 | 'sys.stdout.flush();' |
| 463 | 'sys.stdout.write("line4\\r");' |
| 464 | 'sys.stdout.flush();' |
| 465 | 'sys.stdout.write("\\nline5");' |
| 466 | 'sys.stdout.flush();' |
| 467 | 'sys.stdout.write("\\nline6");'], |
| 468 | stdout=subprocess.PIPE, |
| 469 | universal_newlines=1) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 470 | self.addCleanup(p.stdout.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 471 | stdout = p.stdout.read() |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 472 | self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 473 | |
| 474 | def test_universal_newlines_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 475 | # universal newlines through communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 476 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 477 | 'import sys,os;' + SETBINARY + |
| 478 | 'sys.stdout.write("line1\\n");' |
| 479 | 'sys.stdout.flush();' |
| 480 | 'sys.stdout.write("line2\\n");' |
| 481 | 'sys.stdout.flush();' |
| 482 | 'sys.stdout.write("line3\\r\\n");' |
| 483 | 'sys.stdout.flush();' |
| 484 | 'sys.stdout.write("line4\\r");' |
| 485 | 'sys.stdout.flush();' |
| 486 | 'sys.stdout.write("\\nline5");' |
| 487 | 'sys.stdout.flush();' |
| 488 | 'sys.stdout.write("\\nline6");'], |
| 489 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 490 | universal_newlines=1) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 491 | self.addCleanup(p.stdout.close) |
| 492 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 493 | (stdout, stderr) = p.communicate() |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 494 | self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 495 | |
| 496 | def test_no_leaking(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 497 | # Make sure we leak no resources |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 498 | if not mswindows: |
Peter Astrand | f7f1bb7 | 2005-03-03 20:47:37 +0000 | [diff] [blame] | 499 | max_handles = 1026 # too much for most UNIX systems |
| 500 | else: |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 501 | max_handles = 2050 # too much for (at least some) Windows setups |
| 502 | handles = [] |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 503 | tmpdir = tempfile.mkdtemp() |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 504 | try: |
| 505 | for i in range(max_handles): |
| 506 | try: |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 507 | tmpfile = os.path.join(tmpdir, support.TESTFN) |
| 508 | handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT)) |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 509 | except OSError as e: |
| 510 | if e.errno != errno.EMFILE: |
| 511 | raise |
| 512 | break |
| 513 | else: |
| 514 | self.skipTest("failed to reach the file descriptor limit " |
| 515 | "(tried %d)" % max_handles) |
| 516 | # Close a couple of them (should be enough for a subprocess) |
| 517 | for i in range(10): |
| 518 | os.close(handles.pop()) |
| 519 | # Loop creating some subprocesses. If one of them leaks some fds, |
| 520 | # the next loop iteration will fail by reaching the max fd limit. |
| 521 | for i in range(15): |
| 522 | p = subprocess.Popen([sys.executable, "-c", |
| 523 | "import sys;" |
| 524 | "sys.stdout.write(sys.stdin.read())"], |
| 525 | stdin=subprocess.PIPE, |
| 526 | stdout=subprocess.PIPE, |
| 527 | stderr=subprocess.PIPE) |
| 528 | data = p.communicate(b"lime")[0] |
| 529 | self.assertEqual(data, b"lime") |
| 530 | finally: |
| 531 | for h in handles: |
| 532 | os.close(h) |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 533 | shutil.rmtree(tmpdir) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 534 | |
| 535 | def test_list2cmdline(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 536 | self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']), |
| 537 | '"a b c" d e') |
| 538 | self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']), |
| 539 | 'ab\\"c \\ d') |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 540 | self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']), |
| 541 | 'ab\\"c " \\\\" d') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 542 | self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']), |
| 543 | 'a\\\\\\b "de fg" h') |
| 544 | self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']), |
| 545 | 'a\\\\\\"b c d') |
| 546 | self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']), |
| 547 | '"a\\\\b c" d e') |
| 548 | self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']), |
| 549 | '"a\\\\b\\ c" d e') |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 550 | self.assertEqual(subprocess.list2cmdline(['ab', '']), |
| 551 | 'ab ""') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 552 | |
| 553 | |
| 554 | def test_poll(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 555 | p = subprocess.Popen([sys.executable, |
Tim Peters | 29b6b4f | 2004-10-13 03:43:40 +0000 | [diff] [blame] | 556 | "-c", "import time; time.sleep(1)"]) |
| 557 | count = 0 |
| 558 | while p.poll() is None: |
| 559 | time.sleep(0.1) |
| 560 | count += 1 |
| 561 | # We expect that the poll loop probably went around about 10 times, |
| 562 | # but, based on system scheduling we can't control, it's possible |
| 563 | # poll() never returned None. It "should be" very rare that it |
| 564 | # didn't go around at least twice. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 565 | self.assertGreaterEqual(count, 2) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 566 | # Subsequent invocations should just return the returncode |
| 567 | self.assertEqual(p.poll(), 0) |
| 568 | |
| 569 | |
| 570 | def test_wait(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 571 | p = subprocess.Popen([sys.executable, |
| 572 | "-c", "import time; time.sleep(2)"]) |
| 573 | self.assertEqual(p.wait(), 0) |
| 574 | # Subsequent invocations should just return the returncode |
| 575 | self.assertEqual(p.wait(), 0) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 576 | |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 577 | |
| 578 | def test_invalid_bufsize(self): |
| 579 | # an invalid type of the bufsize argument should raise |
| 580 | # TypeError. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 581 | with self.assertRaises(TypeError): |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 582 | subprocess.Popen([sys.executable, "-c", "pass"], "orange") |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 583 | |
Guido van Rossum | 46a05a7 | 2007-06-07 21:56:45 +0000 | [diff] [blame] | 584 | def test_bufsize_is_none(self): |
| 585 | # bufsize=None should be the same as bufsize=0. |
| 586 | p = subprocess.Popen([sys.executable, "-c", "pass"], None) |
| 587 | self.assertEqual(p.wait(), 0) |
| 588 | # Again with keyword arg |
| 589 | p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None) |
| 590 | self.assertEqual(p.wait(), 0) |
| 591 | |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 592 | def test_leaking_fds_on_error(self): |
| 593 | # see bug #5179: Popen leaks file descriptors to PIPEs if |
| 594 | # the child fails to execute; this will eventually exhaust |
| 595 | # the maximum number of open fds. 1024 seems a very common |
| 596 | # value for that limit, but Windows has 2048, so we loop |
| 597 | # 1024 times (each call leaked two fds). |
| 598 | for i in range(1024): |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 599 | # Windows raises IOError. Others raise OSError. |
| 600 | with self.assertRaises(EnvironmentError) as c: |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 601 | subprocess.Popen(['nonexisting_i_hope'], |
| 602 | stdout=subprocess.PIPE, |
| 603 | stderr=subprocess.PIPE) |
R David Murray | 384069c | 2011-03-13 22:26:53 -0400 | [diff] [blame] | 604 | # ignore errors that indicate the command was not found |
R David Murray | 6924bd7 | 2011-03-13 22:48:55 -0400 | [diff] [blame] | 605 | if c.exception.errno not in (errno.ENOENT, errno.EACCES): |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 606 | raise c.exception |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 607 | |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 608 | def test_issue8780(self): |
| 609 | # Ensure that stdout is inherited from the parent |
| 610 | # if stdout=PIPE is not used |
| 611 | code = ';'.join(( |
| 612 | 'import subprocess, sys', |
| 613 | 'retcode = subprocess.call(' |
| 614 | "[sys.executable, '-c', 'print(\"Hello World!\")'])", |
| 615 | 'assert retcode == 0')) |
| 616 | output = subprocess.check_output([sys.executable, '-c', code]) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 617 | self.assertTrue(output.startswith(b'Hello World!'), ascii(output)) |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 618 | |
Tim Golden | af5ac39 | 2010-08-06 13:03:56 +0000 | [diff] [blame] | 619 | def test_handles_closed_on_exception(self): |
| 620 | # If CreateProcess exits with an error, ensure the |
| 621 | # duplicate output handles are released |
| 622 | ifhandle, ifname = mkstemp() |
| 623 | ofhandle, ofname = mkstemp() |
| 624 | efhandle, efname = mkstemp() |
| 625 | try: |
| 626 | subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle, |
| 627 | stderr=efhandle) |
| 628 | except OSError: |
| 629 | os.close(ifhandle) |
| 630 | os.remove(ifname) |
| 631 | os.close(ofhandle) |
| 632 | os.remove(ofname) |
| 633 | os.close(efhandle) |
| 634 | os.remove(efname) |
| 635 | self.assertFalse(os.path.exists(ifname)) |
| 636 | self.assertFalse(os.path.exists(ofname)) |
| 637 | self.assertFalse(os.path.exists(efname)) |
| 638 | |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 639 | def test_communicate_epipe(self): |
| 640 | # Issue 10963: communicate() should hide EPIPE |
| 641 | p = subprocess.Popen([sys.executable, "-c", 'pass'], |
| 642 | stdin=subprocess.PIPE, |
| 643 | stdout=subprocess.PIPE, |
| 644 | stderr=subprocess.PIPE) |
| 645 | self.addCleanup(p.stdout.close) |
| 646 | self.addCleanup(p.stderr.close) |
| 647 | self.addCleanup(p.stdin.close) |
| 648 | p.communicate(b"x" * 2**20) |
| 649 | |
| 650 | def test_communicate_epipe_only_stdin(self): |
| 651 | # Issue 10963: communicate() should hide EPIPE |
| 652 | p = subprocess.Popen([sys.executable, "-c", 'pass'], |
| 653 | stdin=subprocess.PIPE) |
| 654 | self.addCleanup(p.stdin.close) |
| 655 | time.sleep(2) |
| 656 | p.communicate(b"x" * 2**20) |
| 657 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 658 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 659 | # context manager |
| 660 | class _SuppressCoreFiles(object): |
| 661 | """Try to prevent core files from being created.""" |
| 662 | old_limit = None |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 663 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 664 | def __enter__(self): |
| 665 | """Try to save previous ulimit, then set it to (0, 0).""" |
| 666 | try: |
| 667 | import resource |
| 668 | self.old_limit = resource.getrlimit(resource.RLIMIT_CORE) |
| 669 | resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) |
| 670 | except (ImportError, ValueError, resource.error): |
| 671 | pass |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 672 | |
Ronald Oussoren | 102d11a | 2010-07-23 09:50:05 +0000 | [diff] [blame] | 673 | if sys.platform == 'darwin': |
| 674 | # Check if the 'Crash Reporter' on OSX was configured |
| 675 | # in 'Developer' mode and warn that it will get triggered |
| 676 | # when it is. |
| 677 | # |
| 678 | # This assumes that this context manager is used in tests |
| 679 | # that might trigger the next manager. |
| 680 | value = subprocess.Popen(['/usr/bin/defaults', 'read', |
| 681 | 'com.apple.CrashReporter', 'DialogType'], |
| 682 | stdout=subprocess.PIPE).communicate()[0] |
| 683 | if value.strip() == b'developer': |
| 684 | print("this tests triggers the Crash Reporter, " |
| 685 | "that is intentional", end='') |
| 686 | sys.stdout.flush() |
| 687 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 688 | def __exit__(self, *args): |
| 689 | """Return core file behavior to default.""" |
| 690 | if self.old_limit is None: |
| 691 | return |
| 692 | try: |
| 693 | import resource |
| 694 | resource.setrlimit(resource.RLIMIT_CORE, self.old_limit) |
| 695 | except (ImportError, ValueError, resource.error): |
| 696 | pass |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 697 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 698 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 699 | @unittest.skipIf(mswindows, "POSIX specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 700 | class POSIXProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 701 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 702 | def test_exceptions(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 703 | nonexistent_dir = "/_this/pa.th/does/not/exist" |
| 704 | try: |
| 705 | os.chdir(nonexistent_dir) |
| 706 | except OSError as e: |
| 707 | # This avoids hard coding the errno value or the OS perror() |
| 708 | # string and instead capture the exception that we want to see |
| 709 | # below for comparison. |
| 710 | desired_exception = e |
Benjamin Peterson | 5f78040 | 2010-11-20 18:07:52 +0000 | [diff] [blame] | 711 | desired_exception.strerror += ': ' + repr(sys.executable) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 712 | else: |
| 713 | self.fail("chdir to nonexistant directory %s succeeded." % |
| 714 | nonexistent_dir) |
| 715 | |
| 716 | # Error in the child re-raised in the parent. |
| 717 | try: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 718 | p = subprocess.Popen([sys.executable, "-c", ""], |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 719 | cwd=nonexistent_dir) |
| 720 | except OSError as e: |
| 721 | # Test that the child process chdir failure actually makes |
| 722 | # it up to the parent process as the correct exception. |
| 723 | self.assertEqual(desired_exception.errno, e.errno) |
| 724 | self.assertEqual(desired_exception.strerror, e.strerror) |
| 725 | else: |
| 726 | self.fail("Expected OSError: %s" % desired_exception) |
| 727 | |
| 728 | def test_restore_signals(self): |
| 729 | # Code coverage for both values of restore_signals to make sure it |
| 730 | # at least does not blow up. |
| 731 | # A test for behavior would be complex. Contributions welcome. |
| 732 | subprocess.call([sys.executable, "-c", ""], restore_signals=True) |
| 733 | subprocess.call([sys.executable, "-c", ""], restore_signals=False) |
| 734 | |
| 735 | def test_start_new_session(self): |
| 736 | # For code coverage of calling setsid(). We don't care if we get an |
| 737 | # EPERM error from it depending on the test execution environment, that |
| 738 | # still indicates that it was called. |
| 739 | try: |
| 740 | output = subprocess.check_output( |
| 741 | [sys.executable, "-c", |
| 742 | "import os; print(os.getpgid(os.getpid()))"], |
| 743 | start_new_session=True) |
| 744 | except OSError as e: |
| 745 | if e.errno != errno.EPERM: |
| 746 | raise |
| 747 | else: |
| 748 | parent_pgid = os.getpgid(os.getpid()) |
| 749 | child_pgid = int(output) |
| 750 | self.assertNotEqual(parent_pgid, child_pgid) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 751 | |
| 752 | def test_run_abort(self): |
| 753 | # returncode handles signal termination |
| 754 | with _SuppressCoreFiles(): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 755 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 756 | 'import os; os.abort()']) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 757 | p.wait() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 758 | self.assertEqual(-p.returncode, signal.SIGABRT) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 759 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 760 | def test_preexec(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 761 | # DISCLAIMER: Setting environment variables is *not* a good use |
| 762 | # of a preexec_fn. This is merely a test. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 763 | p = subprocess.Popen([sys.executable, "-c", |
| 764 | 'import sys,os;' |
| 765 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 766 | stdout=subprocess.PIPE, |
| 767 | preexec_fn=lambda: os.putenv("FRUIT", "apple")) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 768 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 769 | self.assertEqual(p.stdout.read(), b"apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 770 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 771 | def test_preexec_exception(self): |
| 772 | def raise_it(): |
| 773 | raise ValueError("What if two swallows carried a coconut?") |
| 774 | try: |
| 775 | p = subprocess.Popen([sys.executable, "-c", ""], |
| 776 | preexec_fn=raise_it) |
| 777 | except RuntimeError as e: |
| 778 | self.assertTrue( |
| 779 | subprocess._posixsubprocess, |
| 780 | "Expected a ValueError from the preexec_fn") |
| 781 | except ValueError as e: |
| 782 | self.assertIn("coconut", e.args[0]) |
| 783 | else: |
| 784 | self.fail("Exception raised by preexec_fn did not make it " |
| 785 | "to the parent process.") |
| 786 | |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 787 | @unittest.skipUnless(gc, "Requires a gc module.") |
| 788 | def test_preexec_gc_module_failure(self): |
| 789 | # This tests the code that disables garbage collection if the child |
| 790 | # process will execute any Python. |
| 791 | def raise_runtime_error(): |
| 792 | raise RuntimeError("this shouldn't escape") |
| 793 | enabled = gc.isenabled() |
| 794 | orig_gc_disable = gc.disable |
| 795 | orig_gc_isenabled = gc.isenabled |
| 796 | try: |
| 797 | gc.disable() |
| 798 | self.assertFalse(gc.isenabled()) |
| 799 | subprocess.call([sys.executable, '-c', ''], |
| 800 | preexec_fn=lambda: None) |
| 801 | self.assertFalse(gc.isenabled(), |
| 802 | "Popen enabled gc when it shouldn't.") |
| 803 | |
| 804 | gc.enable() |
| 805 | self.assertTrue(gc.isenabled()) |
| 806 | subprocess.call([sys.executable, '-c', ''], |
| 807 | preexec_fn=lambda: None) |
| 808 | self.assertTrue(gc.isenabled(), "Popen left gc disabled.") |
| 809 | |
| 810 | gc.disable = raise_runtime_error |
| 811 | self.assertRaises(RuntimeError, subprocess.Popen, |
| 812 | [sys.executable, '-c', ''], |
| 813 | preexec_fn=lambda: None) |
| 814 | |
| 815 | del gc.isenabled # force an AttributeError |
| 816 | self.assertRaises(AttributeError, subprocess.Popen, |
| 817 | [sys.executable, '-c', ''], |
| 818 | preexec_fn=lambda: None) |
| 819 | finally: |
| 820 | gc.disable = orig_gc_disable |
| 821 | gc.isenabled = orig_gc_isenabled |
| 822 | if not enabled: |
| 823 | gc.disable() |
| 824 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 825 | def test_args_string(self): |
| 826 | # args is a string |
| 827 | fd, fname = mkstemp() |
| 828 | # reopen in text mode |
Victor Stinner | f6782ac | 2010-10-16 23:46:43 +0000 | [diff] [blame] | 829 | with open(fd, "w", errors="surrogateescape") as fobj: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 830 | fobj.write("#!/bin/sh\n") |
| 831 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 832 | sys.executable) |
| 833 | os.chmod(fname, 0o700) |
| 834 | p = subprocess.Popen(fname) |
| 835 | p.wait() |
| 836 | os.remove(fname) |
| 837 | self.assertEqual(p.returncode, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 838 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 839 | def test_invalid_args(self): |
| 840 | # invalid arguments should raise ValueError |
| 841 | self.assertRaises(ValueError, subprocess.call, |
| 842 | [sys.executable, "-c", |
| 843 | "import sys; sys.exit(47)"], |
| 844 | startupinfo=47) |
| 845 | self.assertRaises(ValueError, subprocess.call, |
| 846 | [sys.executable, "-c", |
| 847 | "import sys; sys.exit(47)"], |
| 848 | creationflags=47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 849 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 850 | def test_shell_sequence(self): |
| 851 | # Run command through the shell (sequence) |
| 852 | newenv = os.environ.copy() |
| 853 | newenv["FRUIT"] = "apple" |
| 854 | p = subprocess.Popen(["echo $FRUIT"], shell=1, |
| 855 | stdout=subprocess.PIPE, |
| 856 | env=newenv) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 857 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 858 | 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] | 859 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 860 | def test_shell_string(self): |
| 861 | # Run command through the shell (string) |
| 862 | newenv = os.environ.copy() |
| 863 | newenv["FRUIT"] = "apple" |
| 864 | p = subprocess.Popen("echo $FRUIT", shell=1, |
| 865 | stdout=subprocess.PIPE, |
| 866 | env=newenv) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 867 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 868 | 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] | 869 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 870 | def test_call_string(self): |
| 871 | # call() function with string argument on UNIX |
| 872 | fd, fname = mkstemp() |
| 873 | # reopen in text mode |
Victor Stinner | f6782ac | 2010-10-16 23:46:43 +0000 | [diff] [blame] | 874 | with open(fd, "w", errors="surrogateescape") as fobj: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 875 | fobj.write("#!/bin/sh\n") |
| 876 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 877 | sys.executable) |
| 878 | os.chmod(fname, 0o700) |
| 879 | rc = subprocess.call(fname) |
| 880 | os.remove(fname) |
| 881 | self.assertEqual(rc, 47) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 882 | |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 883 | def test_specific_shell(self): |
| 884 | # Issue #9265: Incorrect name passed as arg[0]. |
| 885 | shells = [] |
| 886 | for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']: |
| 887 | for name in ['bash', 'ksh']: |
| 888 | sh = os.path.join(prefix, name) |
| 889 | if os.path.isfile(sh): |
| 890 | shells.append(sh) |
| 891 | if not shells: # Will probably work for any shell but csh. |
| 892 | self.skipTest("bash or ksh required for this test") |
| 893 | sh = '/bin/sh' |
| 894 | if os.path.isfile(sh) and not os.path.islink(sh): |
| 895 | # Test will fail if /bin/sh is a symlink to csh. |
| 896 | shells.append(sh) |
| 897 | for sh in shells: |
| 898 | p = subprocess.Popen("echo $0", executable=sh, shell=True, |
| 899 | stdout=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 900 | self.addCleanup(p.stdout.close) |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 901 | self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii')) |
| 902 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 903 | def _kill_process(self, method, *args): |
Florent Xicluna | 1d8ee3a | 2010-03-05 20:26:54 +0000 | [diff] [blame] | 904 | # Do not inherit file handles from the parent. |
| 905 | # It should fix failures on some platforms. |
Antoine Pitrou | 3d8580f | 2010-09-20 01:33:21 +0000 | [diff] [blame] | 906 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 907 | import sys, time |
| 908 | sys.stdout.write('x\\n') |
| 909 | sys.stdout.flush() |
| 910 | time.sleep(30) |
| 911 | """], |
| 912 | close_fds=True, |
| 913 | stdin=subprocess.PIPE, |
| 914 | stdout=subprocess.PIPE, |
| 915 | stderr=subprocess.PIPE) |
| 916 | # Wait for the interpreter to be completely initialized before |
| 917 | # sending any signal. |
| 918 | p.stdout.read(1) |
| 919 | getattr(p, method)(*args) |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 920 | return p |
| 921 | |
| 922 | def test_send_signal(self): |
| 923 | p = self._kill_process('send_signal', signal.SIGINT) |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 924 | _, stderr = p.communicate() |
| 925 | self.assertIn(b'KeyboardInterrupt', stderr) |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 926 | self.assertNotEqual(p.wait(), 0) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 927 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 928 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 929 | p = self._kill_process('kill') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 930 | _, stderr = p.communicate() |
| 931 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 932 | self.assertEqual(p.wait(), -signal.SIGKILL) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 933 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 934 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 935 | p = self._kill_process('terminate') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 936 | _, stderr = p.communicate() |
| 937 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 938 | self.assertEqual(p.wait(), -signal.SIGTERM) |
| 939 | |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 940 | def check_close_std_fds(self, fds): |
| 941 | # Issue #9905: test that subprocess pipes still work properly with |
| 942 | # some standard fds closed |
| 943 | stdin = 0 |
| 944 | newfds = [] |
| 945 | for a in fds: |
| 946 | b = os.dup(a) |
| 947 | newfds.append(b) |
| 948 | if a == 0: |
| 949 | stdin = b |
| 950 | try: |
| 951 | for fd in fds: |
| 952 | os.close(fd) |
| 953 | out, err = subprocess.Popen([sys.executable, "-c", |
| 954 | 'import sys;' |
| 955 | 'sys.stdout.write("apple");' |
| 956 | 'sys.stdout.flush();' |
| 957 | 'sys.stderr.write("orange")'], |
| 958 | stdin=stdin, |
| 959 | stdout=subprocess.PIPE, |
| 960 | stderr=subprocess.PIPE).communicate() |
| 961 | err = support.strip_python_stderr(err) |
| 962 | self.assertEqual((out, err), (b'apple', b'orange')) |
| 963 | finally: |
| 964 | for b, a in zip(newfds, fds): |
| 965 | os.dup2(b, a) |
| 966 | for b in newfds: |
| 967 | os.close(b) |
| 968 | |
| 969 | def test_close_fd_0(self): |
| 970 | self.check_close_std_fds([0]) |
| 971 | |
| 972 | def test_close_fd_1(self): |
| 973 | self.check_close_std_fds([1]) |
| 974 | |
| 975 | def test_close_fd_2(self): |
| 976 | self.check_close_std_fds([2]) |
| 977 | |
| 978 | def test_close_fds_0_1(self): |
| 979 | self.check_close_std_fds([0, 1]) |
| 980 | |
| 981 | def test_close_fds_0_2(self): |
| 982 | self.check_close_std_fds([0, 2]) |
| 983 | |
| 984 | def test_close_fds_1_2(self): |
| 985 | self.check_close_std_fds([1, 2]) |
| 986 | |
| 987 | def test_close_fds_0_1_2(self): |
| 988 | # Issue #10806: test that subprocess pipes still work properly with |
| 989 | # all standard fds closed. |
| 990 | self.check_close_std_fds([0, 1, 2]) |
| 991 | |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 992 | def test_remapping_std_fds(self): |
| 993 | # open up some temporary files |
| 994 | temps = [mkstemp() for i in range(3)] |
| 995 | try: |
| 996 | temp_fds = [fd for fd, fname in temps] |
| 997 | |
| 998 | # unlink the files -- we won't need to reopen them |
| 999 | for fd, fname in temps: |
| 1000 | os.unlink(fname) |
| 1001 | |
| 1002 | # write some data to what will become stdin, and rewind |
| 1003 | os.write(temp_fds[1], b"STDIN") |
| 1004 | os.lseek(temp_fds[1], 0, 0) |
| 1005 | |
| 1006 | # move the standard file descriptors out of the way |
| 1007 | saved_fds = [os.dup(fd) for fd in range(3)] |
| 1008 | try: |
| 1009 | # duplicate the file objects over the standard fd's |
| 1010 | for fd, temp_fd in enumerate(temp_fds): |
| 1011 | os.dup2(temp_fd, fd) |
| 1012 | |
| 1013 | # now use those files in the "wrong" order, so that subprocess |
| 1014 | # has to rearrange them in the child |
| 1015 | p = subprocess.Popen([sys.executable, "-c", |
| 1016 | 'import sys; got = sys.stdin.read();' |
| 1017 | 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'], |
| 1018 | stdin=temp_fds[1], |
| 1019 | stdout=temp_fds[2], |
| 1020 | stderr=temp_fds[0]) |
| 1021 | p.wait() |
| 1022 | finally: |
| 1023 | # restore the original fd's underneath sys.stdin, etc. |
| 1024 | for std, saved in enumerate(saved_fds): |
| 1025 | os.dup2(saved, std) |
| 1026 | os.close(saved) |
| 1027 | |
| 1028 | for fd in temp_fds: |
| 1029 | os.lseek(fd, 0, 0) |
| 1030 | |
| 1031 | out = os.read(temp_fds[2], 1024) |
| 1032 | err = support.strip_python_stderr(os.read(temp_fds[0], 1024)) |
| 1033 | self.assertEqual(out, b"got STDIN") |
| 1034 | self.assertEqual(err, b"err") |
| 1035 | |
| 1036 | finally: |
| 1037 | for fd in temp_fds: |
| 1038 | os.close(fd) |
| 1039 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1040 | def test_surrogates_error_message(self): |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 1041 | def prepare(): |
| 1042 | raise ValueError("surrogate:\uDCff") |
| 1043 | |
| 1044 | try: |
| 1045 | subprocess.call( |
| 1046 | [sys.executable, "-c", "pass"], |
| 1047 | preexec_fn=prepare) |
| 1048 | except ValueError as err: |
| 1049 | # Pure Python implementations keeps the message |
| 1050 | self.assertIsNone(subprocess._posixsubprocess) |
| 1051 | self.assertEqual(str(err), "surrogate:\uDCff") |
| 1052 | except RuntimeError as err: |
| 1053 | # _posixsubprocess uses a default message |
| 1054 | self.assertIsNotNone(subprocess._posixsubprocess) |
| 1055 | self.assertEqual(str(err), "Exception occurred in preexec_fn.") |
| 1056 | else: |
| 1057 | self.fail("Expected ValueError or RuntimeError") |
| 1058 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1059 | def test_undecodable_env(self): |
| 1060 | for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')): |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1061 | # test str with surrogates |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 1062 | script = "import os; print(ascii(os.getenv(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1063 | env = os.environ.copy() |
| 1064 | env[key] = value |
Victor Stinner | 89f3ad1 | 2010-10-14 10:43:31 +0000 | [diff] [blame] | 1065 | # Use C locale to get ascii for the locale encoding to force |
| 1066 | # surrogate-escaping of \xFF in the child process; otherwise it can |
| 1067 | # be decoded as-is if the default locale is latin-1. |
Victor Stinner | ebc78d2 | 2010-10-14 10:38:17 +0000 | [diff] [blame] | 1068 | env['LC_ALL'] = 'C' |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1069 | stdout = subprocess.check_output( |
| 1070 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1071 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1072 | stdout = stdout.rstrip(b'\n\r') |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1073 | self.assertEqual(stdout.decode('ascii'), ascii(value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1074 | |
| 1075 | # test bytes |
| 1076 | key = key.encode("ascii", "surrogateescape") |
| 1077 | value = value.encode("ascii", "surrogateescape") |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 1078 | script = "import os; print(ascii(os.getenvb(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1079 | env = os.environ.copy() |
| 1080 | env[key] = value |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1081 | stdout = subprocess.check_output( |
| 1082 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1083 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1084 | stdout = stdout.rstrip(b'\n\r') |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1085 | self.assertEqual(stdout.decode('ascii'), ascii(value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1086 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1087 | def test_bytes_program(self): |
| 1088 | abs_program = os.fsencode(sys.executable) |
| 1089 | path, program = os.path.split(sys.executable) |
| 1090 | program = os.fsencode(program) |
| 1091 | |
| 1092 | # absolute bytes path |
| 1093 | exitcode = subprocess.call([abs_program, "-c", "pass"]) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1094 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1095 | |
| 1096 | # bytes program, unicode PATH |
| 1097 | env = os.environ.copy() |
| 1098 | env["PATH"] = path |
| 1099 | exitcode = subprocess.call([program, "-c", "pass"], env=env) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1100 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1101 | |
| 1102 | # bytes program, bytes PATH |
| 1103 | envb = os.environb.copy() |
| 1104 | envb[b"PATH"] = os.fsencode(path) |
| 1105 | exitcode = subprocess.call([program, "-c", "pass"], env=envb) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1106 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1107 | |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 1108 | def test_pipe_cloexec(self): |
| 1109 | sleeper = support.findfile("input_reader.py", subdir="subprocessdata") |
| 1110 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 1111 | |
| 1112 | p1 = subprocess.Popen([sys.executable, sleeper], |
| 1113 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1114 | stderr=subprocess.PIPE, close_fds=False) |
| 1115 | |
| 1116 | self.addCleanup(p1.communicate, b'') |
| 1117 | |
| 1118 | p2 = subprocess.Popen([sys.executable, fd_status], |
| 1119 | stdout=subprocess.PIPE, close_fds=False) |
| 1120 | |
| 1121 | output, error = p2.communicate() |
| 1122 | result_fds = set(map(int, output.split(b','))) |
| 1123 | unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(), |
| 1124 | p1.stderr.fileno()]) |
| 1125 | |
| 1126 | self.assertFalse(result_fds & unwanted_fds, |
| 1127 | "Expected no fds from %r to be open in child, " |
| 1128 | "found %r" % |
| 1129 | (unwanted_fds, result_fds & unwanted_fds)) |
| 1130 | |
| 1131 | def test_pipe_cloexec_real_tools(self): |
| 1132 | qcat = support.findfile("qcat.py", subdir="subprocessdata") |
| 1133 | qgrep = support.findfile("qgrep.py", subdir="subprocessdata") |
| 1134 | |
| 1135 | subdata = b'zxcvbn' |
| 1136 | data = subdata * 4 + b'\n' |
| 1137 | |
| 1138 | p1 = subprocess.Popen([sys.executable, qcat], |
| 1139 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1140 | close_fds=False) |
| 1141 | |
| 1142 | p2 = subprocess.Popen([sys.executable, qgrep, subdata], |
| 1143 | stdin=p1.stdout, stdout=subprocess.PIPE, |
| 1144 | close_fds=False) |
| 1145 | |
| 1146 | self.addCleanup(p1.wait) |
| 1147 | self.addCleanup(p2.wait) |
| 1148 | self.addCleanup(p1.terminate) |
| 1149 | self.addCleanup(p2.terminate) |
| 1150 | |
| 1151 | p1.stdin.write(data) |
| 1152 | p1.stdin.close() |
| 1153 | |
| 1154 | readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10) |
| 1155 | |
| 1156 | self.assertTrue(readfiles, "The child hung") |
| 1157 | self.assertEqual(p2.stdout.read(), data) |
| 1158 | |
Victor Stinner | faa8c13 | 2011-01-03 16:36:00 +0000 | [diff] [blame] | 1159 | p1.stdout.close() |
| 1160 | p2.stdout.close() |
| 1161 | |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 1162 | def test_close_fds(self): |
| 1163 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 1164 | |
| 1165 | fds = os.pipe() |
| 1166 | self.addCleanup(os.close, fds[0]) |
| 1167 | self.addCleanup(os.close, fds[1]) |
| 1168 | |
| 1169 | open_fds = set(fds) |
| 1170 | |
| 1171 | p = subprocess.Popen([sys.executable, fd_status], |
| 1172 | stdout=subprocess.PIPE, close_fds=False) |
| 1173 | output, ignored = p.communicate() |
| 1174 | remaining_fds = set(map(int, output.split(b','))) |
| 1175 | |
| 1176 | self.assertEqual(remaining_fds & open_fds, open_fds, |
| 1177 | "Some fds were closed") |
| 1178 | |
| 1179 | p = subprocess.Popen([sys.executable, fd_status], |
| 1180 | stdout=subprocess.PIPE, close_fds=True) |
| 1181 | output, ignored = p.communicate() |
| 1182 | remaining_fds = set(map(int, output.split(b','))) |
| 1183 | |
| 1184 | self.assertFalse(remaining_fds & open_fds, |
| 1185 | "Some fds were left open") |
| 1186 | self.assertIn(1, remaining_fds, "Subprocess failed") |
| 1187 | |
Victor Stinner | 88701e2 | 2011-06-01 13:13:04 +0200 | [diff] [blame^] | 1188 | # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file |
| 1189 | # descriptor of a pipe closed in the parent process is valid in the |
| 1190 | # child process according to fstat(), but the mode of the file |
| 1191 | # descriptor is invalid, and read or write raise an error. |
| 1192 | @support.requires_mac_ver(10, 5) |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 1193 | def test_pass_fds(self): |
| 1194 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 1195 | |
| 1196 | open_fds = set() |
| 1197 | |
| 1198 | for x in range(5): |
| 1199 | fds = os.pipe() |
| 1200 | self.addCleanup(os.close, fds[0]) |
| 1201 | self.addCleanup(os.close, fds[1]) |
| 1202 | open_fds.update(fds) |
| 1203 | |
| 1204 | for fd in open_fds: |
| 1205 | p = subprocess.Popen([sys.executable, fd_status], |
| 1206 | stdout=subprocess.PIPE, close_fds=True, |
| 1207 | pass_fds=(fd, )) |
| 1208 | output, ignored = p.communicate() |
| 1209 | |
| 1210 | remaining_fds = set(map(int, output.split(b','))) |
| 1211 | to_be_closed = open_fds - {fd} |
| 1212 | |
| 1213 | self.assertIn(fd, remaining_fds, "fd to be passed not passed") |
| 1214 | self.assertFalse(remaining_fds & to_be_closed, |
| 1215 | "fd to be closed passed") |
| 1216 | |
| 1217 | # pass_fds overrides close_fds with a warning. |
| 1218 | with self.assertWarns(RuntimeWarning) as context: |
| 1219 | self.assertFalse(subprocess.call( |
| 1220 | [sys.executable, "-c", "import sys; sys.exit(0)"], |
| 1221 | close_fds=False, pass_fds=(fd, ))) |
| 1222 | self.assertIn('overriding close_fds', str(context.warning)) |
| 1223 | |
Gregory P. Smith | e14e9c2 | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 1224 | def test_stdout_stdin_are_single_inout_fd(self): |
| 1225 | with io.open(os.devnull, "r+") as inout: |
| 1226 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 1227 | stdout=inout, stdin=inout) |
| 1228 | p.wait() |
| 1229 | |
| 1230 | def test_stdout_stderr_are_single_inout_fd(self): |
| 1231 | with io.open(os.devnull, "r+") as inout: |
| 1232 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 1233 | stdout=inout, stderr=inout) |
| 1234 | p.wait() |
| 1235 | |
| 1236 | def test_stderr_stdin_are_single_inout_fd(self): |
| 1237 | with io.open(os.devnull, "r+") as inout: |
| 1238 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 1239 | stderr=inout, stdin=inout) |
| 1240 | p.wait() |
| 1241 | |
Gregory P. Smith | e85db2b | 2010-12-14 14:38:00 +0000 | [diff] [blame] | 1242 | def test_wait_when_sigchild_ignored(self): |
| 1243 | # NOTE: sigchild_ignore.py may not be an effective test on all OSes. |
| 1244 | sigchild_ignore = support.findfile("sigchild_ignore.py", |
| 1245 | subdir="subprocessdata") |
| 1246 | p = subprocess.Popen([sys.executable, sigchild_ignore], |
| 1247 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 1248 | stdout, stderr = p.communicate() |
| 1249 | self.assertEqual(0, p.returncode, "sigchild_ignore.py exited" |
Gregory P. Smith | a80f4fb | 2010-12-14 15:23:02 +0000 | [diff] [blame] | 1250 | " non-zero with this error:\n%s" % |
| 1251 | stderr.decode('utf8')) |
Gregory P. Smith | e85db2b | 2010-12-14 14:38:00 +0000 | [diff] [blame] | 1252 | |
Antoine Pitrou | 7b98d02 | 2011-03-19 17:04:13 +0100 | [diff] [blame] | 1253 | def test_select_unbuffered(self): |
| 1254 | # Issue #11459: bufsize=0 should really set the pipes as |
| 1255 | # unbuffered (and therefore let select() work properly). |
| 1256 | select = support.import_module("select") |
| 1257 | p = subprocess.Popen([sys.executable, "-c", |
| 1258 | 'import sys;' |
| 1259 | 'sys.stdout.write("apple")'], |
| 1260 | stdout=subprocess.PIPE, |
| 1261 | bufsize=0) |
| 1262 | f = p.stdout |
Ross Lagerwall | 17ace7a | 2011-03-26 21:21:46 +0200 | [diff] [blame] | 1263 | self.addCleanup(f.close) |
Antoine Pitrou | 7b98d02 | 2011-03-19 17:04:13 +0100 | [diff] [blame] | 1264 | try: |
| 1265 | self.assertEqual(f.read(4), b"appl") |
| 1266 | self.assertIn(f, select.select([f], [], [], 0.0)[0]) |
| 1267 | finally: |
| 1268 | p.wait() |
| 1269 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1270 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1271 | @unittest.skipUnless(mswindows, "Windows specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1272 | class Win32ProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1273 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1274 | def test_startupinfo(self): |
| 1275 | # startupinfo argument |
| 1276 | # We uses hardcoded constants, because we do not want to |
| 1277 | # depend on win32all. |
| 1278 | STARTF_USESHOWWINDOW = 1 |
| 1279 | SW_MAXIMIZE = 3 |
| 1280 | startupinfo = subprocess.STARTUPINFO() |
| 1281 | startupinfo.dwFlags = STARTF_USESHOWWINDOW |
| 1282 | startupinfo.wShowWindow = SW_MAXIMIZE |
| 1283 | # Since Python is a console process, it won't be affected |
| 1284 | # by wShowWindow, but the argument should be silently |
| 1285 | # ignored |
| 1286 | subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1287 | startupinfo=startupinfo) |
| 1288 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1289 | def test_creationflags(self): |
| 1290 | # creationflags argument |
| 1291 | CREATE_NEW_CONSOLE = 16 |
| 1292 | sys.stderr.write(" a DOS box should flash briefly ...\n") |
| 1293 | subprocess.call(sys.executable + |
| 1294 | ' -c "import time; time.sleep(0.25)"', |
| 1295 | creationflags=CREATE_NEW_CONSOLE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1296 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1297 | def test_invalid_args(self): |
| 1298 | # invalid arguments should raise ValueError |
| 1299 | self.assertRaises(ValueError, subprocess.call, |
| 1300 | [sys.executable, "-c", |
| 1301 | "import sys; sys.exit(47)"], |
| 1302 | preexec_fn=lambda: 1) |
| 1303 | self.assertRaises(ValueError, subprocess.call, |
| 1304 | [sys.executable, "-c", |
| 1305 | "import sys; sys.exit(47)"], |
| 1306 | stdout=subprocess.PIPE, |
| 1307 | close_fds=True) |
| 1308 | |
| 1309 | def test_close_fds(self): |
| 1310 | # close file descriptors |
| 1311 | rc = subprocess.call([sys.executable, "-c", |
| 1312 | "import sys; sys.exit(47)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1313 | close_fds=True) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1314 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1315 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1316 | def test_shell_sequence(self): |
| 1317 | # Run command through the shell (sequence) |
| 1318 | newenv = os.environ.copy() |
| 1319 | newenv["FRUIT"] = "physalis" |
| 1320 | p = subprocess.Popen(["set"], shell=1, |
| 1321 | stdout=subprocess.PIPE, |
| 1322 | env=newenv) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 1323 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1324 | self.assertIn(b"physalis", p.stdout.read()) |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1325 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1326 | def test_shell_string(self): |
| 1327 | # Run command through the shell (string) |
| 1328 | newenv = os.environ.copy() |
| 1329 | newenv["FRUIT"] = "physalis" |
| 1330 | p = subprocess.Popen("set", shell=1, |
| 1331 | stdout=subprocess.PIPE, |
| 1332 | env=newenv) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 1333 | self.addCleanup(p.stdout.close) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1334 | self.assertIn(b"physalis", p.stdout.read()) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1335 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1336 | def test_call_string(self): |
| 1337 | # call() function with string argument on Windows |
| 1338 | rc = subprocess.call(sys.executable + |
| 1339 | ' -c "import sys; sys.exit(47)"') |
| 1340 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1341 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1342 | def _kill_process(self, method, *args): |
| 1343 | # Some win32 buildbot raises EOFError if stdin is inherited |
Antoine Pitrou | a4024e2 | 2010-09-24 18:57:01 +0000 | [diff] [blame] | 1344 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1345 | import sys, time |
| 1346 | sys.stdout.write('x\\n') |
| 1347 | sys.stdout.flush() |
| 1348 | time.sleep(30) |
| 1349 | """], |
| 1350 | stdin=subprocess.PIPE, |
| 1351 | stdout=subprocess.PIPE, |
| 1352 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 1353 | self.addCleanup(p.stdout.close) |
| 1354 | self.addCleanup(p.stderr.close) |
| 1355 | self.addCleanup(p.stdin.close) |
Antoine Pitrou | a4024e2 | 2010-09-24 18:57:01 +0000 | [diff] [blame] | 1356 | # Wait for the interpreter to be completely initialized before |
| 1357 | # sending any signal. |
| 1358 | p.stdout.read(1) |
| 1359 | getattr(p, method)(*args) |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1360 | _, stderr = p.communicate() |
| 1361 | self.assertStderrEqual(stderr, b'') |
Antoine Pitrou | a4024e2 | 2010-09-24 18:57:01 +0000 | [diff] [blame] | 1362 | returncode = p.wait() |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1363 | self.assertNotEqual(returncode, 0) |
| 1364 | |
| 1365 | def test_send_signal(self): |
| 1366 | self._kill_process('send_signal', signal.SIGTERM) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1367 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1368 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1369 | self._kill_process('kill') |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1370 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1371 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1372 | self._kill_process('terminate') |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1373 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1374 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1375 | # The module says: |
| 1376 | # "NB This only works (and is only relevant) for UNIX." |
| 1377 | # |
| 1378 | # Actually, getoutput should work on any platform with an os.popen, but |
| 1379 | # I'll take the comment as given, and skip this suite. |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1380 | @unittest.skipUnless(os.name == 'posix', "only relevant for UNIX") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1381 | class CommandTests(unittest.TestCase): |
| 1382 | def test_getoutput(self): |
| 1383 | self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy') |
| 1384 | self.assertEqual(subprocess.getstatusoutput('echo xyzzy'), |
| 1385 | (0, 'xyzzy')) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1386 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1387 | # we use mkdtemp in the next line to create an empty directory |
| 1388 | # under our exclusive control; from that, we can invent a pathname |
| 1389 | # that we _know_ won't exist. This is guaranteed to fail. |
| 1390 | dir = None |
| 1391 | try: |
| 1392 | dir = tempfile.mkdtemp() |
| 1393 | name = os.path.join(dir, "foo") |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1394 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1395 | status, output = subprocess.getstatusoutput('cat ' + name) |
| 1396 | self.assertNotEqual(status, 0) |
| 1397 | finally: |
| 1398 | if dir is not None: |
| 1399 | os.rmdir(dir) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1400 | |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1401 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1402 | @unittest.skipUnless(getattr(subprocess, '_has_poll', False), |
| 1403 | "poll system call not supported") |
| 1404 | class ProcessTestCaseNoPoll(ProcessTestCase): |
| 1405 | def setUp(self): |
| 1406 | subprocess._has_poll = False |
| 1407 | ProcessTestCase.setUp(self) |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1408 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1409 | def tearDown(self): |
| 1410 | subprocess._has_poll = True |
| 1411 | ProcessTestCase.tearDown(self) |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1412 | |
| 1413 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1414 | @unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False), |
| 1415 | "_posixsubprocess extension module not found.") |
| 1416 | class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase): |
Gregory P. Smith | 7439e7b | 2011-05-28 09:06:02 -0700 | [diff] [blame] | 1417 | @classmethod |
| 1418 | def setUpClass(cls): |
| 1419 | global subprocess |
| 1420 | assert subprocess._posixsubprocess |
| 1421 | # Reimport subprocess while forcing _posixsubprocess to not exist. |
| 1422 | with support.check_warnings(('.*_posixsubprocess .* not being used.*', |
| 1423 | RuntimeWarning)): |
| 1424 | subprocess = support.import_fresh_module( |
| 1425 | 'subprocess', blocked=['_posixsubprocess']) |
| 1426 | assert not subprocess._posixsubprocess |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1427 | |
Gregory P. Smith | 7439e7b | 2011-05-28 09:06:02 -0700 | [diff] [blame] | 1428 | @classmethod |
| 1429 | def tearDownClass(cls): |
| 1430 | global subprocess |
| 1431 | # Reimport subprocess as it should be, restoring order to the universe. |
| 1432 | subprocess = support.import_fresh_module('subprocess') |
| 1433 | assert subprocess._posixsubprocess |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1434 | |
| 1435 | |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 1436 | class HelperFunctionTests(unittest.TestCase): |
Gregory P. Smith | af6d3b8 | 2010-03-01 02:56:44 +0000 | [diff] [blame] | 1437 | @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows") |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 1438 | def test_eintr_retry_call(self): |
| 1439 | record_calls = [] |
| 1440 | def fake_os_func(*args): |
| 1441 | record_calls.append(args) |
| 1442 | if len(record_calls) == 2: |
| 1443 | raise OSError(errno.EINTR, "fake interrupted system call") |
| 1444 | return tuple(reversed(args)) |
| 1445 | |
| 1446 | self.assertEqual((999, 256), |
| 1447 | subprocess._eintr_retry_call(fake_os_func, 256, 999)) |
| 1448 | self.assertEqual([(256, 999)], record_calls) |
| 1449 | # This time there will be an EINTR so it will loop once. |
| 1450 | self.assertEqual((666,), |
| 1451 | subprocess._eintr_retry_call(fake_os_func, 666)) |
| 1452 | self.assertEqual([(256, 999), (666,), (666,)], record_calls) |
| 1453 | |
| 1454 | |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 1455 | @unittest.skipUnless(mswindows, "Windows-specific tests") |
| 1456 | class CommandsWithSpaces (BaseTestCase): |
| 1457 | |
| 1458 | def setUp(self): |
| 1459 | super().setUp() |
| 1460 | f, fname = mkstemp(".py", "te st") |
| 1461 | self.fname = fname.lower () |
| 1462 | os.write(f, b"import sys;" |
| 1463 | b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))" |
| 1464 | ) |
| 1465 | os.close(f) |
| 1466 | |
| 1467 | def tearDown(self): |
| 1468 | os.remove(self.fname) |
| 1469 | super().tearDown() |
| 1470 | |
| 1471 | def with_spaces(self, *args, **kwargs): |
| 1472 | kwargs['stdout'] = subprocess.PIPE |
| 1473 | p = subprocess.Popen(*args, **kwargs) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 1474 | self.addCleanup(p.stdout.close) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 1475 | self.assertEqual( |
| 1476 | p.stdout.read ().decode("mbcs"), |
| 1477 | "2 [%r, 'ab cd']" % self.fname |
| 1478 | ) |
| 1479 | |
| 1480 | def test_shell_string_with_spaces(self): |
| 1481 | # call() function with string argument with spaces on Windows |
Brian Curtin | d835cf1 | 2010-08-13 20:42:57 +0000 | [diff] [blame] | 1482 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 1483 | "ab cd"), shell=1) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 1484 | |
| 1485 | def test_shell_sequence_with_spaces(self): |
| 1486 | # call() function with sequence argument with spaces on Windows |
Brian Curtin | d835cf1 | 2010-08-13 20:42:57 +0000 | [diff] [blame] | 1487 | self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 1488 | |
| 1489 | def test_noshell_string_with_spaces(self): |
| 1490 | # call() function with string argument with spaces on Windows |
| 1491 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 1492 | "ab cd")) |
| 1493 | |
| 1494 | def test_noshell_sequence_with_spaces(self): |
| 1495 | # call() function with sequence argument with spaces on Windows |
| 1496 | self.with_spaces([sys.executable, self.fname, "ab cd"]) |
| 1497 | |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 1498 | |
| 1499 | class ContextManagerTests(ProcessTestCase): |
| 1500 | |
| 1501 | def test_pipe(self): |
| 1502 | with subprocess.Popen([sys.executable, "-c", |
| 1503 | "import sys;" |
| 1504 | "sys.stdout.write('stdout');" |
| 1505 | "sys.stderr.write('stderr');"], |
| 1506 | stdout=subprocess.PIPE, |
| 1507 | stderr=subprocess.PIPE) as proc: |
| 1508 | self.assertEqual(proc.stdout.read(), b"stdout") |
| 1509 | self.assertStderrEqual(proc.stderr.read(), b"stderr") |
| 1510 | |
| 1511 | self.assertTrue(proc.stdout.closed) |
| 1512 | self.assertTrue(proc.stderr.closed) |
| 1513 | |
| 1514 | def test_returncode(self): |
| 1515 | with subprocess.Popen([sys.executable, "-c", |
| 1516 | "import sys; sys.exit(100)"]) as proc: |
Gregory P. Smith | c9557af | 2011-05-11 22:18:23 -0700 | [diff] [blame] | 1517 | pass |
| 1518 | # __exit__ calls wait(), so the returncode should be set |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 1519 | self.assertEqual(proc.returncode, 100) |
| 1520 | |
| 1521 | def test_communicate_stdin(self): |
| 1522 | with subprocess.Popen([sys.executable, "-c", |
| 1523 | "import sys;" |
| 1524 | "sys.exit(sys.stdin.read() == 'context')"], |
| 1525 | stdin=subprocess.PIPE) as proc: |
| 1526 | proc.communicate(b"context") |
| 1527 | self.assertEqual(proc.returncode, 1) |
| 1528 | |
| 1529 | def test_invalid_args(self): |
| 1530 | with self.assertRaises(EnvironmentError) as c: |
| 1531 | with subprocess.Popen(['nonexisting_i_hope'], |
| 1532 | stdout=subprocess.PIPE, |
| 1533 | stderr=subprocess.PIPE) as proc: |
| 1534 | pass |
| 1535 | |
| 1536 | if c.exception.errno != errno.ENOENT: # ignore "no such file" |
| 1537 | raise c.exception |
| 1538 | |
| 1539 | |
Gregory P. Smith | 961e0e8 | 2011-03-15 15:43:39 -0400 | [diff] [blame] | 1540 | def test_main(): |
| 1541 | unit_tests = (ProcessTestCase, |
| 1542 | POSIXProcessTestCase, |
| 1543 | Win32ProcessTestCase, |
| 1544 | ProcessTestCasePOSIXPurePython, |
| 1545 | CommandTests, |
| 1546 | ProcessTestCaseNoPoll, |
| 1547 | HelperFunctionTests, |
| 1548 | CommandsWithSpaces, |
| 1549 | ContextManagerTests) |
| 1550 | |
| 1551 | support.run_unittest(*unit_tests) |
| 1552 | support.reap_children() |
| 1553 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1554 | if __name__ == "__main__": |
Gregory P. Smith | e14e9c2 | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 1555 | unittest.main() |