blob: fda3e62bd6a1d4e6e91c8c65b2a39c690e9f198a [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
Barry Warsaw28a691b2010-04-17 00:19:56 +000013
Nick Coghlan1d5ccdb2012-05-21 23:03:30 +100014import textwrap
Nick Coghland26c18a2010-08-17 13:06:11 +000015from test import support
Berker Peksagce643912015-05-06 06:33:17 +030016from test.support.script_helper import (
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000017 make_pkg, make_script, make_zip_pkg, make_zip_script,
Berker Peksagce643912015-05-06 06:33:17 +030018 assert_python_ok, assert_python_failure, spawn_python, kill_python)
Christian Heimes9cd17752007-11-18 19:35:23 +000019
Nick Coghland26c18a2010-08-17 13:06:11 +000020verbose = support.verbose
Christian Heimes9cd17752007-11-18 19:35:23 +000021
Nick Coghlan37fc4012012-04-22 17:11:33 +100022example_args = ['test1', 'test2', 'test3']
23
Christian Heimescbf3b5c2007-12-03 21:02:03 +000024test_source = """\
Christian Heimes9cd17752007-11-18 19:35:23 +000025# Script may be run with optimisation enabled, so don't rely on assert
26# statements being executed
27def assertEqual(lhs, rhs):
28 if lhs != rhs:
Christian Heimescbf3b5c2007-12-03 21:02:03 +000029 raise AssertionError('%r != %r' % (lhs, rhs))
Christian Heimes9cd17752007-11-18 19:35:23 +000030def assertIdentical(lhs, rhs):
31 if lhs is not rhs:
Christian Heimescbf3b5c2007-12-03 21:02:03 +000032 raise AssertionError('%r is not %r' % (lhs, rhs))
Christian Heimes9cd17752007-11-18 19:35:23 +000033# Check basic code execution
34result = ['Top level assignment']
35def f():
36 result.append('Lower level reference')
37f()
38assertEqual(result, ['Top level assignment', 'Lower level reference'])
39# Check population of magic variables
40assertEqual(__name__, '__main__')
Nick Coghlan3f94cbf2012-07-15 19:10:39 +100041from importlib.machinery import BuiltinImporter
42_loader = __loader__ if __loader__ is BuiltinImporter else type(__loader__)
Nick Coghlan85e729e2012-07-15 18:09:52 +100043print('__loader__==%a' % _loader)
Victor Stinnere3874ed2010-10-17 01:41:09 +000044print('__file__==%a' % __file__)
Nick Coghlan720c7e22013-12-15 20:33:02 +100045print('__cached__==%a' % __cached__)
Christian Heimescbf3b5c2007-12-03 21:02:03 +000046print('__package__==%r' % __package__)
Nick Coghlan720c7e22013-12-15 20:33:02 +100047# Check PEP 451 details
48import os.path
49if __package__ is not None:
50 print('__main__ was located through the import system')
51 assertIdentical(__spec__.loader, __loader__)
52 expected_spec_name = os.path.splitext(os.path.basename(__file__))[0]
53 if __package__:
54 expected_spec_name = __package__ + "." + expected_spec_name
55 assertEqual(__spec__.name, expected_spec_name)
56 assertEqual(__spec__.parent, __package__)
57 assertIdentical(__spec__.submodule_search_locations, None)
58 assertEqual(__spec__.origin, __file__)
59 if __spec__.cached is not None:
60 assertEqual(__spec__.cached, __cached__)
Christian Heimes9cd17752007-11-18 19:35:23 +000061# Check the sys module
62import sys
63assertIdentical(globals(), sys.modules[__name__].__dict__)
Nick Coghlan720c7e22013-12-15 20:33:02 +100064if __spec__ is not None:
65 # XXX: We're not currently making __main__ available under its real name
66 pass # assertIdentical(globals(), sys.modules[__spec__.name].__dict__)
Nick Coghlan37fc4012012-04-22 17:11:33 +100067from test import test_cmd_line_script
68example_args_list = test_cmd_line_script.example_args
69assertEqual(sys.argv[1:], example_args_list)
Victor Stinnere3874ed2010-10-17 01:41:09 +000070print('sys.argv[0]==%a' % sys.argv[0])
71print('sys.path[0]==%a' % sys.path[0])
Nick Coghland26c18a2010-08-17 13:06:11 +000072# Check the working directory
73import os
Victor Stinnere3874ed2010-10-17 01:41:09 +000074print('cwd==%a' % os.getcwd())
Christian Heimescbf3b5c2007-12-03 21:02:03 +000075"""
Christian Heimes9cd17752007-11-18 19:35:23 +000076
Christian Heimescbf3b5c2007-12-03 21:02:03 +000077def _make_test_script(script_dir, script_basename, source=test_source):
Brett Cannone0d88a12012-04-25 20:54:04 -040078 to_return = make_script(script_dir, script_basename, source)
79 importlib.invalidate_caches()
80 return to_return
Christian Heimescbf3b5c2007-12-03 21:02:03 +000081
Nick Coghlanf088e5e2008-12-14 11:50:48 +000082def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
83 source=test_source, depth=1):
Brett Cannone0d88a12012-04-25 20:54:04 -040084 to_return = make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
85 source, depth)
86 importlib.invalidate_caches()
87 return to_return
Nick Coghlanf088e5e2008-12-14 11:50:48 +000088
Christian Heimescbf3b5c2007-12-03 21:02:03 +000089# There's no easy way to pass the script directory in to get
90# -m to work (avoiding that is the whole point of making
91# directories and zipfiles executable!)
92# So we fake it for testing purposes with a custom launch script
93launch_source = """\
94import sys, os.path, runpy
Nick Coghlanf088e5e2008-12-14 11:50:48 +000095sys.path.insert(0, %s)
Christian Heimescbf3b5c2007-12-03 21:02:03 +000096runpy._run_module_as_main(%r)
97"""
98
Nick Coghlanf088e5e2008-12-14 11:50:48 +000099def _make_launch_script(script_dir, script_basename, module_name, path=None):
100 if path is None:
101 path = "os.path.dirname(__file__)"
102 else:
103 path = repr(path)
104 source = launch_source % (path, module_name)
Brett Cannone0d88a12012-04-25 20:54:04 -0400105 to_return = make_script(script_dir, script_basename, source)
106 importlib.invalidate_caches()
107 return to_return
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000108
Christian Heimes9cd17752007-11-18 19:35:23 +0000109class CmdLineTest(unittest.TestCase):
Nick Coghland26c18a2010-08-17 13:06:11 +0000110 def _check_output(self, script_name, exit_code, data,
111 expected_file, expected_argv0,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000112 expected_path0, expected_package,
113 expected_loader):
Nick Coghland26c18a2010-08-17 13:06:11 +0000114 if verbose > 1:
Guido van Rossum87c0f1d2007-11-19 18:03:44 +0000115 print("Output from test script %r:" % script_name)
Serhiy Storchakab0749ca2015-03-25 01:33:19 +0200116 print(repr(data))
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000117 self.assertEqual(exit_code, 0)
Nick Coghlan85e729e2012-07-15 18:09:52 +1000118 printed_loader = '__loader__==%a' % expected_loader
Victor Stinnere3874ed2010-10-17 01:41:09 +0000119 printed_file = '__file__==%a' % expected_file
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000120 printed_package = '__package__==%r' % expected_package
Victor Stinnere3874ed2010-10-17 01:41:09 +0000121 printed_argv0 = 'sys.argv[0]==%a' % expected_argv0
122 printed_path0 = 'sys.path[0]==%a' % expected_path0
123 printed_cwd = 'cwd==%a' % os.getcwd()
Nick Coghland26c18a2010-08-17 13:06:11 +0000124 if verbose > 1:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000125 print('Expected output:')
126 print(printed_file)
127 print(printed_package)
128 print(printed_argv0)
Nick Coghland26c18a2010-08-17 13:06:11 +0000129 print(printed_cwd)
Nick Coghlan85e729e2012-07-15 18:09:52 +1000130 self.assertIn(printed_loader.encode('utf-8'), data)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000131 self.assertIn(printed_file.encode('utf-8'), data)
132 self.assertIn(printed_package.encode('utf-8'), data)
133 self.assertIn(printed_argv0.encode('utf-8'), data)
Nick Coghland26c18a2010-08-17 13:06:11 +0000134 self.assertIn(printed_path0.encode('utf-8'), data)
135 self.assertIn(printed_cwd.encode('utf-8'), data)
136
137 def _check_script(self, script_name, expected_file,
138 expected_argv0, expected_path0,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000139 expected_package, expected_loader,
Nick Coghland26c18a2010-08-17 13:06:11 +0000140 *cmd_line_switches):
Georg Brandlf5247e32010-10-14 08:08:56 +0000141 if not __debug__:
142 cmd_line_switches += ('-' + 'O' * sys.flags.optimize,)
Nick Coghlan37fc4012012-04-22 17:11:33 +1000143 run_args = cmd_line_switches + (script_name,) + tuple(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
Senthil Kumaranf01a3372012-07-04 19:28:16 -0700400 def test_dash_m_error_code_is_one(self):
401 # If a module is invoked with the -m command line flag
402 # and results in an error that the return code to the
403 # shell is '1'
Berker Peksagce643912015-05-06 06:33:17 +0300404 with support.temp_dir() as script_dir:
Nick Coghlan55175962013-07-28 22:11:50 +1000405 with support.change_cwd(path=script_dir):
Senthil Kumaranf01a3372012-07-04 19:28:16 -0700406 pkg_dir = os.path.join(script_dir, 'test_pkg')
407 make_pkg(pkg_dir)
408 script_name = _make_test_script(pkg_dir, 'other',
409 "if __name__ == '__main__': raise ValueError")
410 rc, out, err = assert_python_failure('-m', 'test_pkg.other', *example_args)
411 if verbose > 1:
Serhiy Storchakab0749ca2015-03-25 01:33:19 +0200412 print(repr(out))
Senthil Kumaranf01a3372012-07-04 19:28:16 -0700413 self.assertEqual(rc, 1)
414
Nick Coghlan1d5ccdb2012-05-21 23:03:30 +1000415 def test_pep_409_verbiage(self):
416 # Make sure PEP 409 syntax properly suppresses
417 # the context of an exception
418 script = textwrap.dedent("""\
419 try:
420 raise ValueError
421 except:
422 raise NameError from None
423 """)
Berker Peksagce643912015-05-06 06:33:17 +0300424 with support.temp_dir() as script_dir:
Nick Coghlan1d5ccdb2012-05-21 23:03:30 +1000425 script_name = _make_test_script(script_dir, 'script', script)
426 exitcode, stdout, stderr = assert_python_failure(script_name)
427 text = stderr.decode('ascii').split('\n')
428 self.assertEqual(len(text), 4)
429 self.assertTrue(text[0].startswith('Traceback'))
430 self.assertTrue(text[1].startswith(' File '))
431 self.assertTrue(text[3].startswith('NameError'))
432
Victor Stinnere667e982012-11-12 01:23:15 +0100433 def test_non_ascii(self):
434 # Mac OS X denies the creation of a file with an invalid UTF-8 name.
435 # Windows allows to create a name with an arbitrary bytes name, but
436 # Python cannot a undecodable bytes argument to a subprocess.
Victor Stinner0af71aa2013-01-03 01:50:30 +0100437 if (support.TESTFN_UNDECODABLE
438 and sys.platform not in ('win32', 'darwin')):
439 name = os.fsdecode(support.TESTFN_UNDECODABLE)
440 elif support.TESTFN_NONASCII:
Victor Stinnere667e982012-11-12 01:23:15 +0100441 name = support.TESTFN_NONASCII
442 else:
443 self.skipTest("need support.TESTFN_NONASCII")
444
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200445 # Issue #16218
Victor Stinnere667e982012-11-12 01:23:15 +0100446 source = 'print(ascii(__file__))\n'
447 script_name = _make_test_script(os.curdir, name, source)
448 self.addCleanup(support.unlink, script_name)
449 rc, stdout, stderr = assert_python_ok(script_name)
450 self.assertEqual(
451 ascii(script_name),
452 stdout.rstrip().decode('ascii'),
453 'stdout=%r stderr=%r' % (stdout, stderr))
454 self.assertEqual(0, rc)
455
Nick Coghland979e432014-02-09 10:43:21 +1000456 def test_issue20500_exit_with_exception_value(self):
457 script = textwrap.dedent("""\
458 import sys
459 error = None
460 try:
461 raise ValueError('some text')
462 except ValueError as err:
463 error = err
464
465 if error:
466 sys.exit(error)
467 """)
Berker Peksagce643912015-05-06 06:33:17 +0300468 with support.temp_dir() as script_dir:
Nick Coghland979e432014-02-09 10:43:21 +1000469 script_name = _make_test_script(script_dir, 'script', script)
470 exitcode, stdout, stderr = assert_python_failure(script_name)
471 text = stderr.decode('ascii')
472 self.assertEqual(text, "some text")
473
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200474
Christian Heimes9cd17752007-11-18 19:35:23 +0000475def test_main():
Nick Coghland26c18a2010-08-17 13:06:11 +0000476 support.run_unittest(CmdLineTest)
477 support.reap_children()
Christian Heimes9cd17752007-11-18 19:35:23 +0000478
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000479if __name__ == '__main__':
Christian Heimes9cd17752007-11-18 19:35:23 +0000480 test_main()