1 | n/a | # tests command line execution of scripts |
---|
2 | n/a | |
---|
3 | n/a | import contextlib |
---|
4 | n/a | import importlib |
---|
5 | n/a | import importlib.machinery |
---|
6 | n/a | import zipimport |
---|
7 | n/a | import unittest |
---|
8 | n/a | import sys |
---|
9 | n/a | import os |
---|
10 | n/a | import os.path |
---|
11 | n/a | import py_compile |
---|
12 | n/a | import subprocess |
---|
13 | n/a | import io |
---|
14 | n/a | |
---|
15 | n/a | import textwrap |
---|
16 | n/a | from test import support |
---|
17 | n/a | from test.support.script_helper import ( |
---|
18 | n/a | make_pkg, make_script, make_zip_pkg, make_zip_script, |
---|
19 | n/a | assert_python_ok, assert_python_failure, spawn_python, kill_python) |
---|
20 | n/a | |
---|
21 | n/a | verbose = support.verbose |
---|
22 | n/a | |
---|
23 | n/a | example_args = ['test1', 'test2', 'test3'] |
---|
24 | n/a | |
---|
25 | n/a | test_source = """\ |
---|
26 | n/a | # Script may be run with optimisation enabled, so don't rely on assert |
---|
27 | n/a | # statements being executed |
---|
28 | n/a | def assertEqual(lhs, rhs): |
---|
29 | n/a | if lhs != rhs: |
---|
30 | n/a | raise AssertionError('%r != %r' % (lhs, rhs)) |
---|
31 | n/a | def assertIdentical(lhs, rhs): |
---|
32 | n/a | if lhs is not rhs: |
---|
33 | n/a | raise AssertionError('%r is not %r' % (lhs, rhs)) |
---|
34 | n/a | # Check basic code execution |
---|
35 | n/a | result = ['Top level assignment'] |
---|
36 | n/a | def f(): |
---|
37 | n/a | result.append('Lower level reference') |
---|
38 | n/a | f() |
---|
39 | n/a | assertEqual(result, ['Top level assignment', 'Lower level reference']) |
---|
40 | n/a | # Check population of magic variables |
---|
41 | n/a | assertEqual(__name__, '__main__') |
---|
42 | n/a | from importlib.machinery import BuiltinImporter |
---|
43 | n/a | _loader = __loader__ if __loader__ is BuiltinImporter else type(__loader__) |
---|
44 | n/a | print('__loader__==%a' % _loader) |
---|
45 | n/a | print('__file__==%a' % __file__) |
---|
46 | n/a | print('__cached__==%a' % __cached__) |
---|
47 | n/a | print('__package__==%r' % __package__) |
---|
48 | n/a | # Check PEP 451 details |
---|
49 | n/a | import os.path |
---|
50 | n/a | if __package__ is not None: |
---|
51 | n/a | print('__main__ was located through the import system') |
---|
52 | n/a | assertIdentical(__spec__.loader, __loader__) |
---|
53 | n/a | expected_spec_name = os.path.splitext(os.path.basename(__file__))[0] |
---|
54 | n/a | if __package__: |
---|
55 | n/a | expected_spec_name = __package__ + "." + expected_spec_name |
---|
56 | n/a | assertEqual(__spec__.name, expected_spec_name) |
---|
57 | n/a | assertEqual(__spec__.parent, __package__) |
---|
58 | n/a | assertIdentical(__spec__.submodule_search_locations, None) |
---|
59 | n/a | assertEqual(__spec__.origin, __file__) |
---|
60 | n/a | if __spec__.cached is not None: |
---|
61 | n/a | assertEqual(__spec__.cached, __cached__) |
---|
62 | n/a | # Check the sys module |
---|
63 | n/a | import sys |
---|
64 | n/a | assertIdentical(globals(), sys.modules[__name__].__dict__) |
---|
65 | n/a | if __spec__ is not None: |
---|
66 | n/a | # XXX: We're not currently making __main__ available under its real name |
---|
67 | n/a | pass # assertIdentical(globals(), sys.modules[__spec__.name].__dict__) |
---|
68 | n/a | from test import test_cmd_line_script |
---|
69 | n/a | example_args_list = test_cmd_line_script.example_args |
---|
70 | n/a | assertEqual(sys.argv[1:], example_args_list) |
---|
71 | n/a | print('sys.argv[0]==%a' % sys.argv[0]) |
---|
72 | n/a | print('sys.path[0]==%a' % sys.path[0]) |
---|
73 | n/a | # Check the working directory |
---|
74 | n/a | import os |
---|
75 | n/a | print('cwd==%a' % os.getcwd()) |
---|
76 | n/a | """ |
---|
77 | n/a | |
---|
78 | n/a | def _make_test_script(script_dir, script_basename, source=test_source): |
---|
79 | n/a | to_return = make_script(script_dir, script_basename, source) |
---|
80 | n/a | importlib.invalidate_caches() |
---|
81 | n/a | return to_return |
---|
82 | n/a | |
---|
83 | n/a | def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, |
---|
84 | n/a | source=test_source, depth=1): |
---|
85 | n/a | to_return = make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, |
---|
86 | n/a | source, depth) |
---|
87 | n/a | importlib.invalidate_caches() |
---|
88 | n/a | return to_return |
---|
89 | n/a | |
---|
90 | n/a | # There's no easy way to pass the script directory in to get |
---|
91 | n/a | # -m to work (avoiding that is the whole point of making |
---|
92 | n/a | # directories and zipfiles executable!) |
---|
93 | n/a | # So we fake it for testing purposes with a custom launch script |
---|
94 | n/a | launch_source = """\ |
---|
95 | n/a | import sys, os.path, runpy |
---|
96 | n/a | sys.path.insert(0, %s) |
---|
97 | n/a | runpy._run_module_as_main(%r) |
---|
98 | n/a | """ |
---|
99 | n/a | |
---|
100 | n/a | def _make_launch_script(script_dir, script_basename, module_name, path=None): |
---|
101 | n/a | if path is None: |
---|
102 | n/a | path = "os.path.dirname(__file__)" |
---|
103 | n/a | else: |
---|
104 | n/a | path = repr(path) |
---|
105 | n/a | source = launch_source % (path, module_name) |
---|
106 | n/a | to_return = make_script(script_dir, script_basename, source) |
---|
107 | n/a | importlib.invalidate_caches() |
---|
108 | n/a | return to_return |
---|
109 | n/a | |
---|
110 | n/a | class CmdLineTest(unittest.TestCase): |
---|
111 | n/a | def _check_output(self, script_name, exit_code, data, |
---|
112 | n/a | expected_file, expected_argv0, |
---|
113 | n/a | expected_path0, expected_package, |
---|
114 | n/a | expected_loader): |
---|
115 | n/a | if verbose > 1: |
---|
116 | n/a | print("Output from test script %r:" % script_name) |
---|
117 | n/a | print(repr(data)) |
---|
118 | n/a | self.assertEqual(exit_code, 0) |
---|
119 | n/a | printed_loader = '__loader__==%a' % expected_loader |
---|
120 | n/a | printed_file = '__file__==%a' % expected_file |
---|
121 | n/a | printed_package = '__package__==%r' % expected_package |
---|
122 | n/a | printed_argv0 = 'sys.argv[0]==%a' % expected_argv0 |
---|
123 | n/a | printed_path0 = 'sys.path[0]==%a' % expected_path0 |
---|
124 | n/a | printed_cwd = 'cwd==%a' % os.getcwd() |
---|
125 | n/a | if verbose > 1: |
---|
126 | n/a | print('Expected output:') |
---|
127 | n/a | print(printed_file) |
---|
128 | n/a | print(printed_package) |
---|
129 | n/a | print(printed_argv0) |
---|
130 | n/a | print(printed_cwd) |
---|
131 | n/a | self.assertIn(printed_loader.encode('utf-8'), data) |
---|
132 | n/a | self.assertIn(printed_file.encode('utf-8'), data) |
---|
133 | n/a | self.assertIn(printed_package.encode('utf-8'), data) |
---|
134 | n/a | self.assertIn(printed_argv0.encode('utf-8'), data) |
---|
135 | n/a | self.assertIn(printed_path0.encode('utf-8'), data) |
---|
136 | n/a | self.assertIn(printed_cwd.encode('utf-8'), data) |
---|
137 | n/a | |
---|
138 | n/a | def _check_script(self, script_name, expected_file, |
---|
139 | n/a | expected_argv0, expected_path0, |
---|
140 | n/a | expected_package, expected_loader, |
---|
141 | n/a | *cmd_line_switches): |
---|
142 | n/a | run_args = [*support.optim_args_from_interpreter_flags(), |
---|
143 | n/a | *cmd_line_switches, script_name, *example_args] |
---|
144 | n/a | rc, out, err = assert_python_ok(*run_args, __isolated=False) |
---|
145 | n/a | self._check_output(script_name, rc, out + err, expected_file, |
---|
146 | n/a | expected_argv0, expected_path0, |
---|
147 | n/a | expected_package, expected_loader) |
---|
148 | n/a | |
---|
149 | n/a | def _check_import_error(self, script_name, expected_msg, |
---|
150 | n/a | *cmd_line_switches): |
---|
151 | n/a | run_args = cmd_line_switches + (script_name,) |
---|
152 | n/a | rc, out, err = assert_python_failure(*run_args) |
---|
153 | n/a | if verbose > 1: |
---|
154 | n/a | print('Output from test script %r:' % script_name) |
---|
155 | n/a | print(repr(err)) |
---|
156 | n/a | print('Expected output: %r' % expected_msg) |
---|
157 | n/a | self.assertIn(expected_msg.encode('utf-8'), err) |
---|
158 | n/a | |
---|
159 | n/a | def test_dash_c_loader(self): |
---|
160 | n/a | rc, out, err = assert_python_ok("-c", "print(__loader__)") |
---|
161 | n/a | expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8") |
---|
162 | n/a | self.assertIn(expected, out) |
---|
163 | n/a | |
---|
164 | n/a | def test_stdin_loader(self): |
---|
165 | n/a | # Unfortunately, there's no way to automatically test the fully |
---|
166 | n/a | # interactive REPL, since that code path only gets executed when |
---|
167 | n/a | # stdin is an interactive tty. |
---|
168 | n/a | p = spawn_python() |
---|
169 | n/a | try: |
---|
170 | n/a | p.stdin.write(b"print(__loader__)\n") |
---|
171 | n/a | p.stdin.flush() |
---|
172 | n/a | finally: |
---|
173 | n/a | out = kill_python(p) |
---|
174 | n/a | expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8") |
---|
175 | n/a | self.assertIn(expected, out) |
---|
176 | n/a | |
---|
177 | n/a | @contextlib.contextmanager |
---|
178 | n/a | def interactive_python(self, separate_stderr=False): |
---|
179 | n/a | if separate_stderr: |
---|
180 | n/a | p = spawn_python('-i', bufsize=1, stderr=subprocess.PIPE) |
---|
181 | n/a | stderr = p.stderr |
---|
182 | n/a | else: |
---|
183 | n/a | p = spawn_python('-i', bufsize=1, stderr=subprocess.STDOUT) |
---|
184 | n/a | stderr = p.stdout |
---|
185 | n/a | try: |
---|
186 | n/a | # Drain stderr until prompt |
---|
187 | n/a | while True: |
---|
188 | n/a | data = stderr.read(4) |
---|
189 | n/a | if data == b">>> ": |
---|
190 | n/a | break |
---|
191 | n/a | stderr.readline() |
---|
192 | n/a | yield p |
---|
193 | n/a | finally: |
---|
194 | n/a | kill_python(p) |
---|
195 | n/a | stderr.close() |
---|
196 | n/a | |
---|
197 | n/a | def check_repl_stdout_flush(self, separate_stderr=False): |
---|
198 | n/a | with self.interactive_python(separate_stderr) as p: |
---|
199 | n/a | p.stdin.write(b"print('foo')\n") |
---|
200 | n/a | p.stdin.flush() |
---|
201 | n/a | self.assertEqual(b'foo', p.stdout.readline().strip()) |
---|
202 | n/a | |
---|
203 | n/a | def check_repl_stderr_flush(self, separate_stderr=False): |
---|
204 | n/a | with self.interactive_python(separate_stderr) as p: |
---|
205 | n/a | p.stdin.write(b"1/0\n") |
---|
206 | n/a | p.stdin.flush() |
---|
207 | n/a | stderr = p.stderr if separate_stderr else p.stdout |
---|
208 | n/a | self.assertIn(b'Traceback ', stderr.readline()) |
---|
209 | n/a | self.assertIn(b'File "<stdin>"', stderr.readline()) |
---|
210 | n/a | self.assertIn(b'ZeroDivisionError', stderr.readline()) |
---|
211 | n/a | |
---|
212 | n/a | def test_repl_stdout_flush(self): |
---|
213 | n/a | self.check_repl_stdout_flush() |
---|
214 | n/a | |
---|
215 | n/a | def test_repl_stdout_flush_separate_stderr(self): |
---|
216 | n/a | self.check_repl_stdout_flush(True) |
---|
217 | n/a | |
---|
218 | n/a | def test_repl_stderr_flush(self): |
---|
219 | n/a | self.check_repl_stderr_flush() |
---|
220 | n/a | |
---|
221 | n/a | def test_repl_stderr_flush_separate_stderr(self): |
---|
222 | n/a | self.check_repl_stderr_flush(True) |
---|
223 | n/a | |
---|
224 | n/a | def test_basic_script(self): |
---|
225 | n/a | with support.temp_dir() as script_dir: |
---|
226 | n/a | script_name = _make_test_script(script_dir, 'script') |
---|
227 | n/a | self._check_script(script_name, script_name, script_name, |
---|
228 | n/a | script_dir, None, |
---|
229 | n/a | importlib.machinery.SourceFileLoader) |
---|
230 | n/a | |
---|
231 | n/a | def test_script_compiled(self): |
---|
232 | n/a | with support.temp_dir() as script_dir: |
---|
233 | n/a | script_name = _make_test_script(script_dir, 'script') |
---|
234 | n/a | py_compile.compile(script_name, doraise=True) |
---|
235 | n/a | os.remove(script_name) |
---|
236 | n/a | pyc_file = support.make_legacy_pyc(script_name) |
---|
237 | n/a | self._check_script(pyc_file, pyc_file, |
---|
238 | n/a | pyc_file, script_dir, None, |
---|
239 | n/a | importlib.machinery.SourcelessFileLoader) |
---|
240 | n/a | |
---|
241 | n/a | def test_directory(self): |
---|
242 | n/a | with support.temp_dir() as script_dir: |
---|
243 | n/a | script_name = _make_test_script(script_dir, '__main__') |
---|
244 | n/a | self._check_script(script_dir, script_name, script_dir, |
---|
245 | n/a | script_dir, '', |
---|
246 | n/a | importlib.machinery.SourceFileLoader) |
---|
247 | n/a | |
---|
248 | n/a | def test_directory_compiled(self): |
---|
249 | n/a | with support.temp_dir() as script_dir: |
---|
250 | n/a | script_name = _make_test_script(script_dir, '__main__') |
---|
251 | n/a | py_compile.compile(script_name, doraise=True) |
---|
252 | n/a | os.remove(script_name) |
---|
253 | n/a | pyc_file = support.make_legacy_pyc(script_name) |
---|
254 | n/a | self._check_script(script_dir, pyc_file, script_dir, |
---|
255 | n/a | script_dir, '', |
---|
256 | n/a | importlib.machinery.SourcelessFileLoader) |
---|
257 | n/a | |
---|
258 | n/a | def test_directory_error(self): |
---|
259 | n/a | with support.temp_dir() as script_dir: |
---|
260 | n/a | msg = "can't find '__main__' module in %r" % script_dir |
---|
261 | n/a | self._check_import_error(script_dir, msg) |
---|
262 | n/a | |
---|
263 | n/a | def test_zipfile(self): |
---|
264 | n/a | with support.temp_dir() as script_dir: |
---|
265 | n/a | script_name = _make_test_script(script_dir, '__main__') |
---|
266 | n/a | zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name) |
---|
267 | n/a | self._check_script(zip_name, run_name, zip_name, zip_name, '', |
---|
268 | n/a | zipimport.zipimporter) |
---|
269 | n/a | |
---|
270 | n/a | def test_zipfile_compiled(self): |
---|
271 | n/a | with support.temp_dir() as script_dir: |
---|
272 | n/a | script_name = _make_test_script(script_dir, '__main__') |
---|
273 | n/a | compiled_name = py_compile.compile(script_name, doraise=True) |
---|
274 | n/a | zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name) |
---|
275 | n/a | self._check_script(zip_name, run_name, zip_name, zip_name, '', |
---|
276 | n/a | zipimport.zipimporter) |
---|
277 | n/a | |
---|
278 | n/a | def test_zipfile_error(self): |
---|
279 | n/a | with support.temp_dir() as script_dir: |
---|
280 | n/a | script_name = _make_test_script(script_dir, 'not_main') |
---|
281 | n/a | zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name) |
---|
282 | n/a | msg = "can't find '__main__' module in %r" % zip_name |
---|
283 | n/a | self._check_import_error(zip_name, msg) |
---|
284 | n/a | |
---|
285 | n/a | def test_module_in_package(self): |
---|
286 | n/a | with support.temp_dir() as script_dir: |
---|
287 | n/a | pkg_dir = os.path.join(script_dir, 'test_pkg') |
---|
288 | n/a | make_pkg(pkg_dir) |
---|
289 | n/a | script_name = _make_test_script(pkg_dir, 'script') |
---|
290 | n/a | launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script') |
---|
291 | n/a | self._check_script(launch_name, script_name, script_name, |
---|
292 | n/a | script_dir, 'test_pkg', |
---|
293 | n/a | importlib.machinery.SourceFileLoader) |
---|
294 | n/a | |
---|
295 | n/a | def test_module_in_package_in_zipfile(self): |
---|
296 | n/a | with support.temp_dir() as script_dir: |
---|
297 | n/a | zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script') |
---|
298 | n/a | launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script', zip_name) |
---|
299 | n/a | self._check_script(launch_name, run_name, run_name, |
---|
300 | n/a | zip_name, 'test_pkg', zipimport.zipimporter) |
---|
301 | n/a | |
---|
302 | n/a | def test_module_in_subpackage_in_zipfile(self): |
---|
303 | n/a | with support.temp_dir() as script_dir: |
---|
304 | n/a | zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2) |
---|
305 | n/a | launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.test_pkg.script', zip_name) |
---|
306 | n/a | self._check_script(launch_name, run_name, run_name, |
---|
307 | n/a | zip_name, 'test_pkg.test_pkg', |
---|
308 | n/a | zipimport.zipimporter) |
---|
309 | n/a | |
---|
310 | n/a | def test_package(self): |
---|
311 | n/a | with support.temp_dir() as script_dir: |
---|
312 | n/a | pkg_dir = os.path.join(script_dir, 'test_pkg') |
---|
313 | n/a | make_pkg(pkg_dir) |
---|
314 | n/a | script_name = _make_test_script(pkg_dir, '__main__') |
---|
315 | n/a | launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg') |
---|
316 | n/a | self._check_script(launch_name, script_name, |
---|
317 | n/a | script_name, script_dir, 'test_pkg', |
---|
318 | n/a | importlib.machinery.SourceFileLoader) |
---|
319 | n/a | |
---|
320 | n/a | def test_package_compiled(self): |
---|
321 | n/a | with support.temp_dir() as script_dir: |
---|
322 | n/a | pkg_dir = os.path.join(script_dir, 'test_pkg') |
---|
323 | n/a | make_pkg(pkg_dir) |
---|
324 | n/a | script_name = _make_test_script(pkg_dir, '__main__') |
---|
325 | n/a | compiled_name = py_compile.compile(script_name, doraise=True) |
---|
326 | n/a | os.remove(script_name) |
---|
327 | n/a | pyc_file = support.make_legacy_pyc(script_name) |
---|
328 | n/a | launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg') |
---|
329 | n/a | self._check_script(launch_name, pyc_file, |
---|
330 | n/a | pyc_file, script_dir, 'test_pkg', |
---|
331 | n/a | importlib.machinery.SourcelessFileLoader) |
---|
332 | n/a | |
---|
333 | n/a | def test_package_error(self): |
---|
334 | n/a | with support.temp_dir() as script_dir: |
---|
335 | n/a | pkg_dir = os.path.join(script_dir, 'test_pkg') |
---|
336 | n/a | make_pkg(pkg_dir) |
---|
337 | n/a | msg = ("'test_pkg' is a package and cannot " |
---|
338 | n/a | "be directly executed") |
---|
339 | n/a | launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg') |
---|
340 | n/a | self._check_import_error(launch_name, msg) |
---|
341 | n/a | |
---|
342 | n/a | def test_package_recursion(self): |
---|
343 | n/a | with support.temp_dir() as script_dir: |
---|
344 | n/a | pkg_dir = os.path.join(script_dir, 'test_pkg') |
---|
345 | n/a | make_pkg(pkg_dir) |
---|
346 | n/a | main_dir = os.path.join(pkg_dir, '__main__') |
---|
347 | n/a | make_pkg(main_dir) |
---|
348 | n/a | msg = ("Cannot use package as __main__ module; " |
---|
349 | n/a | "'test_pkg' is a package and cannot " |
---|
350 | n/a | "be directly executed") |
---|
351 | n/a | launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg') |
---|
352 | n/a | self._check_import_error(launch_name, msg) |
---|
353 | n/a | |
---|
354 | n/a | def test_issue8202(self): |
---|
355 | n/a | # Make sure package __init__ modules see "-m" in sys.argv0 while |
---|
356 | n/a | # searching for the module to execute |
---|
357 | n/a | with support.temp_dir() as script_dir: |
---|
358 | n/a | with support.change_cwd(path=script_dir): |
---|
359 | n/a | pkg_dir = os.path.join(script_dir, 'test_pkg') |
---|
360 | n/a | make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])") |
---|
361 | n/a | script_name = _make_test_script(pkg_dir, 'script') |
---|
362 | n/a | rc, out, err = assert_python_ok('-m', 'test_pkg.script', *example_args, __isolated=False) |
---|
363 | n/a | if verbose > 1: |
---|
364 | n/a | print(repr(out)) |
---|
365 | n/a | expected = "init_argv0==%r" % '-m' |
---|
366 | n/a | self.assertIn(expected.encode('utf-8'), out) |
---|
367 | n/a | self._check_output(script_name, rc, out, |
---|
368 | n/a | script_name, script_name, '', 'test_pkg', |
---|
369 | n/a | importlib.machinery.SourceFileLoader) |
---|
370 | n/a | |
---|
371 | n/a | def test_issue8202_dash_c_file_ignored(self): |
---|
372 | n/a | # Make sure a "-c" file in the current directory |
---|
373 | n/a | # does not alter the value of sys.path[0] |
---|
374 | n/a | with support.temp_dir() as script_dir: |
---|
375 | n/a | with support.change_cwd(path=script_dir): |
---|
376 | n/a | with open("-c", "w") as f: |
---|
377 | n/a | f.write("data") |
---|
378 | n/a | rc, out, err = assert_python_ok('-c', |
---|
379 | n/a | 'import sys; print("sys.path[0]==%r" % sys.path[0])', |
---|
380 | n/a | __isolated=False) |
---|
381 | n/a | if verbose > 1: |
---|
382 | n/a | print(repr(out)) |
---|
383 | n/a | expected = "sys.path[0]==%r" % '' |
---|
384 | n/a | self.assertIn(expected.encode('utf-8'), out) |
---|
385 | n/a | |
---|
386 | n/a | def test_issue8202_dash_m_file_ignored(self): |
---|
387 | n/a | # Make sure a "-m" file in the current directory |
---|
388 | n/a | # does not alter the value of sys.path[0] |
---|
389 | n/a | with support.temp_dir() as script_dir: |
---|
390 | n/a | script_name = _make_test_script(script_dir, 'other') |
---|
391 | n/a | with support.change_cwd(path=script_dir): |
---|
392 | n/a | with open("-m", "w") as f: |
---|
393 | n/a | f.write("data") |
---|
394 | n/a | rc, out, err = assert_python_ok('-m', 'other', *example_args, |
---|
395 | n/a | __isolated=False) |
---|
396 | n/a | self._check_output(script_name, rc, out, |
---|
397 | n/a | script_name, script_name, '', '', |
---|
398 | n/a | importlib.machinery.SourceFileLoader) |
---|
399 | n/a | |
---|
400 | n/a | @contextlib.contextmanager |
---|
401 | n/a | def setup_test_pkg(self, *args): |
---|
402 | n/a | with support.temp_dir() as script_dir, \ |
---|
403 | n/a | support.change_cwd(path=script_dir): |
---|
404 | n/a | pkg_dir = os.path.join(script_dir, 'test_pkg') |
---|
405 | n/a | make_pkg(pkg_dir, *args) |
---|
406 | n/a | yield pkg_dir |
---|
407 | n/a | |
---|
408 | n/a | def check_dash_m_failure(self, *args): |
---|
409 | n/a | rc, out, err = assert_python_failure('-m', *args, __isolated=False) |
---|
410 | n/a | if verbose > 1: |
---|
411 | n/a | print(repr(out)) |
---|
412 | n/a | self.assertEqual(rc, 1) |
---|
413 | n/a | return err |
---|
414 | n/a | |
---|
415 | n/a | def test_dash_m_error_code_is_one(self): |
---|
416 | n/a | # If a module is invoked with the -m command line flag |
---|
417 | n/a | # and results in an error that the return code to the |
---|
418 | n/a | # shell is '1' |
---|
419 | n/a | with self.setup_test_pkg() as pkg_dir: |
---|
420 | n/a | script_name = _make_test_script(pkg_dir, 'other', |
---|
421 | n/a | "if __name__ == '__main__': raise ValueError") |
---|
422 | n/a | err = self.check_dash_m_failure('test_pkg.other', *example_args) |
---|
423 | n/a | self.assertIn(b'ValueError', err) |
---|
424 | n/a | |
---|
425 | n/a | def test_dash_m_errors(self): |
---|
426 | n/a | # Exercise error reporting for various invalid package executions |
---|
427 | n/a | tests = ( |
---|
428 | n/a | ('builtins', br'No code object available'), |
---|
429 | n/a | ('builtins.x', br'Error while finding module specification.*' |
---|
430 | n/a | br'AttributeError'), |
---|
431 | n/a | ('builtins.x.y', br'Error while finding module specification.*' |
---|
432 | n/a | br'ModuleNotFoundError.*No module named.*not a package'), |
---|
433 | n/a | ('os.path', br'loader.*cannot handle'), |
---|
434 | n/a | ('importlib', br'No module named.*' |
---|
435 | n/a | br'is a package and cannot be directly executed'), |
---|
436 | n/a | ('importlib.nonexistant', br'No module named'), |
---|
437 | n/a | ('.unittest', br'Relative module names not supported'), |
---|
438 | n/a | ) |
---|
439 | n/a | for name, regex in tests: |
---|
440 | n/a | with self.subTest(name): |
---|
441 | n/a | rc, _, err = assert_python_failure('-m', name) |
---|
442 | n/a | self.assertEqual(rc, 1) |
---|
443 | n/a | self.assertRegex(err, regex) |
---|
444 | n/a | self.assertNotIn(b'Traceback', err) |
---|
445 | n/a | |
---|
446 | n/a | def test_dash_m_bad_pyc(self): |
---|
447 | n/a | with support.temp_dir() as script_dir, \ |
---|
448 | n/a | support.change_cwd(path=script_dir): |
---|
449 | n/a | os.mkdir('test_pkg') |
---|
450 | n/a | # Create invalid *.pyc as empty file |
---|
451 | n/a | with open('test_pkg/__init__.pyc', 'wb'): |
---|
452 | n/a | pass |
---|
453 | n/a | err = self.check_dash_m_failure('test_pkg') |
---|
454 | n/a | self.assertRegex(err, |
---|
455 | n/a | br'Error while finding module specification.*' |
---|
456 | n/a | br'ImportError.*bad magic number') |
---|
457 | n/a | self.assertNotIn(b'is a package', err) |
---|
458 | n/a | self.assertNotIn(b'Traceback', err) |
---|
459 | n/a | |
---|
460 | n/a | def test_dash_m_init_traceback(self): |
---|
461 | n/a | # These were wrapped in an ImportError and tracebacks were |
---|
462 | n/a | # suppressed; see Issue 14285 |
---|
463 | n/a | exceptions = (ImportError, AttributeError, TypeError, ValueError) |
---|
464 | n/a | for exception in exceptions: |
---|
465 | n/a | exception = exception.__name__ |
---|
466 | n/a | init = "raise {0}('Exception in __init__.py')".format(exception) |
---|
467 | n/a | with self.subTest(exception), \ |
---|
468 | n/a | self.setup_test_pkg(init) as pkg_dir: |
---|
469 | n/a | err = self.check_dash_m_failure('test_pkg') |
---|
470 | n/a | self.assertIn(exception.encode('ascii'), err) |
---|
471 | n/a | self.assertIn(b'Exception in __init__.py', err) |
---|
472 | n/a | self.assertIn(b'Traceback', err) |
---|
473 | n/a | |
---|
474 | n/a | def test_dash_m_main_traceback(self): |
---|
475 | n/a | # Ensure that an ImportError's traceback is reported |
---|
476 | n/a | with self.setup_test_pkg() as pkg_dir: |
---|
477 | n/a | main = "raise ImportError('Exception in __main__ module')" |
---|
478 | n/a | _make_test_script(pkg_dir, '__main__', main) |
---|
479 | n/a | err = self.check_dash_m_failure('test_pkg') |
---|
480 | n/a | self.assertIn(b'ImportError', err) |
---|
481 | n/a | self.assertIn(b'Exception in __main__ module', err) |
---|
482 | n/a | self.assertIn(b'Traceback', err) |
---|
483 | n/a | |
---|
484 | n/a | def test_pep_409_verbiage(self): |
---|
485 | n/a | # Make sure PEP 409 syntax properly suppresses |
---|
486 | n/a | # the context of an exception |
---|
487 | n/a | script = textwrap.dedent("""\ |
---|
488 | n/a | try: |
---|
489 | n/a | raise ValueError |
---|
490 | n/a | except: |
---|
491 | n/a | raise NameError from None |
---|
492 | n/a | """) |
---|
493 | n/a | with support.temp_dir() as script_dir: |
---|
494 | n/a | script_name = _make_test_script(script_dir, 'script', script) |
---|
495 | n/a | exitcode, stdout, stderr = assert_python_failure(script_name) |
---|
496 | n/a | text = stderr.decode('ascii').split('\n') |
---|
497 | n/a | self.assertEqual(len(text), 4) |
---|
498 | n/a | self.assertTrue(text[0].startswith('Traceback')) |
---|
499 | n/a | self.assertTrue(text[1].startswith(' File ')) |
---|
500 | n/a | self.assertTrue(text[3].startswith('NameError')) |
---|
501 | n/a | |
---|
502 | n/a | def test_non_ascii(self): |
---|
503 | n/a | # Mac OS X denies the creation of a file with an invalid UTF-8 name. |
---|
504 | n/a | # Windows allows creating a name with an arbitrary bytes name, but |
---|
505 | n/a | # Python cannot a undecodable bytes argument to a subprocess. |
---|
506 | n/a | if (support.TESTFN_UNDECODABLE |
---|
507 | n/a | and sys.platform not in ('win32', 'darwin')): |
---|
508 | n/a | name = os.fsdecode(support.TESTFN_UNDECODABLE) |
---|
509 | n/a | elif support.TESTFN_NONASCII: |
---|
510 | n/a | name = support.TESTFN_NONASCII |
---|
511 | n/a | else: |
---|
512 | n/a | self.skipTest("need support.TESTFN_NONASCII") |
---|
513 | n/a | |
---|
514 | n/a | # Issue #16218 |
---|
515 | n/a | source = 'print(ascii(__file__))\n' |
---|
516 | n/a | script_name = _make_test_script(os.curdir, name, source) |
---|
517 | n/a | self.addCleanup(support.unlink, script_name) |
---|
518 | n/a | rc, stdout, stderr = assert_python_ok(script_name) |
---|
519 | n/a | self.assertEqual( |
---|
520 | n/a | ascii(script_name), |
---|
521 | n/a | stdout.rstrip().decode('ascii'), |
---|
522 | n/a | 'stdout=%r stderr=%r' % (stdout, stderr)) |
---|
523 | n/a | self.assertEqual(0, rc) |
---|
524 | n/a | |
---|
525 | n/a | def test_issue20500_exit_with_exception_value(self): |
---|
526 | n/a | script = textwrap.dedent("""\ |
---|
527 | n/a | import sys |
---|
528 | n/a | error = None |
---|
529 | n/a | try: |
---|
530 | n/a | raise ValueError('some text') |
---|
531 | n/a | except ValueError as err: |
---|
532 | n/a | error = err |
---|
533 | n/a | |
---|
534 | n/a | if error: |
---|
535 | n/a | sys.exit(error) |
---|
536 | n/a | """) |
---|
537 | n/a | with support.temp_dir() as script_dir: |
---|
538 | n/a | script_name = _make_test_script(script_dir, 'script', script) |
---|
539 | n/a | exitcode, stdout, stderr = assert_python_failure(script_name) |
---|
540 | n/a | text = stderr.decode('ascii') |
---|
541 | n/a | self.assertEqual(text, "some text") |
---|
542 | n/a | |
---|
543 | n/a | def test_syntaxerror_unindented_caret_position(self): |
---|
544 | n/a | script = "1 + 1 = 2\n" |
---|
545 | n/a | with support.temp_dir() as script_dir: |
---|
546 | n/a | script_name = _make_test_script(script_dir, 'script', script) |
---|
547 | n/a | exitcode, stdout, stderr = assert_python_failure(script_name) |
---|
548 | n/a | text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read() |
---|
549 | n/a | # Confirm that the caret is located under the first 1 character |
---|
550 | n/a | self.assertIn("\n 1 + 1 = 2\n ^", text) |
---|
551 | n/a | |
---|
552 | n/a | def test_syntaxerror_indented_caret_position(self): |
---|
553 | n/a | script = textwrap.dedent("""\ |
---|
554 | n/a | if True: |
---|
555 | n/a | 1 + 1 = 2 |
---|
556 | n/a | """) |
---|
557 | n/a | with support.temp_dir() as script_dir: |
---|
558 | n/a | script_name = _make_test_script(script_dir, 'script', script) |
---|
559 | n/a | exitcode, stdout, stderr = assert_python_failure(script_name) |
---|
560 | n/a | text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read() |
---|
561 | n/a | # Confirm that the caret is located under the first 1 character |
---|
562 | n/a | self.assertIn("\n 1 + 1 = 2\n ^", text) |
---|
563 | n/a | |
---|
564 | n/a | # Try the same with a form feed at the start of the indented line |
---|
565 | n/a | script = ( |
---|
566 | n/a | "if True:\n" |
---|
567 | n/a | "\f 1 + 1 = 2\n" |
---|
568 | n/a | ) |
---|
569 | n/a | script_name = _make_test_script(script_dir, "script", script) |
---|
570 | n/a | exitcode, stdout, stderr = assert_python_failure(script_name) |
---|
571 | n/a | text = io.TextIOWrapper(io.BytesIO(stderr), "ascii").read() |
---|
572 | n/a | self.assertNotIn("\f", text) |
---|
573 | n/a | self.assertIn("\n 1 + 1 = 2\n ^", text) |
---|
574 | n/a | |
---|
575 | n/a | |
---|
576 | n/a | def test_main(): |
---|
577 | n/a | support.run_unittest(CmdLineTest) |
---|
578 | n/a | support.reap_children() |
---|
579 | n/a | |
---|
580 | n/a | if __name__ == '__main__': |
---|
581 | n/a | test_main() |
---|