1# tests command line execution of scripts 2 3import contextlib 4import importlib 5import importlib.machinery 6import zipimport 7import unittest 8import sys 9import os 10import os.path 11import py_compile 12import subprocess 13import io 14 15import textwrap 16from test import support 17from test.support.script_helper import ( 18 make_pkg, make_script, make_zip_pkg, make_zip_script, 19 assert_python_ok, assert_python_failure, spawn_python, kill_python) 20 21verbose = support.verbose 22 23example_args = ['test1', 'test2', 'test3'] 24 25test_source = """\ 26# 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: 30 raise AssertionError('%r != %r' % (lhs, rhs)) 31def assertIdentical(lhs, rhs): 32 if lhs is not rhs: 33 raise AssertionError('%r is not %r' % (lhs, rhs)) 34# 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__') 42from importlib.machinery import BuiltinImporter 43_loader = __loader__ if __loader__ is BuiltinImporter else type(__loader__) 44print('__loader__==%a' % _loader) 45print('__file__==%a' % __file__) 46print('__cached__==%a' % __cached__) 47print('__package__==%r' % __package__) 48# 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__) 62# Check the sys module 63import sys 64assertIdentical(globals(), sys.modules[__name__].__dict__) 65if __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__) 68from test import test_cmd_line_script 69example_args_list = test_cmd_line_script.example_args 70assertEqual(sys.argv[1:], example_args_list) 71print('sys.argv[0]==%a' % sys.argv[0]) 72print('sys.path[0]==%a' % sys.path[0]) 73# Check the working directory 74import os 75print('cwd==%a' % os.getcwd()) 76""" 77 78def _make_test_script(script_dir, script_basename, source=test_source): 79 to_return = make_script(script_dir, script_basename, source) 80 importlib.invalidate_caches() 81 return to_return 82 83def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, 84 source=test_source, depth=1): 85 to_return = make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, 86 source, depth) 87 importlib.invalidate_caches() 88 return to_return 89 90class CmdLineTest(unittest.TestCase): 91 def _check_output(self, script_name, exit_code, data, 92 expected_file, expected_argv0, 93 expected_path0, expected_package, 94 expected_loader, expected_cwd=None): 95 if verbose > 1: 96 print("Output from test script %r:" % script_name) 97 print(repr(data)) 98 self.assertEqual(exit_code, 0) 99 printed_loader = '__loader__==%a' % expected_loader 100 printed_file = '__file__==%a' % expected_file 101 printed_package = '__package__==%r' % expected_package 102 printed_argv0 = 'sys.argv[0]==%a' % expected_argv0 103 printed_path0 = 'sys.path[0]==%a' % expected_path0 104 if expected_cwd is None: 105 expected_cwd = os.getcwd() 106 printed_cwd = 'cwd==%a' % expected_cwd 107 if verbose > 1: 108 print('Expected output:') 109 print(printed_file) 110 print(printed_package) 111 print(printed_argv0) 112 print(printed_cwd) 113 self.assertIn(printed_loader.encode('utf-8'), data) 114 self.assertIn(printed_file.encode('utf-8'), data) 115 self.assertIn(printed_package.encode('utf-8'), data) 116 self.assertIn(printed_argv0.encode('utf-8'), data) 117 self.assertIn(printed_path0.encode('utf-8'), data) 118 self.assertIn(printed_cwd.encode('utf-8'), data) 119 120 def _check_script(self, script_exec_args, expected_file, 121 expected_argv0, expected_path0, 122 expected_package, expected_loader, 123 *cmd_line_switches, cwd=None, **env_vars): 124 if isinstance(script_exec_args, str): 125 script_exec_args = [script_exec_args] 126 run_args = [*support.optim_args_from_interpreter_flags(), 127 *cmd_line_switches, *script_exec_args, *example_args] 128 rc, out, err = assert_python_ok( 129 *run_args, __isolated=False, __cwd=cwd, **env_vars 130 ) 131 self._check_output(script_exec_args, rc, out + err, expected_file, 132 expected_argv0, expected_path0, 133 expected_package, expected_loader, cwd) 134 135 def _check_import_error(self, script_exec_args, expected_msg, 136 *cmd_line_switches, cwd=None, **env_vars): 137 if isinstance(script_exec_args, str): 138 script_exec_args = (script_exec_args,) 139 else: 140 script_exec_args = tuple(script_exec_args) 141 run_args = cmd_line_switches + script_exec_args 142 rc, out, err = assert_python_failure( 143 *run_args, __isolated=False, __cwd=cwd, **env_vars 144 ) 145 if verbose > 1: 146 print('Output from test script %r:' % script_exec_args) 147 print(repr(err)) 148 print('Expected output: %r' % expected_msg) 149 self.assertIn(expected_msg.encode('utf-8'), err) 150 151 def test_dash_c_loader(self): 152 rc, out, err = assert_python_ok("-c", "print(__loader__)") 153 expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8") 154 self.assertIn(expected, out) 155 156 def test_stdin_loader(self): 157 # Unfortunately, there's no way to automatically test the fully 158 # interactive REPL, since that code path only gets executed when 159 # stdin is an interactive tty. 160 p = spawn_python() 161 try: 162 p.stdin.write(b"print(__loader__)\n") 163 p.stdin.flush() 164 finally: 165 out = kill_python(p) 166 expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8") 167 self.assertIn(expected, out) 168 169 @contextlib.contextmanager 170 def interactive_python(self, separate_stderr=False): 171 if separate_stderr: 172 p = spawn_python('-i', bufsize=1, stderr=subprocess.PIPE) 173 stderr = p.stderr 174 else: 175 p = spawn_python('-i', bufsize=1, stderr=subprocess.STDOUT) 176 stderr = p.stdout 177 try: 178 # Drain stderr until prompt 179 while True: 180 data = stderr.read(4) 181 if data == b">>> ": 182 break 183 stderr.readline() 184 yield p 185 finally: 186 kill_python(p) 187 stderr.close() 188 189 def check_repl_stdout_flush(self, separate_stderr=False): 190 with self.interactive_python(separate_stderr) as p: 191 p.stdin.write(b"print('foo')\n") 192 p.stdin.flush() 193 self.assertEqual(b'foo', p.stdout.readline().strip()) 194 195 def check_repl_stderr_flush(self, separate_stderr=False): 196 with self.interactive_python(separate_stderr) as p: 197 p.stdin.write(b"1/0\n") 198 p.stdin.flush() 199 stderr = p.stderr if separate_stderr else p.stdout 200 self.assertIn(b'Traceback ', stderr.readline()) 201 self.assertIn(b'File "<stdin>"', stderr.readline()) 202 self.assertIn(b'ZeroDivisionError', stderr.readline()) 203 204 def test_repl_stdout_flush(self): 205 self.check_repl_stdout_flush() 206 207 def test_repl_stdout_flush_separate_stderr(self): 208 self.check_repl_stdout_flush(True) 209 210 def test_repl_stderr_flush(self): 211 self.check_repl_stderr_flush() 212 213 def test_repl_stderr_flush_separate_stderr(self): 214 self.check_repl_stderr_flush(True) 215 216 def test_basic_script(self): 217 with support.temp_dir() as script_dir: 218 script_name = _make_test_script(script_dir, 'script') 219 self._check_script(script_name, script_name, script_name, 220 script_dir, None, 221 importlib.machinery.SourceFileLoader) 222 223 def test_script_compiled(self): 224 with support.temp_dir() as script_dir: 225 script_name = _make_test_script(script_dir, 'script') 226 py_compile.compile(script_name, doraise=True) 227 os.remove(script_name) 228 pyc_file = support.make_legacy_pyc(script_name) 229 self._check_script(pyc_file, pyc_file, 230 pyc_file, script_dir, None, 231 importlib.machinery.SourcelessFileLoader) 232 233 def test_directory(self): 234 with support.temp_dir() as script_dir: 235 script_name = _make_test_script(script_dir, '__main__') 236 self._check_script(script_dir, script_name, script_dir, 237 script_dir, '', 238 importlib.machinery.SourceFileLoader) 239 240 def test_directory_compiled(self): 241 with support.temp_dir() as script_dir: 242 script_name = _make_test_script(script_dir, '__main__') 243 py_compile.compile(script_name, doraise=True) 244 os.remove(script_name) 245 pyc_file = support.make_legacy_pyc(script_name) 246 self._check_script(script_dir, pyc_file, script_dir, 247 script_dir, '', 248 importlib.machinery.SourcelessFileLoader) 249 250 def test_directory_error(self): 251 with support.temp_dir() as script_dir: 252 msg = "can't find '__main__' module in %r" % script_dir 253 self._check_import_error(script_dir, msg) 254 255 def test_zipfile(self): 256 with support.temp_dir() as script_dir: 257 script_name = _make_test_script(script_dir, '__main__') 258 zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name) 259 self._check_script(zip_name, run_name, zip_name, zip_name, '', 260 zipimport.zipimporter) 261 262 def test_zipfile_compiled(self): 263 with support.temp_dir() as script_dir: 264 script_name = _make_test_script(script_dir, '__main__') 265 compiled_name = py_compile.compile(script_name, doraise=True) 266 zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name) 267 self._check_script(zip_name, run_name, zip_name, zip_name, '', 268 zipimport.zipimporter) 269 270 def test_zipfile_error(self): 271 with support.temp_dir() as script_dir: 272 script_name = _make_test_script(script_dir, 'not_main') 273 zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name) 274 msg = "can't find '__main__' module in %r" % zip_name 275 self._check_import_error(zip_name, msg) 276 277 def test_module_in_package(self): 278 with support.temp_dir() as script_dir: 279 pkg_dir = os.path.join(script_dir, 'test_pkg') 280 make_pkg(pkg_dir) 281 script_name = _make_test_script(pkg_dir, 'script') 282 self._check_script(["-m", "test_pkg.script"], script_name, script_name, 283 script_dir, 'test_pkg', 284 importlib.machinery.SourceFileLoader, 285 cwd=script_dir) 286 287 def test_module_in_package_in_zipfile(self): 288 with support.temp_dir() as script_dir: 289 zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script') 290 self._check_script(["-m", "test_pkg.script"], run_name, run_name, 291 script_dir, 'test_pkg', zipimport.zipimporter, 292 PYTHONPATH=zip_name, cwd=script_dir) 293 294 def test_module_in_subpackage_in_zipfile(self): 295 with support.temp_dir() as script_dir: 296 zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2) 297 self._check_script(["-m", "test_pkg.test_pkg.script"], run_name, run_name, 298 script_dir, 'test_pkg.test_pkg', 299 zipimport.zipimporter, 300 PYTHONPATH=zip_name, cwd=script_dir) 301 302 def test_package(self): 303 with support.temp_dir() as script_dir: 304 pkg_dir = os.path.join(script_dir, 'test_pkg') 305 make_pkg(pkg_dir) 306 script_name = _make_test_script(pkg_dir, '__main__') 307 self._check_script(["-m", "test_pkg"], script_name, 308 script_name, script_dir, 'test_pkg', 309 importlib.machinery.SourceFileLoader, 310 cwd=script_dir) 311 312 def test_package_compiled(self): 313 with support.temp_dir() as script_dir: 314 pkg_dir = os.path.join(script_dir, 'test_pkg') 315 make_pkg(pkg_dir) 316 script_name = _make_test_script(pkg_dir, '__main__') 317 compiled_name = py_compile.compile(script_name, doraise=True) 318 os.remove(script_name) 319 pyc_file = support.make_legacy_pyc(script_name) 320 self._check_script(["-m", "test_pkg"], pyc_file, 321 pyc_file, script_dir, 'test_pkg', 322 importlib.machinery.SourcelessFileLoader, 323 cwd=script_dir) 324 325 def test_package_error(self): 326 with support.temp_dir() as script_dir: 327 pkg_dir = os.path.join(script_dir, 'test_pkg') 328 make_pkg(pkg_dir) 329 msg = ("'test_pkg' is a package and cannot " 330 "be directly executed") 331 self._check_import_error(["-m", "test_pkg"], msg, cwd=script_dir) 332 333 def test_package_recursion(self): 334 with support.temp_dir() as script_dir: 335 pkg_dir = os.path.join(script_dir, 'test_pkg') 336 make_pkg(pkg_dir) 337 main_dir = os.path.join(pkg_dir, '__main__') 338 make_pkg(main_dir) 339 msg = ("Cannot use package as __main__ module; " 340 "'test_pkg' is a package and cannot " 341 "be directly executed") 342 self._check_import_error(["-m", "test_pkg"], msg, cwd=script_dir) 343 344 def test_issue8202(self): 345 # Make sure package __init__ modules see "-m" in sys.argv0 while 346 # searching for the module to execute 347 with support.temp_dir() as script_dir: 348 with support.change_cwd(path=script_dir): 349 pkg_dir = os.path.join(script_dir, 'test_pkg') 350 make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])") 351 script_name = _make_test_script(pkg_dir, 'script') 352 rc, out, err = assert_python_ok('-m', 'test_pkg.script', *example_args, __isolated=False) 353 if verbose > 1: 354 print(repr(out)) 355 expected = "init_argv0==%r" % '-m' 356 self.assertIn(expected.encode('utf-8'), out) 357 self._check_output(script_name, rc, out, 358 script_name, script_name, script_dir, 'test_pkg', 359 importlib.machinery.SourceFileLoader) 360 361 def test_issue8202_dash_c_file_ignored(self): 362 # Make sure a "-c" file in the current directory 363 # does not alter the value of sys.path[0] 364 with support.temp_dir() as script_dir: 365 with support.change_cwd(path=script_dir): 366 with open("-c", "w") as f: 367 f.write("data") 368 rc, out, err = assert_python_ok('-c', 369 'import sys; print("sys.path[0]==%r" % sys.path[0])', 370 __isolated=False) 371 if verbose > 1: 372 print(repr(out)) 373 expected = "sys.path[0]==%r" % '' 374 self.assertIn(expected.encode('utf-8'), out) 375 376 def test_issue8202_dash_m_file_ignored(self): 377 # Make sure a "-m" file in the current directory 378 # does not alter the value of sys.path[0] 379 with support.temp_dir() as script_dir: 380 script_name = _make_test_script(script_dir, 'other') 381 with support.change_cwd(path=script_dir): 382 with open("-m", "w") as f: 383 f.write("data") 384 rc, out, err = assert_python_ok('-m', 'other', *example_args, 385 __isolated=False) 386 self._check_output(script_name, rc, out, 387 script_name, script_name, script_dir, '', 388 importlib.machinery.SourceFileLoader) 389 390 @contextlib.contextmanager 391 def setup_test_pkg(self, *args): 392 with support.temp_dir() as script_dir, \ 393 support.change_cwd(path=script_dir): 394 pkg_dir = os.path.join(script_dir, 'test_pkg') 395 make_pkg(pkg_dir, *args) 396 yield pkg_dir 397 398 def check_dash_m_failure(self, *args): 399 rc, out, err = assert_python_failure('-m', *args, __isolated=False) 400 if verbose > 1: 401 print(repr(out)) 402 self.assertEqual(rc, 1) 403 return err 404 405 def test_dash_m_error_code_is_one(self): 406 # If a module is invoked with the -m command line flag 407 # and results in an error that the return code to the 408 # shell is '1' 409 with self.setup_test_pkg() as pkg_dir: 410 script_name = _make_test_script(pkg_dir, 'other', 411 "if __name__ == '__main__': raise ValueError") 412 err = self.check_dash_m_failure('test_pkg.other', *example_args) 413 self.assertIn(b'ValueError', err) 414 415 def test_dash_m_errors(self): 416 # Exercise error reporting for various invalid package executions 417 tests = ( 418 ('builtins', br'No code object available'), 419 ('builtins.x', br'Error while finding module specification.*' 420 br'ModuleNotFoundError'), 421 ('builtins.x.y', br'Error while finding module specification.*' 422 br'ModuleNotFoundError.*No module named.*not a package'), 423 ('os.path', br'loader.*cannot handle'), 424 ('importlib', br'No module named.*' 425 br'is a package and cannot be directly executed'), 426 ('importlib.nonexistant', br'No module named'), 427 ('.unittest', br'Relative module names not supported'), 428 ) 429 for name, regex in tests: 430 with self.subTest(name): 431 rc, _, err = assert_python_failure('-m', name) 432 self.assertEqual(rc, 1) 433 self.assertRegex(err, regex) 434 self.assertNotIn(b'Traceback', err) 435 436 def test_dash_m_bad_pyc(self): 437 with support.temp_dir() as script_dir, \ 438 support.change_cwd(path=script_dir): 439 os.mkdir('test_pkg') 440 # Create invalid *.pyc as empty file 441 with open('test_pkg/__init__.pyc', 'wb'): 442 pass 443 err = self.check_dash_m_failure('test_pkg') 444 self.assertRegex(err, 445 br'Error while finding module specification.*' 446 br'ImportError.*bad magic number') 447 self.assertNotIn(b'is a package', err) 448 self.assertNotIn(b'Traceback', err) 449 450 def test_dash_m_init_traceback(self): 451 # These were wrapped in an ImportError and tracebacks were 452 # suppressed; see Issue 14285 453 exceptions = (ImportError, AttributeError, TypeError, ValueError) 454 for exception in exceptions: 455 exception = exception.__name__ 456 init = "raise {0}('Exception in __init__.py')".format(exception) 457 with self.subTest(exception), \ 458 self.setup_test_pkg(init) as pkg_dir: 459 err = self.check_dash_m_failure('test_pkg') 460 self.assertIn(exception.encode('ascii'), err) 461 self.assertIn(b'Exception in __init__.py', err) 462 self.assertIn(b'Traceback', err) 463 464 def test_dash_m_main_traceback(self): 465 # Ensure that an ImportError's traceback is reported 466 with self.setup_test_pkg() as pkg_dir: 467 main = "raise ImportError('Exception in __main__ module')" 468 _make_test_script(pkg_dir, '__main__', main) 469 err = self.check_dash_m_failure('test_pkg') 470 self.assertIn(b'ImportError', err) 471 self.assertIn(b'Exception in __main__ module', err) 472 self.assertIn(b'Traceback', err) 473 474 def test_pep_409_verbiage(self): 475 # Make sure PEP 409 syntax properly suppresses 476 # the context of an exception 477 script = textwrap.dedent("""\ 478 try: 479 raise ValueError 480 except: 481 raise NameError from None 482 """) 483 with support.temp_dir() as script_dir: 484 script_name = _make_test_script(script_dir, 'script', script) 485 exitcode, stdout, stderr = assert_python_failure(script_name) 486 text = stderr.decode('ascii').split('\n') 487 self.assertEqual(len(text), 4) 488 self.assertTrue(text[0].startswith('Traceback')) 489 self.assertTrue(text[1].startswith(' File ')) 490 self.assertTrue(text[3].startswith('NameError')) 491 492 def test_non_ascii(self): 493 # Mac OS X denies the creation of a file with an invalid UTF-8 name. 494 # Windows allows creating a name with an arbitrary bytes name, but 495 # Python cannot a undecodable bytes argument to a subprocess. 496 if (support.TESTFN_UNDECODABLE 497 and sys.platform not in ('win32', 'darwin')): 498 name = os.fsdecode(support.TESTFN_UNDECODABLE) 499 elif support.TESTFN_NONASCII: 500 name = support.TESTFN_NONASCII 501 else: 502 self.skipTest("need support.TESTFN_NONASCII") 503 504 # Issue #16218 505 source = 'print(ascii(__file__))\n' 506 script_name = _make_test_script(os.curdir, name, source) 507 self.addCleanup(support.unlink, script_name) 508 rc, stdout, stderr = assert_python_ok(script_name) 509 self.assertEqual( 510 ascii(script_name), 511 stdout.rstrip().decode('ascii'), 512 'stdout=%r stderr=%r' % (stdout, stderr)) 513 self.assertEqual(0, rc) 514 515 def test_issue20500_exit_with_exception_value(self): 516 script = textwrap.dedent("""\ 517 import sys 518 error = None 519 try: 520 raise ValueError('some text') 521 except ValueError as err: 522 error = err 523 524 if error: 525 sys.exit(error) 526 """) 527 with support.temp_dir() as script_dir: 528 script_name = _make_test_script(script_dir, 'script', script) 529 exitcode, stdout, stderr = assert_python_failure(script_name) 530 text = stderr.decode('ascii') 531 self.assertEqual(text, "some text") 532 533 def test_syntaxerror_unindented_caret_position(self): 534 script = "1 + 1 = 2\n" 535 with support.temp_dir() as script_dir: 536 script_name = _make_test_script(script_dir, 'script', script) 537 exitcode, stdout, stderr = assert_python_failure(script_name) 538 text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read() 539 # Confirm that the caret is located under the first 1 character 540 self.assertIn("\n 1 + 1 = 2\n ^", text) 541 542 def test_syntaxerror_indented_caret_position(self): 543 script = textwrap.dedent("""\ 544 if True: 545 1 + 1 = 2 546 """) 547 with support.temp_dir() as script_dir: 548 script_name = _make_test_script(script_dir, 'script', script) 549 exitcode, stdout, stderr = assert_python_failure(script_name) 550 text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read() 551 # Confirm that the caret is located under the first 1 character 552 self.assertIn("\n 1 + 1 = 2\n ^", text) 553 554 # Try the same with a form feed at the start of the indented line 555 script = ( 556 "if True:\n" 557 "\f 1 + 1 = 2\n" 558 ) 559 script_name = _make_test_script(script_dir, "script", script) 560 exitcode, stdout, stderr = assert_python_failure(script_name) 561 text = io.TextIOWrapper(io.BytesIO(stderr), "ascii").read() 562 self.assertNotIn("\f", text) 563 self.assertIn("\n 1 + 1 = 2\n ^", text) 564 565 def test_consistent_sys_path_for_direct_execution(self): 566 # This test case ensures that the following all give the same 567 # sys.path configuration: 568 # 569 # ./python -s script_dir/__main__.py 570 # ./python -s script_dir 571 # ./python -I script_dir 572 script = textwrap.dedent("""\ 573 import sys 574 for entry in sys.path: 575 print(entry) 576 """) 577 # Always show full path diffs on errors 578 self.maxDiff = None 579 with support.temp_dir() as work_dir, support.temp_dir() as script_dir: 580 script_name = _make_test_script(script_dir, '__main__', script) 581 # Reference output comes from directly executing __main__.py 582 # We omit PYTHONPATH and user site to align with isolated mode 583 p = spawn_python("-Es", script_name, cwd=work_dir) 584 out_by_name = kill_python(p).decode().splitlines() 585 self.assertEqual(out_by_name[0], script_dir) 586 self.assertNotIn(work_dir, out_by_name) 587 # Directory execution should give the same output 588 p = spawn_python("-Es", script_dir, cwd=work_dir) 589 out_by_dir = kill_python(p).decode().splitlines() 590 self.assertEqual(out_by_dir, out_by_name) 591 # As should directory execution in isolated mode 592 p = spawn_python("-I", script_dir, cwd=work_dir) 593 out_by_dir_isolated = kill_python(p).decode().splitlines() 594 self.assertEqual(out_by_dir_isolated, out_by_dir, out_by_name) 595 596 def test_consistent_sys_path_for_module_execution(self): 597 # This test case ensures that the following both give the same 598 # sys.path configuration: 599 # ./python -sm script_pkg.__main__ 600 # ./python -sm script_pkg 601 # 602 # And that this fails as unable to find the package: 603 # ./python -Im script_pkg 604 script = textwrap.dedent("""\ 605 import sys 606 for entry in sys.path: 607 print(entry) 608 """) 609 # Always show full path diffs on errors 610 self.maxDiff = None 611 with support.temp_dir() as work_dir: 612 script_dir = os.path.join(work_dir, "script_pkg") 613 os.mkdir(script_dir) 614 script_name = _make_test_script(script_dir, '__main__', script) 615 # Reference output comes from `-m script_pkg.__main__` 616 # We omit PYTHONPATH and user site to better align with the 617 # direct execution test cases 618 p = spawn_python("-sm", "script_pkg.__main__", cwd=work_dir) 619 out_by_module = kill_python(p).decode().splitlines() 620 self.assertEqual(out_by_module[0], work_dir) 621 self.assertNotIn(script_dir, out_by_module) 622 # Package execution should give the same output 623 p = spawn_python("-sm", "script_pkg", cwd=work_dir) 624 out_by_package = kill_python(p).decode().splitlines() 625 self.assertEqual(out_by_package, out_by_module) 626 # Isolated mode should fail with an import error 627 exitcode, stdout, stderr = assert_python_failure( 628 "-Im", "script_pkg", cwd=work_dir 629 ) 630 traceback_lines = stderr.decode().splitlines() 631 self.assertIn("No module named script_pkg", traceback_lines[-1]) 632 633 def test_nonexisting_script(self): 634 # bpo-34783: "./python script.py" must not crash 635 # if the script file doesn't exist. 636 # (Skip test for macOS framework builds because sys.excutable name 637 # is not the actual Python executable file name. 638 script = 'nonexistingscript.py' 639 self.assertFalse(os.path.exists(script)) 640 641 proc = spawn_python(script, text=True, 642 stdout=subprocess.PIPE, 643 stderr=subprocess.PIPE) 644 out, err = proc.communicate() 645 self.assertIn(": can't open file ", err) 646 self.assertNotEqual(proc.returncode, 0) 647 648 649def test_main(): 650 support.run_unittest(CmdLineTest) 651 support.reap_children() 652 653if __name__ == '__main__': 654 test_main() 655