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