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