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 |
| 6 | import os |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 7 | import errno |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 8 | import tempfile |
| 9 | import time |
Tim Peters | 3761e8d | 2004-10-13 04:07:12 +0000 | [diff] [blame] | 10 | import re |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 11 | import sysconfig |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 12 | try: |
| 13 | import gc |
| 14 | except ImportError: |
| 15 | gc = None |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 16 | |
| 17 | mswindows = (sys.platform == "win32") |
| 18 | |
| 19 | # |
| 20 | # Depends on the following external programs: Python |
| 21 | # |
| 22 | |
| 23 | if mswindows: |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 24 | SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), ' |
| 25 | 'os.O_BINARY);') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 26 | else: |
| 27 | SETBINARY = '' |
| 28 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 29 | |
| 30 | try: |
| 31 | mkstemp = tempfile.mkstemp |
| 32 | except AttributeError: |
| 33 | # tempfile.mkstemp is not available |
| 34 | def mkstemp(): |
| 35 | """Replacement for mkstemp, calling mktemp.""" |
| 36 | fname = tempfile.mktemp() |
| 37 | return os.open(fname, os.O_RDWR|os.O_CREAT), fname |
| 38 | |
Tim Peters | 3761e8d | 2004-10-13 04:07:12 +0000 | [diff] [blame] | 39 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 40 | class BaseTestCase(unittest.TestCase): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 41 | def setUp(self): |
| 42 | # Try to minimize the number of children we have so this test |
| 43 | # doesn't crash on some buildbots (Alphas in particular). |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 44 | support.reap_children() |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 45 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 46 | def tearDown(self): |
| 47 | for inst in subprocess._active: |
| 48 | inst.wait() |
| 49 | subprocess._cleanup() |
| 50 | self.assertFalse(subprocess._active, "subprocess._active not empty") |
| 51 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 52 | def assertStderrEqual(self, stderr, expected, msg=None): |
| 53 | # In a debug build, stuff like "[6580 refs]" is printed to stderr at |
| 54 | # shutdown time. That frustrates tests trying to check stderr produced |
| 55 | # from a spawned Python process. |
Antoine Pitrou | 62f68ed | 2010-08-04 11:48:56 +0000 | [diff] [blame] | 56 | actual = support.strip_python_stderr(stderr) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 57 | self.assertEqual(actual, expected, msg) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 58 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 59 | |
| 60 | class ProcessTestCase(BaseTestCase): |
| 61 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 62 | def test_call_seq(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 63 | # call() function with sequence argument |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 64 | rc = subprocess.call([sys.executable, "-c", |
| 65 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 66 | self.assertEqual(rc, 47) |
| 67 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 68 | def test_check_call_zero(self): |
| 69 | # check_call() function with zero return code |
| 70 | rc = subprocess.check_call([sys.executable, "-c", |
| 71 | "import sys; sys.exit(0)"]) |
| 72 | self.assertEqual(rc, 0) |
| 73 | |
| 74 | def test_check_call_nonzero(self): |
| 75 | # check_call() function with non-zero return code |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 76 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 77 | subprocess.check_call([sys.executable, "-c", |
| 78 | "import sys; sys.exit(47)"]) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 79 | self.assertEqual(c.exception.returncode, 47) |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 80 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 81 | def test_check_output(self): |
| 82 | # check_output() function with zero return code |
| 83 | output = subprocess.check_output( |
| 84 | [sys.executable, "-c", "print('BDFL')"]) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 85 | self.assertIn(b'BDFL', output) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 86 | |
| 87 | def test_check_output_nonzero(self): |
| 88 | # check_call() function with non-zero return code |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 89 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 90 | subprocess.check_output( |
| 91 | [sys.executable, "-c", "import sys; sys.exit(5)"]) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 92 | self.assertEqual(c.exception.returncode, 5) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 93 | |
| 94 | def test_check_output_stderr(self): |
| 95 | # check_output() function stderr redirected to stdout |
| 96 | output = subprocess.check_output( |
| 97 | [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"], |
| 98 | stderr=subprocess.STDOUT) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 99 | self.assertIn(b'BDFL', output) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 100 | |
| 101 | def test_check_output_stdout_arg(self): |
| 102 | # check_output() function stderr redirected to stdout |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 103 | with self.assertRaises(ValueError) as c: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 104 | output = subprocess.check_output( |
| 105 | [sys.executable, "-c", "print('will not be run')"], |
| 106 | stdout=sys.stdout) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 107 | self.fail("Expected ValueError when stdout arg supplied.") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 108 | self.assertIn('stdout', c.exception.args[0]) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 109 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 110 | def test_call_kwargs(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 111 | # call() function with keyword args |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 112 | newenv = os.environ.copy() |
| 113 | newenv["FRUIT"] = "banana" |
| 114 | rc = subprocess.call([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 115 | 'import sys, os;' |
| 116 | 'sys.exit(os.getenv("FRUIT")=="banana")'], |
| 117 | env=newenv) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 118 | self.assertEqual(rc, 1) |
| 119 | |
| 120 | def test_stdin_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 121 | # .stdin is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 122 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 123 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 124 | p.wait() |
| 125 | self.assertEqual(p.stdin, None) |
| 126 | |
| 127 | def test_stdout_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 128 | # .stdout is None when not redirected |
Tim Peters | 29b6b4f | 2004-10-13 03:43:40 +0000 | [diff] [blame] | 129 | p = subprocess.Popen([sys.executable, "-c", |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 130 | 'print(" this bit of output is from a ' |
Tim Peters | 4052fe5 | 2004-10-13 03:29:54 +0000 | [diff] [blame] | 131 | 'test of stdout in a different ' |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 132 | 'process ...")'], |
Tim Peters | 4052fe5 | 2004-10-13 03:29:54 +0000 | [diff] [blame] | 133 | stdin=subprocess.PIPE, stderr=subprocess.PIPE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 134 | p.wait() |
| 135 | self.assertEqual(p.stdout, None) |
| 136 | |
| 137 | def test_stderr_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 138 | # .stderr is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 139 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 140 | stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
| 141 | p.wait() |
| 142 | self.assertEqual(p.stderr, None) |
| 143 | |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 144 | def test_executable_with_cwd(self): |
Florent Xicluna | 1d1ab97 | 2010-03-11 01:53:10 +0000 | [diff] [blame] | 145 | python_dir = os.path.dirname(os.path.realpath(sys.executable)) |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 146 | p = subprocess.Popen(["somethingyoudonthave", "-c", |
| 147 | "import sys; sys.exit(47)"], |
| 148 | executable=sys.executable, cwd=python_dir) |
| 149 | p.wait() |
| 150 | self.assertEqual(p.returncode, 47) |
| 151 | |
| 152 | @unittest.skipIf(sysconfig.is_python_build(), |
| 153 | "need an installed Python. See #7774") |
| 154 | def test_executable_without_cwd(self): |
| 155 | # For a normal installation, it should work without 'cwd' |
| 156 | # argument. For test runs in the build directory, see #7774. |
| 157 | p = subprocess.Popen(["somethingyoudonthave", "-c", |
| 158 | "import sys; sys.exit(47)"], |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 159 | executable=sys.executable) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 160 | p.wait() |
| 161 | self.assertEqual(p.returncode, 47) |
| 162 | |
| 163 | def test_stdin_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 164 | # stdin redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 165 | p = subprocess.Popen([sys.executable, "-c", |
| 166 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 167 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 168 | p.stdin.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 169 | p.stdin.close() |
| 170 | p.wait() |
| 171 | self.assertEqual(p.returncode, 1) |
| 172 | |
| 173 | def test_stdin_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 174 | # stdin is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 175 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 176 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 177 | d = tf.fileno() |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 178 | os.write(d, b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 179 | os.lseek(d, 0, 0) |
| 180 | p = subprocess.Popen([sys.executable, "-c", |
| 181 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 182 | stdin=d) |
| 183 | p.wait() |
| 184 | self.assertEqual(p.returncode, 1) |
| 185 | |
| 186 | def test_stdin_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 187 | # stdin is set to open file object |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 188 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 189 | self.addCleanup(tf.close) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 190 | tf.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 191 | tf.seek(0) |
| 192 | p = subprocess.Popen([sys.executable, "-c", |
| 193 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 194 | stdin=tf) |
| 195 | p.wait() |
| 196 | self.assertEqual(p.returncode, 1) |
| 197 | |
| 198 | def test_stdout_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 199 | # stdout redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 200 | p = subprocess.Popen([sys.executable, "-c", |
| 201 | 'import sys; sys.stdout.write("orange")'], |
| 202 | stdout=subprocess.PIPE) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 203 | self.assertEqual(p.stdout.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 204 | |
| 205 | def test_stdout_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 206 | # stdout is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 207 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 208 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 209 | d = tf.fileno() |
| 210 | p = subprocess.Popen([sys.executable, "-c", |
| 211 | 'import sys; sys.stdout.write("orange")'], |
| 212 | stdout=d) |
| 213 | p.wait() |
| 214 | os.lseek(d, 0, 0) |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 215 | self.assertEqual(os.read(d, 1024), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 216 | |
| 217 | def test_stdout_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 218 | # stdout is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 219 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 220 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 221 | p = subprocess.Popen([sys.executable, "-c", |
| 222 | 'import sys; sys.stdout.write("orange")'], |
| 223 | stdout=tf) |
| 224 | p.wait() |
| 225 | tf.seek(0) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 226 | self.assertEqual(tf.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 227 | |
| 228 | def test_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 229 | # stderr redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 230 | p = subprocess.Popen([sys.executable, "-c", |
| 231 | 'import sys; sys.stderr.write("strawberry")'], |
| 232 | stderr=subprocess.PIPE) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 233 | self.assertStderrEqual(p.stderr.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 234 | |
| 235 | def test_stderr_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 236 | # stderr is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 237 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 238 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 239 | d = tf.fileno() |
| 240 | p = subprocess.Popen([sys.executable, "-c", |
| 241 | 'import sys; sys.stderr.write("strawberry")'], |
| 242 | stderr=d) |
| 243 | p.wait() |
| 244 | os.lseek(d, 0, 0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 245 | self.assertStderrEqual(os.read(d, 1024), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 246 | |
| 247 | def test_stderr_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 248 | # stderr is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 249 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 250 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 251 | p = subprocess.Popen([sys.executable, "-c", |
| 252 | 'import sys; sys.stderr.write("strawberry")'], |
| 253 | stderr=tf) |
| 254 | p.wait() |
| 255 | tf.seek(0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 256 | self.assertStderrEqual(tf.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 257 | |
| 258 | def test_stdout_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 259 | # capture stdout and stderr to the same pipe |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 260 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 261 | 'import sys;' |
| 262 | 'sys.stdout.write("apple");' |
| 263 | 'sys.stdout.flush();' |
| 264 | 'sys.stderr.write("orange")'], |
| 265 | stdout=subprocess.PIPE, |
| 266 | stderr=subprocess.STDOUT) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 267 | self.assertStderrEqual(p.stdout.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 268 | |
| 269 | def test_stdout_stderr_file(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 270 | # capture stdout and stderr to the same open file |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 271 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 272 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 273 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 274 | 'import sys;' |
| 275 | 'sys.stdout.write("apple");' |
| 276 | 'sys.stdout.flush();' |
| 277 | 'sys.stderr.write("orange")'], |
| 278 | stdout=tf, |
| 279 | stderr=tf) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 280 | p.wait() |
| 281 | tf.seek(0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 282 | self.assertStderrEqual(tf.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 283 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 284 | def test_stdout_filedes_of_stdout(self): |
| 285 | # stdout is set to 1 (#1531862). |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 286 | 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] | 287 | rc = subprocess.call([sys.executable, "-c", cmd], stdout=1) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 288 | self.assertEqual(rc, 2) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 289 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 290 | def test_cwd(self): |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 291 | tmpdir = tempfile.gettempdir() |
Peter Astrand | 195404f | 2004-11-12 15:51:48 +0000 | [diff] [blame] | 292 | # We cannot use os.path.realpath to canonicalize the path, |
| 293 | # since it doesn't expand Tru64 {memb} strings. See bug 1063571. |
| 294 | cwd = os.getcwd() |
| 295 | os.chdir(tmpdir) |
| 296 | tmpdir = os.getcwd() |
| 297 | os.chdir(cwd) |
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,os;' |
| 300 | 'sys.stdout.write(os.getcwd())'], |
| 301 | stdout=subprocess.PIPE, |
| 302 | cwd=tmpdir) |
Fredrik Lundh | 59c0559 | 2004-10-13 06:55:40 +0000 | [diff] [blame] | 303 | normcase = os.path.normcase |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 304 | self.assertEqual(normcase(p.stdout.read().decode("utf-8")), |
| 305 | normcase(tmpdir)) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 306 | |
| 307 | def test_env(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 308 | newenv = os.environ.copy() |
| 309 | newenv["FRUIT"] = "orange" |
| 310 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 311 | 'import sys,os;' |
| 312 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 313 | stdout=subprocess.PIPE, |
| 314 | env=newenv) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 315 | self.assertEqual(p.stdout.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 316 | |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 317 | def test_communicate_stdin(self): |
| 318 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 319 | 'import sys;' |
| 320 | 'sys.exit(sys.stdin.read() == "pear")'], |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 321 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 322 | p.communicate(b"pear") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 323 | self.assertEqual(p.returncode, 1) |
| 324 | |
| 325 | def test_communicate_stdout(self): |
| 326 | p = subprocess.Popen([sys.executable, "-c", |
| 327 | 'import sys; sys.stdout.write("pineapple")'], |
| 328 | stdout=subprocess.PIPE) |
| 329 | (stdout, stderr) = p.communicate() |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 330 | self.assertEqual(stdout, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 331 | self.assertEqual(stderr, None) |
| 332 | |
| 333 | def test_communicate_stderr(self): |
| 334 | p = subprocess.Popen([sys.executable, "-c", |
| 335 | 'import sys; sys.stderr.write("pineapple")'], |
| 336 | stderr=subprocess.PIPE) |
| 337 | (stdout, stderr) = p.communicate() |
| 338 | self.assertEqual(stdout, None) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 339 | self.assertStderrEqual(stderr, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 340 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 341 | def test_communicate(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 342 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 343 | 'import sys,os;' |
| 344 | 'sys.stderr.write("pineapple");' |
| 345 | 'sys.stdout.write(sys.stdin.read())'], |
| 346 | stdin=subprocess.PIPE, |
| 347 | stdout=subprocess.PIPE, |
| 348 | stderr=subprocess.PIPE) |
Georg Brandl | 1abcbf8 | 2008-07-01 19:28:43 +0000 | [diff] [blame] | 349 | (stdout, stderr) = p.communicate(b"banana") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 350 | self.assertEqual(stdout, b"banana") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 351 | self.assertStderrEqual(stderr, b"pineapple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 352 | |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 353 | # This test is Linux specific for simplicity to at least have |
| 354 | # some coverage. It is not a platform specific bug. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 355 | @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()), |
| 356 | "Linux specific") |
| 357 | # Test for the fd leak reported in http://bugs.python.org/issue2791. |
| 358 | def test_communicate_pipe_fd_leak(self): |
| 359 | fd_directory = '/proc/%d/fd' % os.getpid() |
| 360 | num_fds_before_popen = len(os.listdir(fd_directory)) |
| 361 | p = subprocess.Popen([sys.executable, "-c", "print()"], |
| 362 | stdout=subprocess.PIPE) |
| 363 | p.communicate() |
| 364 | num_fds_after_communicate = len(os.listdir(fd_directory)) |
| 365 | del p |
| 366 | num_fds_after_destruction = len(os.listdir(fd_directory)) |
| 367 | self.assertEqual(num_fds_before_popen, num_fds_after_destruction) |
| 368 | self.assertEqual(num_fds_before_popen, num_fds_after_communicate) |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 369 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 370 | def test_communicate_returns(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 371 | # communicate() should return None if no redirection is active |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 372 | p = subprocess.Popen([sys.executable, "-c", |
| 373 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 374 | (stdout, stderr) = p.communicate() |
| 375 | self.assertEqual(stdout, None) |
| 376 | self.assertEqual(stderr, None) |
| 377 | |
| 378 | def test_communicate_pipe_buf(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 379 | # communicate() with writes larger than pipe_buf |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 380 | # This test will probably deadlock rather than fail, if |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 381 | # communicate() does not work properly. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 382 | x, y = os.pipe() |
| 383 | if mswindows: |
| 384 | pipe_buf = 512 |
| 385 | else: |
| 386 | pipe_buf = os.fpathconf(x, "PC_PIPE_BUF") |
| 387 | os.close(x) |
| 388 | os.close(y) |
| 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.stdout.write(sys.stdin.read(47));' |
| 392 | 'sys.stderr.write("xyz"*%d);' |
| 393 | 'sys.stdout.write(sys.stdin.read())' % pipe_buf], |
| 394 | stdin=subprocess.PIPE, |
| 395 | stdout=subprocess.PIPE, |
| 396 | stderr=subprocess.PIPE) |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 397 | string_to_write = b"abc"*pipe_buf |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 398 | (stdout, stderr) = p.communicate(string_to_write) |
| 399 | self.assertEqual(stdout, string_to_write) |
| 400 | |
| 401 | def test_writes_before_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 402 | # stdin.write before communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 403 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 404 | 'import sys,os;' |
| 405 | 'sys.stdout.write(sys.stdin.read())'], |
| 406 | stdin=subprocess.PIPE, |
| 407 | stdout=subprocess.PIPE, |
| 408 | stderr=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 409 | p.stdin.write(b"banana") |
| 410 | (stdout, stderr) = p.communicate(b"split") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 411 | self.assertEqual(stdout, b"bananasplit") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 412 | self.assertStderrEqual(stderr, b"") |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 413 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 414 | def test_universal_newlines(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 415 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 416 | 'import sys,os;' + SETBINARY + |
| 417 | 'sys.stdout.write("line1\\n");' |
| 418 | 'sys.stdout.flush();' |
| 419 | 'sys.stdout.write("line2\\n");' |
| 420 | 'sys.stdout.flush();' |
| 421 | 'sys.stdout.write("line3\\r\\n");' |
| 422 | 'sys.stdout.flush();' |
| 423 | 'sys.stdout.write("line4\\r");' |
| 424 | 'sys.stdout.flush();' |
| 425 | 'sys.stdout.write("\\nline5");' |
| 426 | 'sys.stdout.flush();' |
| 427 | 'sys.stdout.write("\\nline6");'], |
| 428 | stdout=subprocess.PIPE, |
| 429 | universal_newlines=1) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 430 | stdout = p.stdout.read() |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 431 | self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 432 | |
| 433 | def test_universal_newlines_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 434 | # universal newlines through communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 435 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 436 | 'import sys,os;' + SETBINARY + |
| 437 | 'sys.stdout.write("line1\\n");' |
| 438 | 'sys.stdout.flush();' |
| 439 | 'sys.stdout.write("line2\\n");' |
| 440 | 'sys.stdout.flush();' |
| 441 | 'sys.stdout.write("line3\\r\\n");' |
| 442 | 'sys.stdout.flush();' |
| 443 | 'sys.stdout.write("line4\\r");' |
| 444 | 'sys.stdout.flush();' |
| 445 | 'sys.stdout.write("\\nline5");' |
| 446 | 'sys.stdout.flush();' |
| 447 | 'sys.stdout.write("\\nline6");'], |
| 448 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 449 | universal_newlines=1) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 450 | (stdout, stderr) = p.communicate() |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 451 | self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 452 | |
| 453 | def test_no_leaking(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 454 | # Make sure we leak no resources |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 455 | if not mswindows: |
Peter Astrand | f7f1bb7 | 2005-03-03 20:47:37 +0000 | [diff] [blame] | 456 | max_handles = 1026 # too much for most UNIX systems |
| 457 | else: |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 458 | max_handles = 2050 # too much for (at least some) Windows setups |
| 459 | handles = [] |
| 460 | try: |
| 461 | for i in range(max_handles): |
| 462 | try: |
| 463 | handles.append(os.open(support.TESTFN, |
| 464 | os.O_WRONLY | os.O_CREAT)) |
| 465 | except OSError as e: |
| 466 | if e.errno != errno.EMFILE: |
| 467 | raise |
| 468 | break |
| 469 | else: |
| 470 | self.skipTest("failed to reach the file descriptor limit " |
| 471 | "(tried %d)" % max_handles) |
| 472 | # Close a couple of them (should be enough for a subprocess) |
| 473 | for i in range(10): |
| 474 | os.close(handles.pop()) |
| 475 | # Loop creating some subprocesses. If one of them leaks some fds, |
| 476 | # the next loop iteration will fail by reaching the max fd limit. |
| 477 | for i in range(15): |
| 478 | p = subprocess.Popen([sys.executable, "-c", |
| 479 | "import sys;" |
| 480 | "sys.stdout.write(sys.stdin.read())"], |
| 481 | stdin=subprocess.PIPE, |
| 482 | stdout=subprocess.PIPE, |
| 483 | stderr=subprocess.PIPE) |
| 484 | data = p.communicate(b"lime")[0] |
| 485 | self.assertEqual(data, b"lime") |
| 486 | finally: |
| 487 | for h in handles: |
| 488 | os.close(h) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 489 | |
| 490 | def test_list2cmdline(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 491 | self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']), |
| 492 | '"a b c" d e') |
| 493 | self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']), |
| 494 | 'ab\\"c \\ d') |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 495 | self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']), |
| 496 | 'ab\\"c " \\\\" d') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 497 | self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']), |
| 498 | 'a\\\\\\b "de fg" h') |
| 499 | self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']), |
| 500 | 'a\\\\\\"b c d') |
| 501 | self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']), |
| 502 | '"a\\\\b c" d e') |
| 503 | self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']), |
| 504 | '"a\\\\b\\ c" d e') |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 505 | self.assertEqual(subprocess.list2cmdline(['ab', '']), |
| 506 | 'ab ""') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 507 | |
| 508 | |
| 509 | def test_poll(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 510 | p = subprocess.Popen([sys.executable, |
Tim Peters | 29b6b4f | 2004-10-13 03:43:40 +0000 | [diff] [blame] | 511 | "-c", "import time; time.sleep(1)"]) |
| 512 | count = 0 |
| 513 | while p.poll() is None: |
| 514 | time.sleep(0.1) |
| 515 | count += 1 |
| 516 | # We expect that the poll loop probably went around about 10 times, |
| 517 | # but, based on system scheduling we can't control, it's possible |
| 518 | # poll() never returned None. It "should be" very rare that it |
| 519 | # didn't go around at least twice. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 520 | self.assertGreaterEqual(count, 2) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 521 | # Subsequent invocations should just return the returncode |
| 522 | self.assertEqual(p.poll(), 0) |
| 523 | |
| 524 | |
| 525 | def test_wait(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 526 | p = subprocess.Popen([sys.executable, |
| 527 | "-c", "import time; time.sleep(2)"]) |
| 528 | self.assertEqual(p.wait(), 0) |
| 529 | # Subsequent invocations should just return the returncode |
| 530 | self.assertEqual(p.wait(), 0) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 531 | |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 532 | |
| 533 | def test_invalid_bufsize(self): |
| 534 | # an invalid type of the bufsize argument should raise |
| 535 | # TypeError. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 536 | with self.assertRaises(TypeError): |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 537 | subprocess.Popen([sys.executable, "-c", "pass"], "orange") |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 538 | |
Guido van Rossum | 46a05a7 | 2007-06-07 21:56:45 +0000 | [diff] [blame] | 539 | def test_bufsize_is_none(self): |
| 540 | # bufsize=None should be the same as bufsize=0. |
| 541 | p = subprocess.Popen([sys.executable, "-c", "pass"], None) |
| 542 | self.assertEqual(p.wait(), 0) |
| 543 | # Again with keyword arg |
| 544 | p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None) |
| 545 | self.assertEqual(p.wait(), 0) |
| 546 | |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 547 | def test_leaking_fds_on_error(self): |
| 548 | # see bug #5179: Popen leaks file descriptors to PIPEs if |
| 549 | # the child fails to execute; this will eventually exhaust |
| 550 | # the maximum number of open fds. 1024 seems a very common |
| 551 | # value for that limit, but Windows has 2048, so we loop |
| 552 | # 1024 times (each call leaked two fds). |
| 553 | for i in range(1024): |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 554 | # Windows raises IOError. Others raise OSError. |
| 555 | with self.assertRaises(EnvironmentError) as c: |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 556 | subprocess.Popen(['nonexisting_i_hope'], |
| 557 | stdout=subprocess.PIPE, |
| 558 | stderr=subprocess.PIPE) |
Antoine Pitrou | 679e0f2 | 2010-09-18 17:56:02 +0000 | [diff] [blame] | 559 | if c.exception.errno != errno.ENOENT: # ignore "no such file" |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 560 | raise c.exception |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 561 | |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 562 | def test_issue8780(self): |
| 563 | # Ensure that stdout is inherited from the parent |
| 564 | # if stdout=PIPE is not used |
| 565 | code = ';'.join(( |
| 566 | 'import subprocess, sys', |
| 567 | 'retcode = subprocess.call(' |
| 568 | "[sys.executable, '-c', 'print(\"Hello World!\")'])", |
| 569 | 'assert retcode == 0')) |
| 570 | output = subprocess.check_output([sys.executable, '-c', code]) |
| 571 | self.assert_(output.startswith(b'Hello World!'), ascii(output)) |
| 572 | |
Tim Golden | af5ac39 | 2010-08-06 13:03:56 +0000 | [diff] [blame] | 573 | def test_handles_closed_on_exception(self): |
| 574 | # If CreateProcess exits with an error, ensure the |
| 575 | # duplicate output handles are released |
| 576 | ifhandle, ifname = mkstemp() |
| 577 | ofhandle, ofname = mkstemp() |
| 578 | efhandle, efname = mkstemp() |
| 579 | try: |
| 580 | subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle, |
| 581 | stderr=efhandle) |
| 582 | except OSError: |
| 583 | os.close(ifhandle) |
| 584 | os.remove(ifname) |
| 585 | os.close(ofhandle) |
| 586 | os.remove(ofname) |
| 587 | os.close(efhandle) |
| 588 | os.remove(efname) |
| 589 | self.assertFalse(os.path.exists(ifname)) |
| 590 | self.assertFalse(os.path.exists(ofname)) |
| 591 | self.assertFalse(os.path.exists(efname)) |
| 592 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 593 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 594 | # context manager |
| 595 | class _SuppressCoreFiles(object): |
| 596 | """Try to prevent core files from being created.""" |
| 597 | old_limit = None |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 598 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 599 | def __enter__(self): |
| 600 | """Try to save previous ulimit, then set it to (0, 0).""" |
| 601 | try: |
| 602 | import resource |
| 603 | self.old_limit = resource.getrlimit(resource.RLIMIT_CORE) |
| 604 | resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) |
| 605 | except (ImportError, ValueError, resource.error): |
| 606 | pass |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 607 | |
Ronald Oussoren | 102d11a | 2010-07-23 09:50:05 +0000 | [diff] [blame] | 608 | if sys.platform == 'darwin': |
| 609 | # Check if the 'Crash Reporter' on OSX was configured |
| 610 | # in 'Developer' mode and warn that it will get triggered |
| 611 | # when it is. |
| 612 | # |
| 613 | # This assumes that this context manager is used in tests |
| 614 | # that might trigger the next manager. |
| 615 | value = subprocess.Popen(['/usr/bin/defaults', 'read', |
| 616 | 'com.apple.CrashReporter', 'DialogType'], |
| 617 | stdout=subprocess.PIPE).communicate()[0] |
| 618 | if value.strip() == b'developer': |
| 619 | print("this tests triggers the Crash Reporter, " |
| 620 | "that is intentional", end='') |
| 621 | sys.stdout.flush() |
| 622 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 623 | def __exit__(self, *args): |
| 624 | """Return core file behavior to default.""" |
| 625 | if self.old_limit is None: |
| 626 | return |
| 627 | try: |
| 628 | import resource |
| 629 | resource.setrlimit(resource.RLIMIT_CORE, self.old_limit) |
| 630 | except (ImportError, ValueError, resource.error): |
| 631 | pass |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 632 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 633 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 634 | @unittest.skipIf(mswindows, "POSIX specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 635 | class POSIXProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 636 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 637 | def test_exceptions(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 638 | nonexistent_dir = "/_this/pa.th/does/not/exist" |
| 639 | try: |
| 640 | os.chdir(nonexistent_dir) |
| 641 | except OSError as e: |
| 642 | # This avoids hard coding the errno value or the OS perror() |
| 643 | # string and instead capture the exception that we want to see |
| 644 | # below for comparison. |
| 645 | desired_exception = e |
| 646 | else: |
| 647 | self.fail("chdir to nonexistant directory %s succeeded." % |
| 648 | nonexistent_dir) |
| 649 | |
| 650 | # Error in the child re-raised in the parent. |
| 651 | try: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 652 | p = subprocess.Popen([sys.executable, "-c", ""], |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 653 | cwd=nonexistent_dir) |
| 654 | except OSError as e: |
| 655 | # Test that the child process chdir failure actually makes |
| 656 | # it up to the parent process as the correct exception. |
| 657 | self.assertEqual(desired_exception.errno, e.errno) |
| 658 | self.assertEqual(desired_exception.strerror, e.strerror) |
| 659 | else: |
| 660 | self.fail("Expected OSError: %s" % desired_exception) |
| 661 | |
| 662 | def test_restore_signals(self): |
| 663 | # Code coverage for both values of restore_signals to make sure it |
| 664 | # at least does not blow up. |
| 665 | # A test for behavior would be complex. Contributions welcome. |
| 666 | subprocess.call([sys.executable, "-c", ""], restore_signals=True) |
| 667 | subprocess.call([sys.executable, "-c", ""], restore_signals=False) |
| 668 | |
| 669 | def test_start_new_session(self): |
| 670 | # For code coverage of calling setsid(). We don't care if we get an |
| 671 | # EPERM error from it depending on the test execution environment, that |
| 672 | # still indicates that it was called. |
| 673 | try: |
| 674 | output = subprocess.check_output( |
| 675 | [sys.executable, "-c", |
| 676 | "import os; print(os.getpgid(os.getpid()))"], |
| 677 | start_new_session=True) |
| 678 | except OSError as e: |
| 679 | if e.errno != errno.EPERM: |
| 680 | raise |
| 681 | else: |
| 682 | parent_pgid = os.getpgid(os.getpid()) |
| 683 | child_pgid = int(output) |
| 684 | self.assertNotEqual(parent_pgid, child_pgid) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 685 | |
| 686 | def test_run_abort(self): |
| 687 | # returncode handles signal termination |
| 688 | with _SuppressCoreFiles(): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 689 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 690 | 'import os; os.abort()']) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 691 | p.wait() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 692 | self.assertEqual(-p.returncode, signal.SIGABRT) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 693 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 694 | def test_preexec(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 695 | # DISCLAIMER: Setting environment variables is *not* a good use |
| 696 | # of a preexec_fn. This is merely a test. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 697 | p = subprocess.Popen([sys.executable, "-c", |
| 698 | 'import sys,os;' |
| 699 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 700 | stdout=subprocess.PIPE, |
| 701 | preexec_fn=lambda: os.putenv("FRUIT", "apple")) |
| 702 | self.assertEqual(p.stdout.read(), b"apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 703 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 704 | def test_preexec_exception(self): |
| 705 | def raise_it(): |
| 706 | raise ValueError("What if two swallows carried a coconut?") |
| 707 | try: |
| 708 | p = subprocess.Popen([sys.executable, "-c", ""], |
| 709 | preexec_fn=raise_it) |
| 710 | except RuntimeError as e: |
| 711 | self.assertTrue( |
| 712 | subprocess._posixsubprocess, |
| 713 | "Expected a ValueError from the preexec_fn") |
| 714 | except ValueError as e: |
| 715 | self.assertIn("coconut", e.args[0]) |
| 716 | else: |
| 717 | self.fail("Exception raised by preexec_fn did not make it " |
| 718 | "to the parent process.") |
| 719 | |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 720 | @unittest.skipUnless(gc, "Requires a gc module.") |
| 721 | def test_preexec_gc_module_failure(self): |
| 722 | # This tests the code that disables garbage collection if the child |
| 723 | # process will execute any Python. |
| 724 | def raise_runtime_error(): |
| 725 | raise RuntimeError("this shouldn't escape") |
| 726 | enabled = gc.isenabled() |
| 727 | orig_gc_disable = gc.disable |
| 728 | orig_gc_isenabled = gc.isenabled |
| 729 | try: |
| 730 | gc.disable() |
| 731 | self.assertFalse(gc.isenabled()) |
| 732 | subprocess.call([sys.executable, '-c', ''], |
| 733 | preexec_fn=lambda: None) |
| 734 | self.assertFalse(gc.isenabled(), |
| 735 | "Popen enabled gc when it shouldn't.") |
| 736 | |
| 737 | gc.enable() |
| 738 | self.assertTrue(gc.isenabled()) |
| 739 | subprocess.call([sys.executable, '-c', ''], |
| 740 | preexec_fn=lambda: None) |
| 741 | self.assertTrue(gc.isenabled(), "Popen left gc disabled.") |
| 742 | |
| 743 | gc.disable = raise_runtime_error |
| 744 | self.assertRaises(RuntimeError, subprocess.Popen, |
| 745 | [sys.executable, '-c', ''], |
| 746 | preexec_fn=lambda: None) |
| 747 | |
| 748 | del gc.isenabled # force an AttributeError |
| 749 | self.assertRaises(AttributeError, subprocess.Popen, |
| 750 | [sys.executable, '-c', ''], |
| 751 | preexec_fn=lambda: None) |
| 752 | finally: |
| 753 | gc.disable = orig_gc_disable |
| 754 | gc.isenabled = orig_gc_isenabled |
| 755 | if not enabled: |
| 756 | gc.disable() |
| 757 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 758 | def test_args_string(self): |
| 759 | # args is a string |
| 760 | fd, fname = mkstemp() |
| 761 | # reopen in text mode |
Victor Stinner | f6782ac | 2010-10-16 23:46:43 +0000 | [diff] [blame] | 762 | with open(fd, "w", errors="surrogateescape") as fobj: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 763 | fobj.write("#!/bin/sh\n") |
| 764 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 765 | sys.executable) |
| 766 | os.chmod(fname, 0o700) |
| 767 | p = subprocess.Popen(fname) |
| 768 | p.wait() |
| 769 | os.remove(fname) |
| 770 | self.assertEqual(p.returncode, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 771 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 772 | def test_invalid_args(self): |
| 773 | # invalid arguments should raise ValueError |
| 774 | self.assertRaises(ValueError, subprocess.call, |
| 775 | [sys.executable, "-c", |
| 776 | "import sys; sys.exit(47)"], |
| 777 | startupinfo=47) |
| 778 | self.assertRaises(ValueError, subprocess.call, |
| 779 | [sys.executable, "-c", |
| 780 | "import sys; sys.exit(47)"], |
| 781 | creationflags=47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 782 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 783 | def test_shell_sequence(self): |
| 784 | # Run command through the shell (sequence) |
| 785 | newenv = os.environ.copy() |
| 786 | newenv["FRUIT"] = "apple" |
| 787 | p = subprocess.Popen(["echo $FRUIT"], shell=1, |
| 788 | stdout=subprocess.PIPE, |
| 789 | env=newenv) |
| 790 | 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] | 791 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 792 | def test_shell_string(self): |
| 793 | # Run command through the shell (string) |
| 794 | newenv = os.environ.copy() |
| 795 | newenv["FRUIT"] = "apple" |
| 796 | p = subprocess.Popen("echo $FRUIT", shell=1, |
| 797 | stdout=subprocess.PIPE, |
| 798 | env=newenv) |
| 799 | 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] | 800 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 801 | def test_call_string(self): |
| 802 | # call() function with string argument on UNIX |
| 803 | fd, fname = mkstemp() |
| 804 | # reopen in text mode |
Victor Stinner | f6782ac | 2010-10-16 23:46:43 +0000 | [diff] [blame] | 805 | with open(fd, "w", errors="surrogateescape") as fobj: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 806 | fobj.write("#!/bin/sh\n") |
| 807 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 808 | sys.executable) |
| 809 | os.chmod(fname, 0o700) |
| 810 | rc = subprocess.call(fname) |
| 811 | os.remove(fname) |
| 812 | self.assertEqual(rc, 47) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 813 | |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 814 | def test_specific_shell(self): |
| 815 | # Issue #9265: Incorrect name passed as arg[0]. |
| 816 | shells = [] |
| 817 | for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']: |
| 818 | for name in ['bash', 'ksh']: |
| 819 | sh = os.path.join(prefix, name) |
| 820 | if os.path.isfile(sh): |
| 821 | shells.append(sh) |
| 822 | if not shells: # Will probably work for any shell but csh. |
| 823 | self.skipTest("bash or ksh required for this test") |
| 824 | sh = '/bin/sh' |
| 825 | if os.path.isfile(sh) and not os.path.islink(sh): |
| 826 | # Test will fail if /bin/sh is a symlink to csh. |
| 827 | shells.append(sh) |
| 828 | for sh in shells: |
| 829 | p = subprocess.Popen("echo $0", executable=sh, shell=True, |
| 830 | stdout=subprocess.PIPE) |
| 831 | self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii')) |
| 832 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 833 | def _kill_process(self, method, *args): |
Florent Xicluna | 1d8ee3a | 2010-03-05 20:26:54 +0000 | [diff] [blame] | 834 | # Do not inherit file handles from the parent. |
| 835 | # It should fix failures on some platforms. |
Antoine Pitrou | 3d8580f | 2010-09-20 01:33:21 +0000 | [diff] [blame] | 836 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 837 | import sys, time |
| 838 | sys.stdout.write('x\\n') |
| 839 | sys.stdout.flush() |
| 840 | time.sleep(30) |
| 841 | """], |
| 842 | close_fds=True, |
| 843 | stdin=subprocess.PIPE, |
| 844 | stdout=subprocess.PIPE, |
| 845 | stderr=subprocess.PIPE) |
| 846 | # Wait for the interpreter to be completely initialized before |
| 847 | # sending any signal. |
| 848 | p.stdout.read(1) |
| 849 | getattr(p, method)(*args) |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 850 | return p |
| 851 | |
| 852 | def test_send_signal(self): |
| 853 | p = self._kill_process('send_signal', signal.SIGINT) |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 854 | _, stderr = p.communicate() |
| 855 | self.assertIn(b'KeyboardInterrupt', stderr) |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 856 | self.assertNotEqual(p.wait(), 0) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 857 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 858 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 859 | p = self._kill_process('kill') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 860 | _, stderr = p.communicate() |
| 861 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 862 | self.assertEqual(p.wait(), -signal.SIGKILL) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 863 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 864 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 865 | p = self._kill_process('terminate') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 866 | _, stderr = p.communicate() |
| 867 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 868 | self.assertEqual(p.wait(), -signal.SIGTERM) |
| 869 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 870 | def test_surrogates_error_message(self): |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 871 | def prepare(): |
| 872 | raise ValueError("surrogate:\uDCff") |
| 873 | |
| 874 | try: |
| 875 | subprocess.call( |
| 876 | [sys.executable, "-c", "pass"], |
| 877 | preexec_fn=prepare) |
| 878 | except ValueError as err: |
| 879 | # Pure Python implementations keeps the message |
| 880 | self.assertIsNone(subprocess._posixsubprocess) |
| 881 | self.assertEqual(str(err), "surrogate:\uDCff") |
| 882 | except RuntimeError as err: |
| 883 | # _posixsubprocess uses a default message |
| 884 | self.assertIsNotNone(subprocess._posixsubprocess) |
| 885 | self.assertEqual(str(err), "Exception occurred in preexec_fn.") |
| 886 | else: |
| 887 | self.fail("Expected ValueError or RuntimeError") |
| 888 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 889 | def test_undecodable_env(self): |
| 890 | for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')): |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 891 | # test str with surrogates |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 892 | script = "import os; print(ascii(os.getenv(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 893 | env = os.environ.copy() |
| 894 | env[key] = value |
Victor Stinner | 89f3ad1 | 2010-10-14 10:43:31 +0000 | [diff] [blame] | 895 | # Use C locale to get ascii for the locale encoding to force |
| 896 | # surrogate-escaping of \xFF in the child process; otherwise it can |
| 897 | # be decoded as-is if the default locale is latin-1. |
Victor Stinner | ebc78d2 | 2010-10-14 10:38:17 +0000 | [diff] [blame] | 898 | env['LC_ALL'] = 'C' |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 899 | stdout = subprocess.check_output( |
| 900 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 901 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 902 | stdout = stdout.rstrip(b'\n\r') |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 903 | self.assertEquals(stdout.decode('ascii'), ascii(value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 904 | |
| 905 | # test bytes |
| 906 | key = key.encode("ascii", "surrogateescape") |
| 907 | value = value.encode("ascii", "surrogateescape") |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 908 | script = "import os; print(ascii(os.getenvb(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 909 | env = os.environ.copy() |
| 910 | env[key] = value |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 911 | stdout = subprocess.check_output( |
| 912 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 913 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 914 | stdout = stdout.rstrip(b'\n\r') |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 915 | self.assertEquals(stdout.decode('ascii'), ascii(value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 916 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 917 | def test_bytes_program(self): |
| 918 | abs_program = os.fsencode(sys.executable) |
| 919 | path, program = os.path.split(sys.executable) |
| 920 | program = os.fsencode(program) |
| 921 | |
| 922 | # absolute bytes path |
| 923 | exitcode = subprocess.call([abs_program, "-c", "pass"]) |
| 924 | self.assertEquals(exitcode, 0) |
| 925 | |
| 926 | # bytes program, unicode PATH |
| 927 | env = os.environ.copy() |
| 928 | env["PATH"] = path |
| 929 | exitcode = subprocess.call([program, "-c", "pass"], env=env) |
| 930 | self.assertEquals(exitcode, 0) |
| 931 | |
| 932 | # bytes program, bytes PATH |
| 933 | envb = os.environb.copy() |
| 934 | envb[b"PATH"] = os.fsencode(path) |
| 935 | exitcode = subprocess.call([program, "-c", "pass"], env=envb) |
| 936 | self.assertEquals(exitcode, 0) |
| 937 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 938 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 939 | @unittest.skipUnless(mswindows, "Windows specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 940 | class Win32ProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 941 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 942 | def test_startupinfo(self): |
| 943 | # startupinfo argument |
| 944 | # We uses hardcoded constants, because we do not want to |
| 945 | # depend on win32all. |
| 946 | STARTF_USESHOWWINDOW = 1 |
| 947 | SW_MAXIMIZE = 3 |
| 948 | startupinfo = subprocess.STARTUPINFO() |
| 949 | startupinfo.dwFlags = STARTF_USESHOWWINDOW |
| 950 | startupinfo.wShowWindow = SW_MAXIMIZE |
| 951 | # Since Python is a console process, it won't be affected |
| 952 | # by wShowWindow, but the argument should be silently |
| 953 | # ignored |
| 954 | subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 955 | startupinfo=startupinfo) |
| 956 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 957 | def test_creationflags(self): |
| 958 | # creationflags argument |
| 959 | CREATE_NEW_CONSOLE = 16 |
| 960 | sys.stderr.write(" a DOS box should flash briefly ...\n") |
| 961 | subprocess.call(sys.executable + |
| 962 | ' -c "import time; time.sleep(0.25)"', |
| 963 | creationflags=CREATE_NEW_CONSOLE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 964 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 965 | def test_invalid_args(self): |
| 966 | # invalid arguments should raise ValueError |
| 967 | self.assertRaises(ValueError, subprocess.call, |
| 968 | [sys.executable, "-c", |
| 969 | "import sys; sys.exit(47)"], |
| 970 | preexec_fn=lambda: 1) |
| 971 | self.assertRaises(ValueError, subprocess.call, |
| 972 | [sys.executable, "-c", |
| 973 | "import sys; sys.exit(47)"], |
| 974 | stdout=subprocess.PIPE, |
| 975 | close_fds=True) |
| 976 | |
| 977 | def test_close_fds(self): |
| 978 | # close file descriptors |
| 979 | rc = subprocess.call([sys.executable, "-c", |
| 980 | "import sys; sys.exit(47)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 981 | close_fds=True) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 982 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 983 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 984 | def test_shell_sequence(self): |
| 985 | # Run command through the shell (sequence) |
| 986 | newenv = os.environ.copy() |
| 987 | newenv["FRUIT"] = "physalis" |
| 988 | p = subprocess.Popen(["set"], shell=1, |
| 989 | stdout=subprocess.PIPE, |
| 990 | env=newenv) |
| 991 | self.assertIn(b"physalis", p.stdout.read()) |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 992 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 993 | def test_shell_string(self): |
| 994 | # Run command through the shell (string) |
| 995 | newenv = os.environ.copy() |
| 996 | newenv["FRUIT"] = "physalis" |
| 997 | p = subprocess.Popen("set", shell=1, |
| 998 | stdout=subprocess.PIPE, |
| 999 | env=newenv) |
| 1000 | self.assertIn(b"physalis", p.stdout.read()) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1001 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1002 | def test_call_string(self): |
| 1003 | # call() function with string argument on Windows |
| 1004 | rc = subprocess.call(sys.executable + |
| 1005 | ' -c "import sys; sys.exit(47)"') |
| 1006 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1007 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1008 | def _kill_process(self, method, *args): |
| 1009 | # Some win32 buildbot raises EOFError if stdin is inherited |
Antoine Pitrou | a4024e2 | 2010-09-24 18:57:01 +0000 | [diff] [blame] | 1010 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1011 | import sys, time |
| 1012 | sys.stdout.write('x\\n') |
| 1013 | sys.stdout.flush() |
| 1014 | time.sleep(30) |
| 1015 | """], |
| 1016 | stdin=subprocess.PIPE, |
| 1017 | stdout=subprocess.PIPE, |
| 1018 | stderr=subprocess.PIPE) |
| 1019 | # Wait for the interpreter to be completely initialized before |
| 1020 | # sending any signal. |
| 1021 | p.stdout.read(1) |
| 1022 | getattr(p, method)(*args) |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1023 | _, stderr = p.communicate() |
| 1024 | self.assertStderrEqual(stderr, b'') |
Antoine Pitrou | a4024e2 | 2010-09-24 18:57:01 +0000 | [diff] [blame] | 1025 | returncode = p.wait() |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1026 | self.assertNotEqual(returncode, 0) |
| 1027 | |
| 1028 | def test_send_signal(self): |
| 1029 | self._kill_process('send_signal', signal.SIGTERM) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1030 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1031 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1032 | self._kill_process('kill') |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1033 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1034 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1035 | self._kill_process('terminate') |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1036 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1037 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1038 | # The module says: |
| 1039 | # "NB This only works (and is only relevant) for UNIX." |
| 1040 | # |
| 1041 | # Actually, getoutput should work on any platform with an os.popen, but |
| 1042 | # I'll take the comment as given, and skip this suite. |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1043 | @unittest.skipUnless(os.name == 'posix', "only relevant for UNIX") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1044 | class CommandTests(unittest.TestCase): |
| 1045 | def test_getoutput(self): |
| 1046 | self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy') |
| 1047 | self.assertEqual(subprocess.getstatusoutput('echo xyzzy'), |
| 1048 | (0, 'xyzzy')) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1049 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1050 | # we use mkdtemp in the next line to create an empty directory |
| 1051 | # under our exclusive control; from that, we can invent a pathname |
| 1052 | # that we _know_ won't exist. This is guaranteed to fail. |
| 1053 | dir = None |
| 1054 | try: |
| 1055 | dir = tempfile.mkdtemp() |
| 1056 | name = os.path.join(dir, "foo") |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1057 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1058 | status, output = subprocess.getstatusoutput('cat ' + name) |
| 1059 | self.assertNotEqual(status, 0) |
| 1060 | finally: |
| 1061 | if dir is not None: |
| 1062 | os.rmdir(dir) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1063 | |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1064 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1065 | @unittest.skipUnless(getattr(subprocess, '_has_poll', False), |
| 1066 | "poll system call not supported") |
| 1067 | class ProcessTestCaseNoPoll(ProcessTestCase): |
| 1068 | def setUp(self): |
| 1069 | subprocess._has_poll = False |
| 1070 | ProcessTestCase.setUp(self) |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1071 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1072 | def tearDown(self): |
| 1073 | subprocess._has_poll = True |
| 1074 | ProcessTestCase.tearDown(self) |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1075 | |
| 1076 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1077 | @unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False), |
| 1078 | "_posixsubprocess extension module not found.") |
| 1079 | class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase): |
| 1080 | def setUp(self): |
| 1081 | subprocess._posixsubprocess = None |
| 1082 | ProcessTestCase.setUp(self) |
| 1083 | POSIXProcessTestCase.setUp(self) |
| 1084 | |
| 1085 | def tearDown(self): |
| 1086 | subprocess._posixsubprocess = sys.modules['_posixsubprocess'] |
| 1087 | POSIXProcessTestCase.tearDown(self) |
| 1088 | ProcessTestCase.tearDown(self) |
| 1089 | |
| 1090 | |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 1091 | class HelperFunctionTests(unittest.TestCase): |
Gregory P. Smith | af6d3b8 | 2010-03-01 02:56:44 +0000 | [diff] [blame] | 1092 | @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows") |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 1093 | def test_eintr_retry_call(self): |
| 1094 | record_calls = [] |
| 1095 | def fake_os_func(*args): |
| 1096 | record_calls.append(args) |
| 1097 | if len(record_calls) == 2: |
| 1098 | raise OSError(errno.EINTR, "fake interrupted system call") |
| 1099 | return tuple(reversed(args)) |
| 1100 | |
| 1101 | self.assertEqual((999, 256), |
| 1102 | subprocess._eintr_retry_call(fake_os_func, 256, 999)) |
| 1103 | self.assertEqual([(256, 999)], record_calls) |
| 1104 | # This time there will be an EINTR so it will loop once. |
| 1105 | self.assertEqual((666,), |
| 1106 | subprocess._eintr_retry_call(fake_os_func, 666)) |
| 1107 | self.assertEqual([(256, 999), (666,), (666,)], record_calls) |
| 1108 | |
| 1109 | |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 1110 | @unittest.skipUnless(mswindows, "Windows-specific tests") |
| 1111 | class CommandsWithSpaces (BaseTestCase): |
| 1112 | |
| 1113 | def setUp(self): |
| 1114 | super().setUp() |
| 1115 | f, fname = mkstemp(".py", "te st") |
| 1116 | self.fname = fname.lower () |
| 1117 | os.write(f, b"import sys;" |
| 1118 | b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))" |
| 1119 | ) |
| 1120 | os.close(f) |
| 1121 | |
| 1122 | def tearDown(self): |
| 1123 | os.remove(self.fname) |
| 1124 | super().tearDown() |
| 1125 | |
| 1126 | def with_spaces(self, *args, **kwargs): |
| 1127 | kwargs['stdout'] = subprocess.PIPE |
| 1128 | p = subprocess.Popen(*args, **kwargs) |
| 1129 | self.assertEqual( |
| 1130 | p.stdout.read ().decode("mbcs"), |
| 1131 | "2 [%r, 'ab cd']" % self.fname |
| 1132 | ) |
| 1133 | |
| 1134 | def test_shell_string_with_spaces(self): |
| 1135 | # call() function with string argument with spaces on Windows |
Brian Curtin | d835cf1 | 2010-08-13 20:42:57 +0000 | [diff] [blame] | 1136 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 1137 | "ab cd"), shell=1) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 1138 | |
| 1139 | def test_shell_sequence_with_spaces(self): |
| 1140 | # call() function with sequence argument with spaces on Windows |
Brian Curtin | d835cf1 | 2010-08-13 20:42:57 +0000 | [diff] [blame] | 1141 | self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 1142 | |
| 1143 | def test_noshell_string_with_spaces(self): |
| 1144 | # call() function with string argument with spaces on Windows |
| 1145 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 1146 | "ab cd")) |
| 1147 | |
| 1148 | def test_noshell_sequence_with_spaces(self): |
| 1149 | # call() function with sequence argument with spaces on Windows |
| 1150 | self.with_spaces([sys.executable, self.fname, "ab cd"]) |
| 1151 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1152 | def test_main(): |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1153 | unit_tests = (ProcessTestCase, |
| 1154 | POSIXProcessTestCase, |
| 1155 | Win32ProcessTestCase, |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1156 | ProcessTestCasePOSIXPurePython, |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1157 | CommandTests, |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 1158 | ProcessTestCaseNoPoll, |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 1159 | HelperFunctionTests, |
| 1160 | CommandsWithSpaces) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1161 | |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1162 | support.run_unittest(*unit_tests) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1163 | support.reap_children() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1164 | |
| 1165 | if __name__ == "__main__": |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1166 | test_main() |