blob: 1587daf8f582dd000aaac9251c5df12f5c2301c8 [file] [log] [blame]
Barry Warsaw28a691b2010-04-17 00:19:56 +00001# tests command line execution of scripts
Christian Heimes9cd17752007-11-18 19:35:23 +00002
Antoine Pitrou9845c7e2014-05-11 13:42:17 +02003import contextlib
Brett Cannone0d88a12012-04-25 20:54:04 -04004import importlib
Nick Coghlan85e729e2012-07-15 18:09:52 +10005import importlib.machinery
6import zipimport
Christian Heimes9cd17752007-11-18 19:35:23 +00007import unittest
Georg Brandlf5247e32010-10-14 08:08:56 +00008import sys
Christian Heimes9cd17752007-11-18 19:35:23 +00009import os
10import os.path
Barry Warsaw28a691b2010-04-17 00:19:56 +000011import py_compile
Antoine Pitrou9845c7e2014-05-11 13:42:17 +020012import subprocess
Martin Panterca3263c2016-12-11 00:18:36 +000013import io
Barry Warsaw28a691b2010-04-17 00:19:56 +000014
Nick Coghlan1d5ccdb2012-05-21 23:03:30 +100015import textwrap
Nick Coghland26c18a2010-08-17 13:06:11 +000016from test import support
Berker Peksagce643912015-05-06 06:33:17 +030017from test.support.script_helper import (
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000018 make_pkg, make_script, make_zip_pkg, make_zip_script,
Berker Peksagce643912015-05-06 06:33:17 +030019 assert_python_ok, assert_python_failure, spawn_python, kill_python)
Christian Heimes9cd17752007-11-18 19:35:23 +000020
Nick Coghland26c18a2010-08-17 13:06:11 +000021verbose = support.verbose
Christian Heimes9cd17752007-11-18 19:35:23 +000022
Nick Coghlan37fc4012012-04-22 17:11:33 +100023example_args = ['test1', 'test2', 'test3']
24
Christian Heimescbf3b5c2007-12-03 21:02:03 +000025test_source = """\
Christian Heimes9cd17752007-11-18 19:35:23 +000026# Script may be run with optimisation enabled, so don't rely on assert
27# statements being executed
28def assertEqual(lhs, rhs):
29 if lhs != rhs:
Christian Heimescbf3b5c2007-12-03 21:02:03 +000030 raise AssertionError('%r != %r' % (lhs, rhs))
Christian Heimes9cd17752007-11-18 19:35:23 +000031def assertIdentical(lhs, rhs):
32 if lhs is not rhs:
Christian Heimescbf3b5c2007-12-03 21:02:03 +000033 raise AssertionError('%r is not %r' % (lhs, rhs))
Christian Heimes9cd17752007-11-18 19:35:23 +000034# Check basic code execution
35result = ['Top level assignment']
36def f():
37 result.append('Lower level reference')
38f()
39assertEqual(result, ['Top level assignment', 'Lower level reference'])
40# Check population of magic variables
41assertEqual(__name__, '__main__')
Nick Coghlan3f94cbf2012-07-15 19:10:39 +100042from importlib.machinery import BuiltinImporter
43_loader = __loader__ if __loader__ is BuiltinImporter else type(__loader__)
Nick Coghlan85e729e2012-07-15 18:09:52 +100044print('__loader__==%a' % _loader)
Victor Stinnere3874ed2010-10-17 01:41:09 +000045print('__file__==%a' % __file__)
Nick Coghlan720c7e22013-12-15 20:33:02 +100046print('__cached__==%a' % __cached__)
Christian Heimescbf3b5c2007-12-03 21:02:03 +000047print('__package__==%r' % __package__)
Nick Coghlan720c7e22013-12-15 20:33:02 +100048# Check PEP 451 details
49import os.path
50if __package__ is not None:
51 print('__main__ was located through the import system')
52 assertIdentical(__spec__.loader, __loader__)
53 expected_spec_name = os.path.splitext(os.path.basename(__file__))[0]
54 if __package__:
55 expected_spec_name = __package__ + "." + expected_spec_name
56 assertEqual(__spec__.name, expected_spec_name)
57 assertEqual(__spec__.parent, __package__)
58 assertIdentical(__spec__.submodule_search_locations, None)
59 assertEqual(__spec__.origin, __file__)
60 if __spec__.cached is not None:
61 assertEqual(__spec__.cached, __cached__)
Christian Heimes9cd17752007-11-18 19:35:23 +000062# Check the sys module
63import sys
64assertIdentical(globals(), sys.modules[__name__].__dict__)
Nick Coghlan720c7e22013-12-15 20:33:02 +100065if __spec__ is not None:
66 # XXX: We're not currently making __main__ available under its real name
67 pass # assertIdentical(globals(), sys.modules[__spec__.name].__dict__)
Nick Coghlan37fc4012012-04-22 17:11:33 +100068from test import test_cmd_line_script
69example_args_list = test_cmd_line_script.example_args
70assertEqual(sys.argv[1:], example_args_list)
Victor Stinnere3874ed2010-10-17 01:41:09 +000071print('sys.argv[0]==%a' % sys.argv[0])
72print('sys.path[0]==%a' % sys.path[0])
Nick Coghland26c18a2010-08-17 13:06:11 +000073# Check the working directory
74import os
Victor Stinnere3874ed2010-10-17 01:41:09 +000075print('cwd==%a' % os.getcwd())
Christian Heimescbf3b5c2007-12-03 21:02:03 +000076"""
Christian Heimes9cd17752007-11-18 19:35:23 +000077
Christian Heimescbf3b5c2007-12-03 21:02:03 +000078def _make_test_script(script_dir, script_basename, source=test_source):
Brett Cannone0d88a12012-04-25 20:54:04 -040079 to_return = make_script(script_dir, script_basename, source)
80 importlib.invalidate_caches()
81 return to_return
Christian Heimescbf3b5c2007-12-03 21:02:03 +000082
Nick Coghlanf088e5e2008-12-14 11:50:48 +000083def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
84 source=test_source, depth=1):
Brett Cannone0d88a12012-04-25 20:54:04 -040085 to_return = make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
86 source, depth)
87 importlib.invalidate_caches()
88 return to_return
Nick Coghlanf088e5e2008-12-14 11:50:48 +000089
Christian Heimescbf3b5c2007-12-03 21:02:03 +000090# There's no easy way to pass the script directory in to get
91# -m to work (avoiding that is the whole point of making
92# directories and zipfiles executable!)
93# So we fake it for testing purposes with a custom launch script
94launch_source = """\
95import sys, os.path, runpy
Nick Coghlanf088e5e2008-12-14 11:50:48 +000096sys.path.insert(0, %s)
Christian Heimescbf3b5c2007-12-03 21:02:03 +000097runpy._run_module_as_main(%r)
98"""
99
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000100def _make_launch_script(script_dir, script_basename, module_name, path=None):
101 if path is None:
102 path = "os.path.dirname(__file__)"
103 else:
104 path = repr(path)
105 source = launch_source % (path, module_name)
Brett Cannone0d88a12012-04-25 20:54:04 -0400106 to_return = make_script(script_dir, script_basename, source)
107 importlib.invalidate_caches()
108 return to_return
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000109
Christian Heimes9cd17752007-11-18 19:35:23 +0000110class CmdLineTest(unittest.TestCase):
Nick Coghland26c18a2010-08-17 13:06:11 +0000111 def _check_output(self, script_name, exit_code, data,
112 expected_file, expected_argv0,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000113 expected_path0, expected_package,
114 expected_loader):
Nick Coghland26c18a2010-08-17 13:06:11 +0000115 if verbose > 1:
Guido van Rossum87c0f1d2007-11-19 18:03:44 +0000116 print("Output from test script %r:" % script_name)
Serhiy Storchakab0749ca2015-03-25 01:33:19 +0200117 print(repr(data))
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000118 self.assertEqual(exit_code, 0)
Nick Coghlan85e729e2012-07-15 18:09:52 +1000119 printed_loader = '__loader__==%a' % expected_loader
Victor Stinnere3874ed2010-10-17 01:41:09 +0000120 printed_file = '__file__==%a' % expected_file
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000121 printed_package = '__package__==%r' % expected_package
Victor Stinnere3874ed2010-10-17 01:41:09 +0000122 printed_argv0 = 'sys.argv[0]==%a' % expected_argv0
123 printed_path0 = 'sys.path[0]==%a' % expected_path0
124 printed_cwd = 'cwd==%a' % os.getcwd()
Nick Coghland26c18a2010-08-17 13:06:11 +0000125 if verbose > 1:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000126 print('Expected output:')
127 print(printed_file)
128 print(printed_package)
129 print(printed_argv0)
Nick Coghland26c18a2010-08-17 13:06:11 +0000130 print(printed_cwd)
Benjamin Petersonab078e92016-07-13 21:13:29 -0700131 self.assertIn(printed_loader.encode('utf-8'), data)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000132 self.assertIn(printed_file.encode('utf-8'), data)
133 self.assertIn(printed_package.encode('utf-8'), data)
134 self.assertIn(printed_argv0.encode('utf-8'), data)
Nick Coghland26c18a2010-08-17 13:06:11 +0000135 self.assertIn(printed_path0.encode('utf-8'), data)
136 self.assertIn(printed_cwd.encode('utf-8'), data)
137
138 def _check_script(self, script_name, expected_file,
139 expected_argv0, expected_path0,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000140 expected_package, expected_loader,
Nick Coghland26c18a2010-08-17 13:06:11 +0000141 *cmd_line_switches):
Victor Stinner9def2842016-01-18 12:15:08 +0100142 run_args = [*support.optim_args_from_interpreter_flags(),
143 *cmd_line_switches, script_name, *example_args]
Victor Stinnere8785ff2013-10-12 14:44:01 +0200144 rc, out, err = assert_python_ok(*run_args, __isolated=False)
Antoine Pitrouf51d8d32010-10-08 18:05:42 +0000145 self._check_output(script_name, rc, out + err, expected_file,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000146 expected_argv0, expected_path0,
147 expected_package, expected_loader)
Christian Heimes9cd17752007-11-18 19:35:23 +0000148
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000149 def _check_import_error(self, script_name, expected_msg,
150 *cmd_line_switches):
151 run_args = cmd_line_switches + (script_name,)
Antoine Pitrouf51d8d32010-10-08 18:05:42 +0000152 rc, out, err = assert_python_failure(*run_args)
Nick Coghland26c18a2010-08-17 13:06:11 +0000153 if verbose > 1:
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000154 print('Output from test script %r:' % script_name)
Serhiy Storchakab0749ca2015-03-25 01:33:19 +0200155 print(repr(err))
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000156 print('Expected output: %r' % expected_msg)
Antoine Pitrouf51d8d32010-10-08 18:05:42 +0000157 self.assertIn(expected_msg.encode('utf-8'), err)
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000158
Nick Coghlan85e729e2012-07-15 18:09:52 +1000159 def test_dash_c_loader(self):
160 rc, out, err = assert_python_ok("-c", "print(__loader__)")
161 expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8")
162 self.assertIn(expected, out)
163
164 def test_stdin_loader(self):
Nick Coghlan37b3b902012-07-15 18:24:42 +1000165 # Unfortunately, there's no way to automatically test the fully
166 # interactive REPL, since that code path only gets executed when
Nick Coghlan8e6e7d32012-07-15 23:13:18 +1000167 # stdin is an interactive tty.
Nick Coghlan85e729e2012-07-15 18:09:52 +1000168 p = spawn_python()
169 try:
170 p.stdin.write(b"print(__loader__)\n")
171 p.stdin.flush()
172 finally:
173 out = kill_python(p)
174 expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8")
175 self.assertIn(expected, out)
176
Antoine Pitrou9845c7e2014-05-11 13:42:17 +0200177 @contextlib.contextmanager
178 def interactive_python(self, separate_stderr=False):
179 if separate_stderr:
180 p = spawn_python('-i', bufsize=1, stderr=subprocess.PIPE)
181 stderr = p.stderr
182 else:
183 p = spawn_python('-i', bufsize=1, stderr=subprocess.STDOUT)
184 stderr = p.stdout
185 try:
186 # Drain stderr until prompt
187 while True:
188 data = stderr.read(4)
189 if data == b">>> ":
190 break
191 stderr.readline()
192 yield p
193 finally:
194 kill_python(p)
195 stderr.close()
196
197 def check_repl_stdout_flush(self, separate_stderr=False):
198 with self.interactive_python(separate_stderr) as p:
199 p.stdin.write(b"print('foo')\n")
200 p.stdin.flush()
201 self.assertEqual(b'foo', p.stdout.readline().strip())
202
203 def check_repl_stderr_flush(self, separate_stderr=False):
204 with self.interactive_python(separate_stderr) as p:
205 p.stdin.write(b"1/0\n")
206 p.stdin.flush()
207 stderr = p.stderr if separate_stderr else p.stdout
208 self.assertIn(b'Traceback ', stderr.readline())
209 self.assertIn(b'File "<stdin>"', stderr.readline())
210 self.assertIn(b'ZeroDivisionError', stderr.readline())
211
212 def test_repl_stdout_flush(self):
213 self.check_repl_stdout_flush()
214
215 def test_repl_stdout_flush_separate_stderr(self):
216 self.check_repl_stdout_flush(True)
217
218 def test_repl_stderr_flush(self):
219 self.check_repl_stderr_flush()
220
221 def test_repl_stderr_flush_separate_stderr(self):
222 self.check_repl_stderr_flush(True)
223
Christian Heimes9cd17752007-11-18 19:35:23 +0000224 def test_basic_script(self):
Berker Peksagce643912015-05-06 06:33:17 +0300225 with support.temp_dir() as script_dir:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000226 script_name = _make_test_script(script_dir, 'script')
Nick Coghland26c18a2010-08-17 13:06:11 +0000227 self._check_script(script_name, script_name, script_name,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000228 script_dir, None,
229 importlib.machinery.SourceFileLoader)
Christian Heimes9cd17752007-11-18 19:35:23 +0000230
231 def test_script_compiled(self):
Berker Peksagce643912015-05-06 06:33:17 +0300232 with support.temp_dir() as script_dir:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000233 script_name = _make_test_script(script_dir, 'script')
Nick Coghland26c18a2010-08-17 13:06:11 +0000234 py_compile.compile(script_name, doraise=True)
Christian Heimes9cd17752007-11-18 19:35:23 +0000235 os.remove(script_name)
Nick Coghland26c18a2010-08-17 13:06:11 +0000236 pyc_file = support.make_legacy_pyc(script_name)
237 self._check_script(pyc_file, pyc_file,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000238 pyc_file, script_dir, None,
239 importlib.machinery.SourcelessFileLoader)
Christian Heimes9cd17752007-11-18 19:35:23 +0000240
241 def test_directory(self):
Berker Peksagce643912015-05-06 06:33:17 +0300242 with support.temp_dir() as script_dir:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000243 script_name = _make_test_script(script_dir, '__main__')
Nick Coghland26c18a2010-08-17 13:06:11 +0000244 self._check_script(script_dir, script_name, script_dir,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000245 script_dir, '',
246 importlib.machinery.SourceFileLoader)
Christian Heimes9cd17752007-11-18 19:35:23 +0000247
248 def test_directory_compiled(self):
Berker Peksagce643912015-05-06 06:33:17 +0300249 with support.temp_dir() as script_dir:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000250 script_name = _make_test_script(script_dir, '__main__')
Nick Coghland26c18a2010-08-17 13:06:11 +0000251 py_compile.compile(script_name, doraise=True)
Christian Heimes9cd17752007-11-18 19:35:23 +0000252 os.remove(script_name)
Nick Coghland26c18a2010-08-17 13:06:11 +0000253 pyc_file = support.make_legacy_pyc(script_name)
254 self._check_script(script_dir, pyc_file, script_dir,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000255 script_dir, '',
256 importlib.machinery.SourcelessFileLoader)
Christian Heimes9cd17752007-11-18 19:35:23 +0000257
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000258 def test_directory_error(self):
Berker Peksagce643912015-05-06 06:33:17 +0300259 with support.temp_dir() as script_dir:
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000260 msg = "can't find '__main__' module in %r" % script_dir
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000261 self._check_import_error(script_dir, msg)
262
Christian Heimes9cd17752007-11-18 19:35:23 +0000263 def test_zipfile(self):
Berker Peksagce643912015-05-06 06:33:17 +0300264 with support.temp_dir() as script_dir:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000265 script_name = _make_test_script(script_dir, '__main__')
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000266 zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +1000267 self._check_script(zip_name, run_name, zip_name, zip_name, '',
268 zipimport.zipimporter)
Christian Heimes9cd17752007-11-18 19:35:23 +0000269
270 def test_zipfile_compiled(self):
Berker Peksagce643912015-05-06 06:33:17 +0300271 with support.temp_dir() as script_dir:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000272 script_name = _make_test_script(script_dir, '__main__')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000273 compiled_name = py_compile.compile(script_name, doraise=True)
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000274 zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +1000275 self._check_script(zip_name, run_name, zip_name, zip_name, '',
276 zipimport.zipimporter)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000277
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000278 def test_zipfile_error(self):
Berker Peksagce643912015-05-06 06:33:17 +0300279 with support.temp_dir() as script_dir:
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000280 script_name = _make_test_script(script_dir, 'not_main')
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000281 zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name)
282 msg = "can't find '__main__' module in %r" % zip_name
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000283 self._check_import_error(zip_name, msg)
284
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000285 def test_module_in_package(self):
Berker Peksagce643912015-05-06 06:33:17 +0300286 with support.temp_dir() as script_dir:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000287 pkg_dir = os.path.join(script_dir, 'test_pkg')
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000288 make_pkg(pkg_dir)
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000289 script_name = _make_test_script(pkg_dir, 'script')
290 launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script')
Nick Coghlan85e729e2012-07-15 18:09:52 +1000291 self._check_script(launch_name, script_name, script_name,
292 script_dir, 'test_pkg',
293 importlib.machinery.SourceFileLoader)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000294
295 def test_module_in_package_in_zipfile(self):
Berker Peksagce643912015-05-06 06:33:17 +0300296 with support.temp_dir() as script_dir:
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000297 zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script')
298 launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script', zip_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +1000299 self._check_script(launch_name, run_name, run_name,
300 zip_name, 'test_pkg', zipimport.zipimporter)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000301
302 def test_module_in_subpackage_in_zipfile(self):
Berker Peksagce643912015-05-06 06:33:17 +0300303 with support.temp_dir() as script_dir:
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000304 zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2)
305 launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.test_pkg.script', zip_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +1000306 self._check_script(launch_name, run_name, run_name,
307 zip_name, 'test_pkg.test_pkg',
308 zipimport.zipimporter)
Christian Heimes9cd17752007-11-18 19:35:23 +0000309
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000310 def test_package(self):
Berker Peksagce643912015-05-06 06:33:17 +0300311 with support.temp_dir() as script_dir:
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000312 pkg_dir = os.path.join(script_dir, 'test_pkg')
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000313 make_pkg(pkg_dir)
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000314 script_name = _make_test_script(pkg_dir, '__main__')
315 launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
316 self._check_script(launch_name, script_name,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000317 script_name, script_dir, 'test_pkg',
318 importlib.machinery.SourceFileLoader)
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000319
320 def test_package_compiled(self):
Berker Peksagce643912015-05-06 06:33:17 +0300321 with support.temp_dir() as script_dir:
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000322 pkg_dir = os.path.join(script_dir, 'test_pkg')
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000323 make_pkg(pkg_dir)
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000324 script_name = _make_test_script(pkg_dir, '__main__')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000325 compiled_name = py_compile.compile(script_name, doraise=True)
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000326 os.remove(script_name)
Nick Coghland26c18a2010-08-17 13:06:11 +0000327 pyc_file = support.make_legacy_pyc(script_name)
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000328 launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000329 self._check_script(launch_name, pyc_file,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000330 pyc_file, script_dir, 'test_pkg',
331 importlib.machinery.SourcelessFileLoader)
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000332
333 def test_package_error(self):
Berker Peksagce643912015-05-06 06:33:17 +0300334 with support.temp_dir() as script_dir:
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000335 pkg_dir = os.path.join(script_dir, 'test_pkg')
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000336 make_pkg(pkg_dir)
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000337 msg = ("'test_pkg' is a package and cannot "
338 "be directly executed")
339 launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
340 self._check_import_error(launch_name, msg)
341
342 def test_package_recursion(self):
Berker Peksagce643912015-05-06 06:33:17 +0300343 with support.temp_dir() as script_dir:
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000344 pkg_dir = os.path.join(script_dir, 'test_pkg')
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000345 make_pkg(pkg_dir)
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000346 main_dir = os.path.join(pkg_dir, '__main__')
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000347 make_pkg(main_dir)
Nick Coghlan3f48ae32009-02-08 01:58:26 +0000348 msg = ("Cannot use package as __main__ module; "
349 "'test_pkg' is a package and cannot "
350 "be directly executed")
351 launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
352 self._check_import_error(launch_name, msg)
353
Nick Coghland26c18a2010-08-17 13:06:11 +0000354 def test_issue8202(self):
355 # Make sure package __init__ modules see "-m" in sys.argv0 while
356 # searching for the module to execute
Berker Peksagce643912015-05-06 06:33:17 +0300357 with support.temp_dir() as script_dir:
Nick Coghlan55175962013-07-28 22:11:50 +1000358 with support.change_cwd(path=script_dir):
Nick Coghland26c18a2010-08-17 13:06:11 +0000359 pkg_dir = os.path.join(script_dir, 'test_pkg')
360 make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])")
361 script_name = _make_test_script(pkg_dir, 'script')
Victor Stinnere8785ff2013-10-12 14:44:01 +0200362 rc, out, err = assert_python_ok('-m', 'test_pkg.script', *example_args, __isolated=False)
Nick Coghland26c18a2010-08-17 13:06:11 +0000363 if verbose > 1:
Serhiy Storchakab0749ca2015-03-25 01:33:19 +0200364 print(repr(out))
Nick Coghland26c18a2010-08-17 13:06:11 +0000365 expected = "init_argv0==%r" % '-m'
Antoine Pitrouf51d8d32010-10-08 18:05:42 +0000366 self.assertIn(expected.encode('utf-8'), out)
367 self._check_output(script_name, rc, out,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000368 script_name, script_name, '', 'test_pkg',
369 importlib.machinery.SourceFileLoader)
Nick Coghland26c18a2010-08-17 13:06:11 +0000370
371 def test_issue8202_dash_c_file_ignored(self):
372 # Make sure a "-c" file in the current directory
373 # does not alter the value of sys.path[0]
Berker Peksagce643912015-05-06 06:33:17 +0300374 with support.temp_dir() as script_dir:
Nick Coghlan55175962013-07-28 22:11:50 +1000375 with support.change_cwd(path=script_dir):
Nick Coghland26c18a2010-08-17 13:06:11 +0000376 with open("-c", "w") as f:
377 f.write("data")
Antoine Pitrouf51d8d32010-10-08 18:05:42 +0000378 rc, out, err = assert_python_ok('-c',
Victor Stinnere8785ff2013-10-12 14:44:01 +0200379 'import sys; print("sys.path[0]==%r" % sys.path[0])',
380 __isolated=False)
Nick Coghland26c18a2010-08-17 13:06:11 +0000381 if verbose > 1:
Serhiy Storchakab0749ca2015-03-25 01:33:19 +0200382 print(repr(out))
Nick Coghland26c18a2010-08-17 13:06:11 +0000383 expected = "sys.path[0]==%r" % ''
Antoine Pitrouf51d8d32010-10-08 18:05:42 +0000384 self.assertIn(expected.encode('utf-8'), out)
Nick Coghland26c18a2010-08-17 13:06:11 +0000385
386 def test_issue8202_dash_m_file_ignored(self):
387 # Make sure a "-m" file in the current directory
388 # does not alter the value of sys.path[0]
Berker Peksagce643912015-05-06 06:33:17 +0300389 with support.temp_dir() as script_dir:
Nick Coghland26c18a2010-08-17 13:06:11 +0000390 script_name = _make_test_script(script_dir, 'other')
Nick Coghlan55175962013-07-28 22:11:50 +1000391 with support.change_cwd(path=script_dir):
Nick Coghland26c18a2010-08-17 13:06:11 +0000392 with open("-m", "w") as f:
393 f.write("data")
Victor Stinnere8785ff2013-10-12 14:44:01 +0200394 rc, out, err = assert_python_ok('-m', 'other', *example_args,
395 __isolated=False)
Antoine Pitrouf51d8d32010-10-08 18:05:42 +0000396 self._check_output(script_name, rc, out,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000397 script_name, script_name, '', '',
398 importlib.machinery.SourceFileLoader)
Christian Heimes9cd17752007-11-18 19:35:23 +0000399
Martin Panter657257e2015-12-03 01:23:10 +0000400 @contextlib.contextmanager
401 def setup_test_pkg(self, *args):
402 with support.temp_dir() as script_dir, \
403 support.change_cwd(path=script_dir):
404 pkg_dir = os.path.join(script_dir, 'test_pkg')
405 make_pkg(pkg_dir, *args)
406 yield pkg_dir
407
408 def check_dash_m_failure(self, *args):
409 rc, out, err = assert_python_failure('-m', *args, __isolated=False)
410 if verbose > 1:
411 print(repr(out))
412 self.assertEqual(rc, 1)
413 return err
414
Senthil Kumaranf01a3372012-07-04 19:28:16 -0700415 def test_dash_m_error_code_is_one(self):
416 # If a module is invoked with the -m command line flag
417 # and results in an error that the return code to the
418 # shell is '1'
Martin Panter657257e2015-12-03 01:23:10 +0000419 with self.setup_test_pkg() as pkg_dir:
420 script_name = _make_test_script(pkg_dir, 'other',
421 "if __name__ == '__main__': raise ValueError")
422 err = self.check_dash_m_failure('test_pkg.other', *example_args)
423 self.assertIn(b'ValueError', err)
424
425 def test_dash_m_errors(self):
426 # Exercise error reporting for various invalid package executions
427 tests = (
428 ('builtins', br'No code object available'),
Martin Panter9c8aa9b2016-08-21 04:07:58 +0000429 ('builtins.x', br'Error while finding module specification.*'
430 br'AttributeError'),
431 ('builtins.x.y', br'Error while finding module specification.*'
Eric Snow46f97b82016-09-07 16:56:15 -0700432 br'ModuleNotFoundError.*No module named.*not a package'),
Martin Panter657257e2015-12-03 01:23:10 +0000433 ('os.path', br'loader.*cannot handle'),
434 ('importlib', br'No module named.*'
435 br'is a package and cannot be directly executed'),
436 ('importlib.nonexistant', br'No module named'),
Martin Panter7dda4212015-12-10 06:47:06 +0000437 ('.unittest', br'Relative module names not supported'),
Martin Panter657257e2015-12-03 01:23:10 +0000438 )
439 for name, regex in tests:
440 with self.subTest(name):
441 rc, _, err = assert_python_failure('-m', name)
Senthil Kumaranf01a3372012-07-04 19:28:16 -0700442 self.assertEqual(rc, 1)
Martin Panter657257e2015-12-03 01:23:10 +0000443 self.assertRegex(err, regex)
444 self.assertNotIn(b'Traceback', err)
445
Martin Panterdda58432015-12-12 06:58:55 +0000446 def test_dash_m_bad_pyc(self):
447 with support.temp_dir() as script_dir, \
448 support.change_cwd(path=script_dir):
449 os.mkdir('test_pkg')
450 # Create invalid *.pyc as empty file
451 with open('test_pkg/__init__.pyc', 'wb'):
452 pass
453 err = self.check_dash_m_failure('test_pkg')
Martin Panter9c8aa9b2016-08-21 04:07:58 +0000454 self.assertRegex(err,
455 br'Error while finding module specification.*'
Martin Panterdda58432015-12-12 06:58:55 +0000456 br'ImportError.*bad magic number')
457 self.assertNotIn(b'is a package', err)
458 self.assertNotIn(b'Traceback', err)
459
Martin Panter657257e2015-12-03 01:23:10 +0000460 def test_dash_m_init_traceback(self):
461 # These were wrapped in an ImportError and tracebacks were
462 # suppressed; see Issue 14285
463 exceptions = (ImportError, AttributeError, TypeError, ValueError)
464 for exception in exceptions:
465 exception = exception.__name__
466 init = "raise {0}('Exception in __init__.py')".format(exception)
467 with self.subTest(exception), \
468 self.setup_test_pkg(init) as pkg_dir:
469 err = self.check_dash_m_failure('test_pkg')
470 self.assertIn(exception.encode('ascii'), err)
471 self.assertIn(b'Exception in __init__.py', err)
472 self.assertIn(b'Traceback', err)
473
474 def test_dash_m_main_traceback(self):
475 # Ensure that an ImportError's traceback is reported
476 with self.setup_test_pkg() as pkg_dir:
477 main = "raise ImportError('Exception in __main__ module')"
478 _make_test_script(pkg_dir, '__main__', main)
479 err = self.check_dash_m_failure('test_pkg')
480 self.assertIn(b'ImportError', err)
481 self.assertIn(b'Exception in __main__ module', err)
482 self.assertIn(b'Traceback', err)
Senthil Kumaranf01a3372012-07-04 19:28:16 -0700483
Nick Coghlan1d5ccdb2012-05-21 23:03:30 +1000484 def test_pep_409_verbiage(self):
485 # Make sure PEP 409 syntax properly suppresses
486 # the context of an exception
487 script = textwrap.dedent("""\
488 try:
489 raise ValueError
490 except:
491 raise NameError from None
492 """)
Berker Peksagce643912015-05-06 06:33:17 +0300493 with support.temp_dir() as script_dir:
Nick Coghlan1d5ccdb2012-05-21 23:03:30 +1000494 script_name = _make_test_script(script_dir, 'script', script)
495 exitcode, stdout, stderr = assert_python_failure(script_name)
496 text = stderr.decode('ascii').split('\n')
497 self.assertEqual(len(text), 4)
498 self.assertTrue(text[0].startswith('Traceback'))
499 self.assertTrue(text[1].startswith(' File '))
500 self.assertTrue(text[3].startswith('NameError'))
501
Victor Stinnere667e982012-11-12 01:23:15 +0100502 def test_non_ascii(self):
503 # Mac OS X denies the creation of a file with an invalid UTF-8 name.
Martin Panterc04fb562016-02-10 05:44:01 +0000504 # Windows allows creating a name with an arbitrary bytes name, but
Victor Stinnere667e982012-11-12 01:23:15 +0100505 # Python cannot a undecodable bytes argument to a subprocess.
Victor Stinner0af71aa2013-01-03 01:50:30 +0100506 if (support.TESTFN_UNDECODABLE
507 and sys.platform not in ('win32', 'darwin')):
508 name = os.fsdecode(support.TESTFN_UNDECODABLE)
509 elif support.TESTFN_NONASCII:
Victor Stinnere667e982012-11-12 01:23:15 +0100510 name = support.TESTFN_NONASCII
511 else:
512 self.skipTest("need support.TESTFN_NONASCII")
513
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200514 # Issue #16218
Victor Stinnere667e982012-11-12 01:23:15 +0100515 source = 'print(ascii(__file__))\n'
516 script_name = _make_test_script(os.curdir, name, source)
517 self.addCleanup(support.unlink, script_name)
518 rc, stdout, stderr = assert_python_ok(script_name)
519 self.assertEqual(
520 ascii(script_name),
521 stdout.rstrip().decode('ascii'),
522 'stdout=%r stderr=%r' % (stdout, stderr))
523 self.assertEqual(0, rc)
524
Nick Coghland979e432014-02-09 10:43:21 +1000525 def test_issue20500_exit_with_exception_value(self):
526 script = textwrap.dedent("""\
527 import sys
528 error = None
529 try:
530 raise ValueError('some text')
531 except ValueError as err:
532 error = err
533
534 if error:
535 sys.exit(error)
536 """)
Berker Peksagce643912015-05-06 06:33:17 +0300537 with support.temp_dir() as script_dir:
Nick Coghland979e432014-02-09 10:43:21 +1000538 script_name = _make_test_script(script_dir, 'script', script)
539 exitcode, stdout, stderr = assert_python_failure(script_name)
540 text = stderr.decode('ascii')
541 self.assertEqual(text, "some text")
542
Martin Panterca3263c2016-12-11 00:18:36 +0000543 def test_syntaxerror_unindented_caret_position(self):
544 script = "1 + 1 = 2\n"
545 with support.temp_dir() as script_dir:
546 script_name = _make_test_script(script_dir, 'script', script)
547 exitcode, stdout, stderr = assert_python_failure(script_name)
548 text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read()
549 # Confirm that the caret is located under the first 1 character
550 self.assertIn("\n 1 + 1 = 2\n ^", text)
551
552 def test_syntaxerror_indented_caret_position(self):
553 script = textwrap.dedent("""\
554 if True:
555 1 + 1 = 2
556 """)
557 with support.temp_dir() as script_dir:
558 script_name = _make_test_script(script_dir, 'script', script)
559 exitcode, stdout, stderr = assert_python_failure(script_name)
560 text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read()
561 # Confirm that the caret is located under the first 1 character
562 self.assertIn("\n 1 + 1 = 2\n ^", text)
563
564 # Try the same with a form feed at the start of the indented line
565 script = (
566 "if True:\n"
567 "\f 1 + 1 = 2\n"
568 )
569 script_name = _make_test_script(script_dir, "script", script)
570 exitcode, stdout, stderr = assert_python_failure(script_name)
571 text = io.TextIOWrapper(io.BytesIO(stderr), "ascii").read()
572 self.assertNotIn("\f", text)
573 self.assertIn("\n 1 + 1 = 2\n ^", text)
574
Nick Coghlan75345c52017-03-12 21:34:22 +1000575 def test_consistent_sys_path_for_direct_execution(self):
576 # This test case ensures that the following all give the same
577 # sys.path configuration:
578 #
579 # ./python -s script_dir/__main__.py
580 # ./python -s script_dir
581 # ./python -I script_dir
582 script = textwrap.dedent("""\
583 import sys
584 for entry in sys.path:
585 print(entry)
586 """)
587 # Always show full path diffs on errors
588 self.maxDiff = None
589 with support.temp_dir() as work_dir, support.temp_dir() as script_dir:
590 script_name = _make_test_script(script_dir, '__main__', script)
591 # Reference output comes from directly executing __main__.py
592 # We omit PYTHONPATH and user site to align with isolated mode
593 p = spawn_python("-Es", script_name, cwd=work_dir)
594 out_by_name = kill_python(p).decode().splitlines()
595 self.assertEqual(out_by_name[0], script_dir)
596 self.assertNotIn(work_dir, out_by_name)
597 # Directory execution should give the same output
598 p = spawn_python("-Es", script_dir, cwd=work_dir)
599 out_by_dir = kill_python(p).decode().splitlines()
600 self.assertEqual(out_by_dir, out_by_name)
601 # As should directory execution in isolated mode
602 p = spawn_python("-I", script_dir, cwd=work_dir)
603 out_by_dir_isolated = kill_python(p).decode().splitlines()
604 self.assertEqual(out_by_dir_isolated, out_by_dir, out_by_name)
605
606 def test_consistent_sys_path_for_module_execution(self):
607 # This test case ensures that the following both give the same
608 # sys.path configuration:
609 # ./python -sm script_pkg.__main__
610 # ./python -sm script_pkg
611 #
612 # And that this fails as unable to find the package:
613 # ./python -Im script_pkg
614 script = textwrap.dedent("""\
615 import sys
616 for entry in sys.path:
617 print(entry)
618 """)
619 # Always show full path diffs on errors
620 self.maxDiff = None
621 with support.temp_dir() as work_dir:
622 script_dir = os.path.join(work_dir, "script_pkg")
623 os.mkdir(script_dir)
624 script_name = _make_test_script(script_dir, '__main__', script)
625 # Reference output comes from `-m script_pkg.__main__`
626 # We omit PYTHONPATH and user site to better align with the
627 # direct execution test cases
628 p = spawn_python("-sm", "script_pkg.__main__", cwd=work_dir)
629 out_by_module = kill_python(p).decode().splitlines()
630 self.assertEqual(out_by_module[0], '')
631 self.assertNotIn(script_dir, out_by_module)
632 # Package execution should give the same output
633 p = spawn_python("-sm", "script_pkg", cwd=work_dir)
634 out_by_package = kill_python(p).decode().splitlines()
635 self.assertEqual(out_by_package, out_by_module)
636 # Isolated mode should fail with an import error
637 exitcode, stdout, stderr = assert_python_failure(
638 "-Im", "script_pkg", cwd=work_dir
639 )
640 traceback_lines = stderr.decode().splitlines()
641 self.assertIn("No module named script_pkg", traceback_lines[-1])
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200642
Christian Heimes9cd17752007-11-18 19:35:23 +0000643def test_main():
Nick Coghland26c18a2010-08-17 13:06:11 +0000644 support.run_unittest(CmdLineTest)
645 support.reap_children()
Christian Heimes9cd17752007-11-18 19:35:23 +0000646
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000647if __name__ == '__main__':
Christian Heimes9cd17752007-11-18 19:35:23 +0000648 test_main()