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