Debian Codegraph @

lib-python/3/test/test_cmd_line_script.py

raw symbols SCIP
1 # tests command line execution of scripts
2
3 import contextlib
4 import importlib
5 import importlib.machinery
6 import zipimport
7 import unittest
8 import sys
9 import os
10 import os.path
11 import py_compile
12 import subprocess
13 import io
14
15 import textwrap
16 from test import support
17 from test.support import import_helper
18 from test.support import os_helper
19 from test.support.script_helper import (
20 make_pkg, make_script, make_zip_pkg, make_zip_script,
21 assert_python_ok, assert_python_failure, spawn_python, kill_python)
22
23 verbose = support.verbose
24
25 example_args = ['test1', 'test2', 'test3']
26
27 test_source = """\
28 # Script may be run with optimisation enabled, so don't rely on assert
29 # statements being executed
30 def assertEqual(lhs, rhs):
31 if lhs != rhs:
32 raise AssertionError('%r != %r' % (lhs, rhs))
33 def assertIdentical(lhs, rhs):
34 if lhs is not rhs:
35 raise AssertionError('%r is not %r' % (lhs, rhs))
36 # Check basic code execution
37 result = ['Top level assignment']
38 def f():
39 result.append('Lower level reference')
40 f()
41 assertEqual(result, ['Top level assignment', 'Lower level reference'])
42 # Check population of magic variables
43 assertEqual(__name__, '__main__')
44 from importlib.machinery import BuiltinImporter
45 _loader = __loader__ if __loader__ is BuiltinImporter else type(__loader__)
46 print('__loader__==%a' % _loader)
47 print('__file__==%a' % __file__)
48 print('__cached__==%a' % __cached__)
49 print('__package__==%r' % __package__)
50 # Check PEP 451 details
51 import os.path
52 if __package__ is not None:
53 print('__main__ was located through the import system')
54 assertIdentical(__spec__.loader, __loader__)
55 expected_spec_name = os.path.splitext(os.path.basename(__file__))[0]
56 if __package__:
57 expected_spec_name = __package__ + "." + expected_spec_name
58 assertEqual(__spec__.name, expected_spec_name)
59 assertEqual(__spec__.parent, __package__)
60 assertIdentical(__spec__.submodule_search_locations, None)
61 assertEqual(__spec__.origin, __file__)
62 if __spec__.cached is not None:
63 assertEqual(__spec__.cached, __cached__)
64 # Check the sys module
65 import sys
66 assertIdentical(globals(), sys.modules[__name__].__dict__)
67 if __spec__ is not None:
68 # XXX: We're not currently making __main__ available under its real name
69 pass # assertIdentical(globals(), sys.modules[__spec__.name].__dict__)
70 from test import test_cmd_line_script
71 example_args_list = test_cmd_line_script.example_args
72 assertEqual(sys.argv[1:], example_args_list)
73 print('sys.argv[0]==%a' % sys.argv[0])
74 print('sys.path[0]==%a' % sys.path[0])
75 # Check the working directory
76 import os
77 print('cwd==%a' % os.getcwd())
78 """
79
80 def _make_test_script(script_dir, script_basename, source=test_source):
81 to_return = make_script(script_dir, script_basename, source)
82 importlib.invalidate_caches()
83 return to_return
84
85 def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
86 source=test_source, depth=1):
87 to_return = make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
88 source, depth)
89 importlib.invalidate_caches()
90 return to_return
91
92 class CmdLineTest(unittest.TestCase):
93 def _check_output(self, script_name, exit_code, data,
94 expected_file, expected_argv0,
95 expected_path0, expected_package,
96 expected_loader, expected_cwd=None):
97 if verbose > 1:
98 print("Output from test script %r:" % script_name)
99 print(repr(data))
100 self.assertEqual(exit_code, 0)
101 printed_loader = '__loader__==%a' % expected_loader
102 printed_file = '__file__==%a' % expected_file
103 printed_package = '__package__==%r' % expected_package
104 printed_argv0 = 'sys.argv[0]==%a' % expected_argv0
105 printed_path0 = 'sys.path[0]==%a' % expected_path0
106 if expected_cwd is None:
107 expected_cwd = os.getcwd()
108 printed_cwd = 'cwd==%a' % expected_cwd
109 if verbose > 1:
110 print('Expected output:')
111 print(printed_file)
112 print(printed_package)
113 print(printed_argv0)
114 print(printed_cwd)
115 self.assertIn(printed_loader.encode('utf-8'), data)
116 self.assertIn(printed_file.encode('utf-8'), data)
117 self.assertIn(printed_package.encode('utf-8'), data)
118 self.assertIn(printed_argv0.encode('utf-8'), data)
119 # PYTHONSAFEPATH=1 changes the default sys.path[0]
120 if not sys.flags.safe_path:
121 self.assertIn(printed_path0.encode('utf-8'), data)
122 self.assertIn(printed_cwd.encode('utf-8'), data)
123
124 def _check_script(self, script_exec_args, expected_file,
125 expected_argv0, expected_path0,
126 expected_package, expected_loader,
127 *cmd_line_switches, cwd=None, **env_vars):
128 if isinstance(script_exec_args, str):
129 script_exec_args = [script_exec_args]
130 run_args = [*support.optim_args_from_interpreter_flags(),
131 *cmd_line_switches, *script_exec_args, *example_args]
132 rc, out, err = assert_python_ok(
133 *run_args, __isolated=False, __cwd=cwd, **env_vars
134 )
135 self._check_output(script_exec_args, rc, out + err, expected_file,
136 expected_argv0, expected_path0,
137 expected_package, expected_loader, cwd)
138
139 def _check_import_error(self, script_exec_args, expected_msg,
140 *cmd_line_switches, cwd=None, **env_vars):
141 if isinstance(script_exec_args, str):
142 script_exec_args = (script_exec_args,)
143 else:
144 script_exec_args = tuple(script_exec_args)
145 run_args = cmd_line_switches + script_exec_args
146 rc, out, err = assert_python_failure(
147 *run_args, __isolated=False, __cwd=cwd, **env_vars
148 )
149 if verbose > 1:
150 print(f'Output from test script {script_exec_args!r:}')
151 print(repr(err))
152 print('Expected output: %r' % expected_msg)
153 self.assertIn(expected_msg.encode('utf-8'), err)
154
155 def test_dash_c_loader(self):
156 rc, out, err = assert_python_ok("-c", "print(__loader__)")
157 expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8")
158 self.assertIn(expected, out)
159
160 def test_stdin_loader(self):
161 # Unfortunately, there's no way to automatically test the fully
162 # interactive REPL, since that code path only gets executed when
163 # stdin is an interactive tty.
164 p = spawn_python()
165 try:
166 p.stdin.write(b"print(__loader__)\n")
167 p.stdin.flush()
168 finally:
169 out = kill_python(p)
170 expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8")
171 self.assertIn(expected, out)
172
173 @contextlib.contextmanager
174 def interactive_python(self, separate_stderr=False):
175 if separate_stderr:
176 p = spawn_python('-i', stderr=subprocess.PIPE)
177 stderr = p.stderr
178 else:
179 p = spawn_python('-i', stderr=subprocess.STDOUT)
180 stderr = p.stdout
181 try:
182 # Drain stderr until prompt
183 if support.check_impl_detail(pypy=True):
184 ps1 = b">>>> "
185 # PyPy: the prompt is still printed to stdout, like it
186 # is in CPython 2.7. This messes up the logic below
187 # if stdout and stderr are different. Skip for now.
188 if separate_stderr:
189 self.skipTest("the prompt is still written to "
190 "stdout in pypy")
191 else:
192 ps1 = b">>> "
193 while True:
194 data = stderr.read(len(ps1))
195 if data == ps1:
196 break
197 stderr.readline()
198 yield p
199 finally:
200 kill_python(p)
201 stderr.close()
202
203 def check_repl_stdout_flush(self, separate_stderr=False):
204 with self.interactive_python(separate_stderr) as p:
205 p.stdin.write(b"print('foo')\n")
206 p.stdin.flush()
207 self.assertEqual(b'foo', p.stdout.readline().strip())
208
209 def check_repl_stderr_flush(self, separate_stderr=False):
210 with self.interactive_python(separate_stderr) as p:
211 p.stdin.write(b"1/0\n")
212 p.stdin.flush()
213 stderr = p.stderr if separate_stderr else p.stdout
214 self.assertIn(b'Traceback ', stderr.readline())
215 self.assertIn(b'File "<stdin>"', stderr.readline())
216 self.assertIn(b'ZeroDivisionError', stderr.readline())
217
218 def test_repl_stdout_flush(self):
219 self.check_repl_stdout_flush()
220
221 def test_repl_stdout_flush_separate_stderr(self):
222 self.check_repl_stdout_flush(True)
223
224 def test_repl_stderr_flush(self):
225 self.check_repl_stderr_flush()
226
227 def test_repl_stderr_flush_separate_stderr(self):
228 self.check_repl_stderr_flush(True)
229
230 def test_basic_script(self):
231 with os_helper.temp_dir() as script_dir:
232 script_name = _make_test_script(script_dir, 'script')
233 self._check_script(script_name, script_name, script_name,
234 script_dir, None,
235 importlib.machinery.SourceFileLoader,
236 expected_cwd=script_dir)
237
238 def test_script_abspath(self):
239 # pass the script using the relative path, expect the absolute path
240 # in __file__
241 with os_helper.temp_cwd() as script_dir:
242 self.assertTrue(os.path.isabs(script_dir), script_dir)
243
244 script_name = _make_test_script(script_dir, 'script')
245 relative_name = os.path.basename(script_name)
246 self._check_script(relative_name, script_name, relative_name,
247 script_dir, None,
248 importlib.machinery.SourceFileLoader)
249
250 def test_script_compiled(self):
251 with os_helper.temp_dir() as script_dir:
252 script_name = _make_test_script(script_dir, 'script')
253 py_compile.compile(script_name, doraise=True)
254 os.remove(script_name)
255 pyc_file = import_helper.make_legacy_pyc(script_name)
256 self._check_script(pyc_file, pyc_file,
257 pyc_file, script_dir, None,
258 importlib.machinery.SourcelessFileLoader)
259
260 def test_directory(self):
261 with os_helper.temp_dir() as script_dir:
262 script_name = _make_test_script(script_dir, '__main__')
263 self._check_script(script_dir, script_name, script_dir,
264 script_dir, '',
265 importlib.machinery.SourceFileLoader)
266
267 def test_directory_compiled(self):
268 with os_helper.temp_dir() as script_dir:
269 script_name = _make_test_script(script_dir, '__main__')
270 py_compile.compile(script_name, doraise=True)
271 os.remove(script_name)
272 pyc_file = import_helper.make_legacy_pyc(script_name)
273 self._check_script(script_dir, pyc_file, script_dir,
274 script_dir, '',
275 importlib.machinery.SourcelessFileLoader)
276
277 def test_directory_error(self):
278 with os_helper.temp_dir() as script_dir:
279 msg = "can't find '__main__' module in %r" % script_dir
280 self._check_import_error(script_dir, msg)
281
282 def test_zipfile(self):
283 with os_helper.temp_dir() as script_dir:
284 script_name = _make_test_script(script_dir, '__main__')
285 zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name)
286 self._check_script(zip_name, run_name, zip_name, zip_name, '',
287 zipimport.zipimporter)
288
289 def test_zipfile_compiled_timestamp(self):
290 with os_helper.temp_dir() as script_dir:
291 script_name = _make_test_script(script_dir, '__main__')
292 compiled_name = py_compile.compile(
293 script_name, doraise=True,
294 invalidation_mode=py_compile.PycInvalidationMode.TIMESTAMP)
295 zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name)
296 self._check_script(zip_name, run_name, zip_name, zip_name, '',
297 zipimport.zipimporter)
298
299 def test_zipfile_compiled_checked_hash(self):
300 with os_helper.temp_dir() as script_dir:
301 script_name = _make_test_script(script_dir, '__main__')
302 compiled_name = py_compile.compile(
303 script_name, doraise=True,
304 invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH)
305 zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name)
306 self._check_script(zip_name, run_name, zip_name, zip_name, '',
307 zipimport.zipimporter)
308
309 def test_zipfile_compiled_unchecked_hash(self):
310 with os_helper.temp_dir() as script_dir:
311 script_name = _make_test_script(script_dir, '__main__')
312 compiled_name = py_compile.compile(
313 script_name, doraise=True,
314 invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH)
315 zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name)
316 self._check_script(zip_name, run_name, zip_name, zip_name, '',
317 zipimport.zipimporter)
318
319 def test_zipfile_error(self):
320 with os_helper.temp_dir() as script_dir:
321 script_name = _make_test_script(script_dir, 'not_main')
322 zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name)
323 msg = "can't find '__main__' module in %r" % zip_name
324 self._check_import_error(zip_name, msg)
325
326 def test_module_in_package(self):
327 with os_helper.temp_dir() as script_dir:
328 pkg_dir = os.path.join(script_dir, 'test_pkg')
329 make_pkg(pkg_dir)
330 script_name = _make_test_script(pkg_dir, 'script')
331 self._check_script(["-m", "test_pkg.script"], script_name, script_name,
332 script_dir, 'test_pkg',
333 importlib.machinery.SourceFileLoader,
334 cwd=script_dir)
335
336 def test_module_in_package_in_zipfile(self):
337 with os_helper.temp_dir() as script_dir:
338 zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script')
339 self._check_script(["-m", "test_pkg.script"], run_name, run_name,
340 script_dir, 'test_pkg', zipimport.zipimporter,
341 PYTHONPATH=zip_name, cwd=script_dir)
342
343 def test_module_in_subpackage_in_zipfile(self):
344 with os_helper.temp_dir() as script_dir:
345 zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2)
346 self._check_script(["-m", "test_pkg.test_pkg.script"], run_name, run_name,
347 script_dir, 'test_pkg.test_pkg',
348 zipimport.zipimporter,
349 PYTHONPATH=zip_name, cwd=script_dir)
350
351 def test_package(self):
352 with os_helper.temp_dir() as script_dir:
353 pkg_dir = os.path.join(script_dir, 'test_pkg')
354 make_pkg(pkg_dir)
355 script_name = _make_test_script(pkg_dir, '__main__')
356 self._check_script(["-m", "test_pkg"], script_name,
357 script_name, script_dir, 'test_pkg',
358 importlib.machinery.SourceFileLoader,
359 cwd=script_dir)
360
361 def test_package_compiled(self):
362 with os_helper.temp_dir() as script_dir:
363 pkg_dir = os.path.join(script_dir, 'test_pkg')
364 make_pkg(pkg_dir)
365 script_name = _make_test_script(pkg_dir, '__main__')
366 compiled_name = py_compile.compile(script_name, doraise=True)
367 os.remove(script_name)
368 pyc_file = import_helper.make_legacy_pyc(script_name)
369 self._check_script(["-m", "test_pkg"], pyc_file,
370 pyc_file, script_dir, 'test_pkg',
371 importlib.machinery.SourcelessFileLoader,
372 cwd=script_dir)
373
374 def test_package_error(self):
375 with os_helper.temp_dir() as script_dir:
376 pkg_dir = os.path.join(script_dir, 'test_pkg')
377 make_pkg(pkg_dir)
378 msg = ("'test_pkg' is a package and cannot "
379 "be directly executed")
380 self._check_import_error(["-m", "test_pkg"], msg, cwd=script_dir)
381
382 def test_package_recursion(self):
383 with os_helper.temp_dir() as script_dir:
384 pkg_dir = os.path.join(script_dir, 'test_pkg')
385 make_pkg(pkg_dir)
386 main_dir = os.path.join(pkg_dir, '__main__')
387 make_pkg(main_dir)
388 msg = ("Cannot use package as __main__ module; "
389 "'test_pkg' is a package and cannot "
390 "be directly executed")
391 self._check_import_error(["-m", "test_pkg"], msg, cwd=script_dir)
392
393 def test_issue8202(self):
394 # Make sure package __init__ modules see "-m" in sys.argv0 while
395 # searching for the module to execute
396 with os_helper.temp_dir() as script_dir:
397 with os_helper.change_cwd(path=script_dir):
398 pkg_dir = os.path.join(script_dir, 'test_pkg')
399 make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])")
400 script_name = _make_test_script(pkg_dir, 'script')
401 rc, out, err = assert_python_ok('-m', 'test_pkg.script', *example_args, __isolated=False)
402 if verbose > 1:
403 print(repr(out))
404 expected = "init_argv0==%r" % '-m'
405 self.assertIn(expected.encode('utf-8'), out)
406 self._check_output(script_name, rc, out,
407 script_name, script_name, script_dir, 'test_pkg',
408 importlib.machinery.SourceFileLoader)
409
410 def test_issue8202_dash_c_file_ignored(self):
411 # Make sure a "-c" file in the current directory
412 # does not alter the value of sys.path[0]
413 with os_helper.temp_dir() as script_dir:
414 with os_helper.change_cwd(path=script_dir):
415 with open("-c", "w", encoding="utf-8") as f:
416 f.write("data")
417 rc, out, err = assert_python_ok('-c',
418 'import sys; print("sys.path[0]==%r" % sys.path[0])',
419 __isolated=False)
420 if verbose > 1:
421 print(repr(out))
422 expected = "sys.path[0]==%r" % ''
423 self.assertIn(expected.encode('utf-8'), out)
424
425 def test_issue8202_dash_m_file_ignored(self):
426 # Make sure a "-m" file in the current directory
427 # does not alter the value of sys.path[0]
428 with os_helper.temp_dir() as script_dir:
429 script_name = _make_test_script(script_dir, 'other')
430 with os_helper.change_cwd(path=script_dir):
431 with open("-m", "w", encoding="utf-8") as f:
432 f.write("data")
433 rc, out, err = assert_python_ok('-m', 'other', *example_args,
434 __isolated=False)
435 self._check_output(script_name, rc, out,
436 script_name, script_name, script_dir, '',
437 importlib.machinery.SourceFileLoader)
438
439 def test_issue20884(self):
440 # On Windows, script with encoding cookie and LF line ending
441 # will be failed.
442 with os_helper.temp_dir() as script_dir:
443 script_name = os.path.join(script_dir, "issue20884.py")
444 with open(script_name, "w", encoding="latin1", newline='\n') as f:
445 f.write("#coding: iso-8859-1\n")
446 f.write('"""\n')
447 for _ in range(30):
448 f.write('x'*80 + '\n')
449 f.write('"""\n')
450
451 with os_helper.change_cwd(path=script_dir):
452 rc, out, err = assert_python_ok(script_name)
453 self.assertEqual(b"", out)
454 self.assertEqual(b"", err)
455
456 @contextlib.contextmanager
457 def setup_test_pkg(self, *args):
458 with os_helper.temp_dir() as script_dir, \
459 os_helper.change_cwd(path=script_dir):
460 pkg_dir = os.path.join(script_dir, 'test_pkg')
461 make_pkg(pkg_dir, *args)
462 yield pkg_dir
463
464 def check_dash_m_failure(self, *args):
465 rc, out, err = assert_python_failure('-m', *args, __isolated=False)
466 if verbose > 1:
467 print(repr(out))
468 self.assertEqual(rc, 1)
469 return err
470
471 def test_dash_m_error_code_is_one(self):
472 # If a module is invoked with the -m command line flag
473 # and results in an error that the return code to the
474 # shell is '1'
475 with self.setup_test_pkg() as pkg_dir:
476 script_name = _make_test_script(pkg_dir, 'other',
477 "if __name__ == '__main__': raise ValueError")
478 err = self.check_dash_m_failure('test_pkg.other', *example_args)
479 self.assertIn(b'ValueError', err)
480
481 def test_dash_m_errors(self):
482 # Exercise error reporting for various invalid package executions
483 tests = (
484 ('builtins', br'No code object available'),
485 ('builtins.x', br'Error while finding module specification.*'
486 br'ModuleNotFoundError'),
487 ('builtins.x.y', br'Error while finding module specification.*'
488 br'ModuleNotFoundError.*No module named.*not a package'),
489 ('importlib', br'No module named.*'
490 br'is a package and cannot be directly executed'),
491 ('importlib.nonexistent', br'No module named'),
492 ('.unittest', br'Relative module names not supported'),
493 )
494 for name, regex in tests:
495 with self.subTest(name):
496 rc, _, err = assert_python_failure('-m', name)
497 self.assertEqual(rc, 1)
498 self.assertRegex(err, regex)
499 self.assertNotIn(b'Traceback', err)
500
501 def test_dash_m_bad_pyc(self):
502 with os_helper.temp_dir() as script_dir, \
503 os_helper.change_cwd(path=script_dir):
504 os.mkdir('test_pkg')
505 # Create invalid *.pyc as empty file
506 with open('test_pkg/__init__.pyc', 'wb'):
507 pass
508 err = self.check_dash_m_failure('test_pkg')
509 self.assertRegex(err,
510 br'Error while finding module specification.*'
511 br'ImportError.*bad magic number')
512 self.assertNotIn(b'is a package', err)
513 self.assertNotIn(b'Traceback', err)
514
515 def test_hint_when_triying_to_import_a_py_file(self):
516 with os_helper.temp_dir() as script_dir, \
517 os_helper.change_cwd(path=script_dir):
518 # Create invalid *.pyc as empty file
519 with open('asyncio.py', 'wb'):
520 pass
521 err = self.check_dash_m_failure('asyncio.py')
522 self.assertIn(b"Try using 'asyncio' instead "
523 b"of 'asyncio.py' as the module name", err)
524
525 def test_dash_m_init_traceback(self):
526 # These were wrapped in an ImportError and tracebacks were
527 # suppressed; see Issue 14285
528 exceptions = (ImportError, AttributeError, TypeError, ValueError)
529 for exception in exceptions:
530 exception = exception.__name__
531 init = "raise {0}('Exception in __init__.py')".format(exception)
532 with self.subTest(exception), \
533 self.setup_test_pkg(init) as pkg_dir:
534 err = self.check_dash_m_failure('test_pkg')
535 self.assertIn(exception.encode('ascii'), err)
536 self.assertIn(b'Exception in __init__.py', err)
537 self.assertIn(b'Traceback', err)
538
539 def test_dash_m_main_traceback(self):
540 # Ensure that an ImportError's traceback is reported
541 with self.setup_test_pkg() as pkg_dir:
542 main = "raise ImportError('Exception in __main__ module')"
543 _make_test_script(pkg_dir, '__main__', main)
544 err = self.check_dash_m_failure('test_pkg')
545 self.assertIn(b'ImportError', err)
546 self.assertIn(b'Exception in __main__ module', err)
547 self.assertIn(b'Traceback', err)
548
549 def test_pep_409_verbiage(self):
550 # Make sure PEP 409 syntax properly suppresses
551 # the context of an exception
552 script = textwrap.dedent("""\
553 try:
554 raise ValueError
555 except:
556 raise NameError from None
557 """)
558 with os_helper.temp_dir() as script_dir:
559 script_name = _make_test_script(script_dir, 'script', script)
560 exitcode, stdout, stderr = assert_python_failure(script_name)
561 text = stderr.decode('ascii').split('\n')
562 self.assertEqual(len(text), 5)
563 self.assertTrue(text[0].startswith('Traceback'))
564 self.assertTrue(text[1].startswith(' File '))
565 self.assertTrue(text[3].startswith('NameError'))
566
567 def test_non_ascii(self):
568 # Mac OS X denies the creation of a file with an invalid UTF-8 name.
569 # Windows allows creating a name with an arbitrary bytes name, but
570 # Python cannot a undecodable bytes argument to a subprocess.
571 # WASI does not permit invalid UTF-8 names.
572 if (os_helper.TESTFN_UNDECODABLE
573 and sys.platform not in ('win32', 'darwin', 'emscripten', 'wasi')):
574 name = os.fsdecode(os_helper.TESTFN_UNDECODABLE)
575 elif os_helper.TESTFN_NONASCII:
576 name = os_helper.TESTFN_NONASCII
577 else:
578 self.skipTest("need os_helper.TESTFN_NONASCII")
579
580 # Issue #16218
581 source = 'print(ascii(__file__))\n'
582 script_name = _make_test_script(os.getcwd(), name, source)
583 self.addCleanup(os_helper.unlink, script_name)
584 rc, stdout, stderr = assert_python_ok(script_name)
585 self.assertEqual(
586 ascii(script_name),
587 stdout.rstrip().decode('ascii'),
588 'stdout=%r stderr=%r' % (stdout, stderr))
589 self.assertEqual(0, rc)
590
591 def test_issue20500_exit_with_exception_value(self):
592 script = textwrap.dedent("""\
593 import sys
594 error = None
595 try:
596 raise ValueError('some text')
597 except ValueError as err:
598 error = err
599
600 if error:
601 sys.exit(error)
602 """)
603 with os_helper.temp_dir() as script_dir:
604 script_name = _make_test_script(script_dir, 'script', script)
605 exitcode, stdout, stderr = assert_python_failure(script_name)
606 text = stderr.decode('ascii')
607 self.assertEqual(text.rstrip(), "some text")
608
609 def test_syntaxerror_unindented_caret_position(self):
610 script = "1 + 1 = 2\n"
611 with os_helper.temp_dir() as script_dir:
612 script_name = _make_test_script(script_dir, 'script', script)
613 exitcode, stdout, stderr = assert_python_failure(script_name)
614 text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read()
615 # Confirm that the caret is located under the '=' sign
616 self.assertIn("\n ^^^^^\n", text)
617
618 def test_syntaxerror_indented_caret_position(self):
619 script = textwrap.dedent("""\
620 if True:
621 1 + 1 = 2
622 """)
623 with os_helper.temp_dir() as script_dir:
624 script_name = _make_test_script(script_dir, 'script', script)
625 exitcode, stdout, stderr = assert_python_failure(script_name)
626 text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read()
627 # Confirm that the caret starts under the first 1 character
628 self.assertIn("\n 1 + 1 = 2\n ^^^^^\n", text)
629
630 # Try the same with a form feed at the start of the indented line
631 script = (
632 "if True:\n"
633 "\f 1 + 1 = 2\n"
634 )
635 script_name = _make_test_script(script_dir, "script", script)
636 exitcode, stdout, stderr = assert_python_failure(script_name)
637 text = io.TextIOWrapper(io.BytesIO(stderr), "ascii").read()
638 self.assertNotIn("\f", text)
639 self.assertIn("\n 1 + 1 = 2\n ^^^^^\n", text)
640
641 def test_syntaxerror_multi_line_fstring(self):
642 script = 'foo = f"""{}\nfoo"""\n'
643 with os_helper.temp_dir() as script_dir:
644 script_name = _make_test_script(script_dir, 'script', script)
645 exitcode, stdout, stderr = assert_python_failure(script_name)
646 self.assertEqual(
647 stderr.splitlines()[-3:],
648 [
649 b' foo"""',
650 b' ^',
651 b'SyntaxError: f-string: empty expression not allowed',
652 ],
653 )
654
655 def test_syntaxerror_invalid_escape_sequence_multi_line(self):
656 script = 'foo = """\\q"""\n'
657 with os_helper.temp_dir() as script_dir:
658 script_name = _make_test_script(script_dir, 'script', script)
659 exitcode, stdout, stderr = assert_python_failure(
660 '-Werror', script_name,
661 )
662 self.assertEqual(
663 stderr.splitlines()[-3:],
664 [ b' foo = """\\q"""',
665 b' ^^^^^^^^',
666 b'SyntaxError: invalid escape sequence \'\\q\''
667 ],
668 )
669
670 def test_syntaxerror_null_bytes(self):
671 script = "x = '\0' nothing to see here\n';import os;os.system('echo pwnd')\n"
672 with os_helper.temp_dir() as script_dir:
673 script_name = _make_test_script(script_dir, 'script', script)
674 exitcode, stdout, stderr = assert_python_failure(script_name)
675 self.assertEqual(
676 stderr.splitlines()[-2:],
677 [ b" x = '",
678 b'SyntaxError: source code cannot contain null bytes'
679 ],
680 )
681
682 def test_syntaxerror_null_bytes_in_multiline_string(self):
683 scripts = ["\n'''\nmultilinestring\0\n'''", "\nf'''\nmultilinestring\0\n'''"] # Both normal and f-strings
684 with os_helper.temp_dir() as script_dir:
685 for script in scripts:
686 script_name = _make_test_script(script_dir, 'script', script)
687 _, _, stderr = assert_python_failure(script_name)
688 self.assertEqual(
689 stderr.splitlines()[-2:],
690 [ b" multilinestring",
691 b'SyntaxError: source code cannot contain null bytes'
692 ]
693 )
694
695 def test_consistent_sys_path_for_direct_execution(self):
696 # This test case ensures that the following all give the same
697 # sys.path configuration:
698 #
699 # ./python -s script_dir/__main__.py
700 # ./python -s script_dir
701 # ./python -I script_dir
702 script = textwrap.dedent("""\
703 import sys
704 for entry in sys.path:
705 print(entry)
706 """)
707 # Always show full path diffs on errors
708 self.maxDiff = None
709 with os_helper.temp_dir() as work_dir, os_helper.temp_dir() as script_dir:
710 script_name = _make_test_script(script_dir, '__main__', script)
711 # Reference output comes from directly executing __main__.py
712 # We omit PYTHONPATH and user site to align with isolated mode
713 p = spawn_python("-Es", script_name, cwd=work_dir)
714 out_by_name = kill_python(p).decode().splitlines()
715 self.assertEqual(out_by_name[0], script_dir)
716 self.assertNotIn(work_dir, out_by_name)
717 # Directory execution should give the same output
718 p = spawn_python("-Es", script_dir, cwd=work_dir)
719 out_by_dir = kill_python(p).decode().splitlines()
720 self.assertEqual(out_by_dir, out_by_name)
721 # As should directory execution in isolated mode
722 p = spawn_python("-I", script_dir, cwd=work_dir)
723 out_by_dir_isolated = kill_python(p).decode().splitlines()
724 self.assertEqual(out_by_dir_isolated, out_by_dir, out_by_name)
725
726 def test_consistent_sys_path_for_module_execution(self):
727 # This test case ensures that the following both give the same
728 # sys.path configuration:
729 # ./python -sm script_pkg.__main__
730 # ./python -sm script_pkg
731 #
732 # And that this fails as unable to find the package:
733 # ./python -Im script_pkg
734 script = textwrap.dedent("""\
735 import sys
736 for entry in sys.path:
737 print(entry)
738 """)
739 # Always show full path diffs on errors
740 self.maxDiff = None
741 with os_helper.temp_dir() as work_dir:
742 script_dir = os.path.join(work_dir, "script_pkg")
743 os.mkdir(script_dir)
744 script_name = _make_test_script(script_dir, '__main__', script)
745 # Reference output comes from `-m script_pkg.__main__`
746 # We omit PYTHONPATH and user site to better align with the
747 # direct execution test cases
748 p = spawn_python("-sm", "script_pkg.__main__", cwd=work_dir)
749 out_by_module = kill_python(p).decode().splitlines()
750 self.assertEqual(out_by_module[0], work_dir)
751 self.assertNotIn(script_dir, out_by_module)
752 # Package execution should give the same output
753 p = spawn_python("-sm", "script_pkg", cwd=work_dir)
754 out_by_package = kill_python(p).decode().splitlines()
755 self.assertEqual(out_by_package, out_by_module)
756 # Isolated mode should fail with an import error
757 exitcode, stdout, stderr = assert_python_failure(
758 "-Im", "script_pkg", cwd=work_dir
759 )
760 traceback_lines = stderr.decode().splitlines()
761 self.assertIn("No module named script_pkg", traceback_lines[-1])
762
763 def test_nonexisting_script(self):
764 # bpo-34783: "./python script.py" must not crash
765 # if the script file doesn't exist.
766 # (Skip test for macOS framework builds because sys.executable name
767 # is not the actual Python executable file name.
768 script = 'nonexistingscript.py'
769 self.assertFalse(os.path.exists(script))
770
771 proc = spawn_python(script, text=True,
772 stdout=subprocess.PIPE,
773 stderr=subprocess.PIPE)
774 out, err = proc.communicate()
775 self.assertIn(": can't open file ", err)
776 self.assertNotEqual(proc.returncode, 0)
777
778 @unittest.skipUnless(os.path.exists('/dev/fd/0'), 'requires /dev/fd platform')
779 @unittest.skipIf(sys.platform.startswith("freebsd") and
780 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
781 "Requires fdescfs mounted on /dev/fd on FreeBSD")
782 def test_script_as_dev_fd(self):
783 # GH-87235: On macOS passing a non-trivial script to /dev/fd/N can cause
784 # problems because all open /dev/fd/N file descriptors share the same
785 # offset.
786 script = 'print("12345678912345678912345")'
787 with os_helper.temp_dir() as work_dir:
788 script_name = _make_test_script(work_dir, 'script.py', script)
789 with open(script_name, "r") as fp:
790 p = spawn_python(f"/dev/fd/{fp.fileno()}", close_fds=True, pass_fds=(0,1,2,fp.fileno()))
791 out, err = p.communicate()
792 self.assertEqual(out, b"12345678912345678912345\n")
793
794
795
796 def tearDownModule():
797 support.reap_children()
798
799
800 if __name__ == '__main__':
801 unittest.main()