Debian Codegraph @

Lib/test/test_runpy.py

raw
1 # Test the runpy module
2 import contextlib
3 import importlib.machinery, importlib.util
4 import os.path
5 import pathlib
6 import py_compile
7 import re
8 import signal
9 import subprocess
10 import sys
11 import tempfile
12 import textwrap
13 import unittest
14 import warnings
15 from test.support import (
16 force_not_colorized_test_class,
17 infinite_recursion,
18 no_tracing,
19 requires_resource,
20 requires_subprocess,
21 verbose,
22 )
23 from test.support.import_helper import forget, make_legacy_pyc, unload
24 from test.support.os_helper import create_empty_file, temp_dir, FakePath
25 from test.support.script_helper import make_script, make_zip_script
26
27
28 import runpy
29 from runpy import _run_code, _run_module_code, run_module, run_path
30 # Note: This module can't safely test _run_module_as_main as it
31 # runs its tests in the current process, which would mess with the
32 # real __main__ module (usually test.regrtest)
33 # See test_cmd_line_script for a test that executes that code path
34
35
36 # Set up the test code and expected results
37 example_source = """\
38 # Check basic code execution
39 result = ['Top level assignment']
40 def f():
41 result.append('Lower level reference')
42 f()
43 del f
44 # Check the sys module
45 import sys
46 run_argv0 = sys.argv[0]
47 run_name_in_sys_modules = __name__ in sys.modules
48 module_in_sys_modules = (run_name_in_sys_modules and
49 globals() is sys.modules[__name__].__dict__)
50 # Check nested operation
51 import runpy
52 nested = runpy._run_module_code('x=1\\n', mod_name='<run>')
53 """
54
55 implicit_namespace = {
56 "__name__": None,
57 "__file__": None,
58 "__cached__": None,
59 "__package__": None,
60 "__doc__": None,
61 "__spec__": None
62 }
63 example_namespace = {
64 "sys": sys,
65 "runpy": runpy,
66 "result": ["Top level assignment", "Lower level reference"],
67 "run_argv0": sys.argv[0],
68 "run_name_in_sys_modules": False,
69 "module_in_sys_modules": False,
70 "nested": dict(implicit_namespace,
71 x=1, __name__="<run>", __loader__=None),
72 }
73 example_namespace.update(implicit_namespace)
74
75 class CodeExecutionMixin:
76 # Issue #15230 (run_path not handling run_name correctly) highlighted a
77 # problem with the way arguments were being passed from higher level APIs
78 # down to lower level code. This mixin makes it easier to ensure full
79 # testing occurs at those upper layers as well, not just at the utility
80 # layer
81
82 # Figuring out the loader details in advance is hard to do, so we skip
83 # checking the full details of loader and loader_state
84 CHECKED_SPEC_ATTRIBUTES = ["name", "parent", "origin", "cached",
85 "has_location", "submodule_search_locations"]
86
87 def assertNamespaceMatches(self, result_ns, expected_ns):
88 """Check two namespaces match.
89
90 Ignores any unspecified interpreter created names
91 """
92 # Avoid side effects
93 result_ns = result_ns.copy()
94 expected_ns = expected_ns.copy()
95 # Impls are permitted to add extra names, so filter them out
96 for k in list(result_ns):
97 if k.startswith("__") and k.endswith("__"):
98 if k not in expected_ns:
99 result_ns.pop(k)
100 if k not in expected_ns["nested"]:
101 result_ns["nested"].pop(k)
102 # Spec equality includes the loader, so we take the spec out of the
103 # result namespace and check that separately
104 result_spec = result_ns.pop("__spec__")
105 expected_spec = expected_ns.pop("__spec__")
106 if expected_spec is None:
107 self.assertIsNone(result_spec)
108 else:
109 # If an expected loader is set, we just check we got the right
110 # type, rather than checking for full equality
111 if expected_spec.loader is not None:
112 self.assertEqual(type(result_spec.loader),
113 type(expected_spec.loader))
114 for attr in self.CHECKED_SPEC_ATTRIBUTES:
115 k = "__spec__." + attr
116 actual = (k, getattr(result_spec, attr))
117 expected = (k, getattr(expected_spec, attr))
118 self.assertEqual(actual, expected)
119 # For the rest, we still don't use direct dict comparison on the
120 # namespace, as the diffs are too hard to debug if anything breaks
121 self.assertEqual(set(result_ns), set(expected_ns))
122 for k in result_ns:
123 actual = (k, result_ns[k])
124 expected = (k, expected_ns[k])
125 self.assertEqual(actual, expected)
126
127 def check_code_execution(self, create_namespace, expected_namespace):
128 """Check that an interface runs the example code correctly
129
130 First argument is a callable accepting the initial globals and
131 using them to create the actual namespace
132 Second argument is the expected result
133 """
134 sentinel = object()
135 expected_ns = expected_namespace.copy()
136 run_name = expected_ns["__name__"]
137 saved_argv0 = sys.argv[0]
138 saved_mod = sys.modules.get(run_name, sentinel)
139 # Check without initial globals
140 result_ns = create_namespace(None)
141 self.assertNamespaceMatches(result_ns, expected_ns)
142 self.assertIs(sys.argv[0], saved_argv0)
143 self.assertIs(sys.modules.get(run_name, sentinel), saved_mod)
144 # And then with initial globals
145 initial_ns = {"sentinel": sentinel}
146 expected_ns["sentinel"] = sentinel
147 result_ns = create_namespace(initial_ns)
148 self.assertIsNot(result_ns, initial_ns)
149 self.assertNamespaceMatches(result_ns, expected_ns)
150 self.assertIs(sys.argv[0], saved_argv0)
151 self.assertIs(sys.modules.get(run_name, sentinel), saved_mod)
152
153
154 class ExecutionLayerTestCase(unittest.TestCase, CodeExecutionMixin):
155 """Unit tests for runpy._run_code and runpy._run_module_code"""
156
157 def test_run_code(self):
158 expected_ns = example_namespace.copy()
159 expected_ns.update({
160 "__loader__": None,
161 })
162 def create_ns(init_globals):
163 return _run_code(example_source, {}, init_globals)
164 self.check_code_execution(create_ns, expected_ns)
165
166 def test_run_module_code(self):
167 mod_name = "<Nonsense>"
168 mod_fname = "Some other nonsense"
169 mod_loader = "Now you're just being silly"
170 mod_package = '' # Treat as a top level module
171 mod_spec = importlib.machinery.ModuleSpec(mod_name,
172 origin=mod_fname,
173 loader=mod_loader)
174 expected_ns = example_namespace.copy()
175 expected_ns.update({
176 "__name__": mod_name,
177 "__file__": mod_fname,
178 "__loader__": mod_loader,
179 "__package__": mod_package,
180 "__spec__": mod_spec,
181 "run_argv0": mod_fname,
182 "run_name_in_sys_modules": True,
183 "module_in_sys_modules": True,
184 })
185 def create_ns(init_globals):
186 return _run_module_code(example_source,
187 init_globals,
188 mod_name,
189 mod_spec)
190 self.check_code_execution(create_ns, expected_ns)
191
192 # TODO: Use self.addCleanup to get rid of a lot of try-finally blocks
193 class RunModuleTestCase(unittest.TestCase, CodeExecutionMixin):
194 """Unit tests for runpy.run_module"""
195
196 def expect_import_error(self, mod_name):
197 try:
198 run_module(mod_name)
199 except ImportError:
200 pass
201 else:
202 self.fail("Expected import error for " + mod_name)
203
204 def test_invalid_names(self):
205 # Builtin module
206 self.expect_import_error("sys")
207 # Non-existent modules
208 self.expect_import_error("sys.imp.eric")
209 self.expect_import_error("os.path.half")
210 self.expect_import_error("a.bee")
211 # Relative names not allowed
212 self.expect_import_error(".howard")
213 self.expect_import_error("..eaten")
214 self.expect_import_error(".test_runpy")
215 self.expect_import_error(".unittest")
216 # Package without __main__.py
217 self.expect_import_error("multiprocessing")
218
219 def test_library_module(self):
220 self.assertEqual(run_module("runpy")["__name__"], "runpy")
221
222 def _add_pkg_dir(self, pkg_dir, namespace=False):
223 os.mkdir(pkg_dir)
224 if namespace:
225 return None
226 pkg_fname = os.path.join(pkg_dir, "__init__.py")
227 create_empty_file(pkg_fname)
228 return pkg_fname
229
230 def _make_pkg(self, source, depth, mod_base="runpy_test",
231 *, namespace=False, parent_namespaces=False):
232 # Enforce a couple of internal sanity checks on test cases
233 if (namespace or parent_namespaces) and not depth:
234 raise RuntimeError("Can't mark top level module as a "
235 "namespace package")
236 pkg_name = "__runpy_pkg__"
237 test_fname = mod_base+os.extsep+"py"
238 pkg_dir = sub_dir = os.path.realpath(tempfile.mkdtemp())
239 if verbose > 1: print(" Package tree in:", sub_dir)
240 sys.path.insert(0, pkg_dir)
241 if verbose > 1: print(" Updated sys.path:", sys.path[0])
242 if depth:
243 namespace_flags = [parent_namespaces] * depth
244 namespace_flags[-1] = namespace
245 for namespace_flag in namespace_flags:
246 sub_dir = os.path.join(sub_dir, pkg_name)
247 pkg_fname = self._add_pkg_dir(sub_dir, namespace_flag)
248 if verbose > 1: print(" Next level in:", sub_dir)
249 if verbose > 1: print(" Created:", pkg_fname)
250 mod_fname = os.path.join(sub_dir, test_fname)
251 with open(mod_fname, "w") as mod_file:
252 mod_file.write(source)
253 if verbose > 1: print(" Created:", mod_fname)
254 mod_name = (pkg_name+".")*depth + mod_base
255 mod_spec = importlib.util.spec_from_file_location(mod_name,
256 mod_fname)
257 return pkg_dir, mod_fname, mod_name, mod_spec
258
259 def _del_pkg(self, top):
260 for entry in list(sys.modules):
261 if entry.startswith("__runpy_pkg__"):
262 del sys.modules[entry]
263 if verbose > 1: print(" Removed sys.modules entries")
264 del sys.path[0]
265 if verbose > 1: print(" Removed sys.path entry")
266 for root, dirs, files in os.walk(top, topdown=False):
267 for name in files:
268 try:
269 os.remove(os.path.join(root, name))
270 except OSError as ex:
271 if verbose > 1: print(ex) # Persist with cleaning up
272 for name in dirs:
273 fullname = os.path.join(root, name)
274 try:
275 os.rmdir(fullname)
276 except OSError as ex:
277 if verbose > 1: print(ex) # Persist with cleaning up
278 try:
279 os.rmdir(top)
280 if verbose > 1: print(" Removed package tree")
281 except OSError as ex:
282 if verbose > 1: print(ex) # Persist with cleaning up
283
284 def _fix_ns_for_legacy_pyc(self, ns, alter_sys):
285 char_to_add = "c"
286 ns["__file__"] += char_to_add
287 ns["__cached__"] = ns["__file__"]
288 spec = ns["__spec__"]
289 new_spec = importlib.util.spec_from_file_location(spec.name,
290 ns["__file__"])
291 ns["__spec__"] = new_spec
292 if alter_sys:
293 ns["run_argv0"] += char_to_add
294
295
296 def _check_module(self, depth, alter_sys=False,
297 *, namespace=False, parent_namespaces=False):
298 pkg_dir, mod_fname, mod_name, mod_spec = (
299 self._make_pkg(example_source, depth,
300 namespace=namespace,
301 parent_namespaces=parent_namespaces))
302 forget(mod_name)
303 expected_ns = example_namespace.copy()
304 expected_ns.update({
305 "__name__": mod_name,
306 "__file__": mod_fname,
307 "__cached__": mod_spec.cached,
308 "__package__": mod_name.rpartition(".")[0],
309 "__spec__": mod_spec,
310 })
311 if alter_sys:
312 expected_ns.update({
313 "run_argv0": mod_fname,
314 "run_name_in_sys_modules": True,
315 "module_in_sys_modules": True,
316 })
317 def create_ns(init_globals):
318 return run_module(mod_name, init_globals, alter_sys=alter_sys)
319 try:
320 if verbose > 1: print("Running from source:", mod_name)
321 self.check_code_execution(create_ns, expected_ns)
322 importlib.invalidate_caches()
323 __import__(mod_name)
324 os.remove(mod_fname)
325 if not sys.dont_write_bytecode:
326 make_legacy_pyc(mod_fname)
327 unload(mod_name) # In case loader caches paths
328 importlib.invalidate_caches()
329 if verbose > 1: print("Running from compiled:", mod_name)
330 self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
331 self.check_code_execution(create_ns, expected_ns)
332 finally:
333 self._del_pkg(pkg_dir)
334 if verbose > 1: print("Module executed successfully")
335
336 def _check_package(self, depth, alter_sys=False,
337 *, namespace=False, parent_namespaces=False):
338 pkg_dir, mod_fname, mod_name, mod_spec = (
339 self._make_pkg(example_source, depth, "__main__",
340 namespace=namespace,
341 parent_namespaces=parent_namespaces))
342 pkg_name = mod_name.rpartition(".")[0]
343 forget(mod_name)
344 expected_ns = example_namespace.copy()
345 expected_ns.update({
346 "__name__": mod_name,
347 "__file__": mod_fname,
348 "__cached__": importlib.util.cache_from_source(mod_fname),
349 "__package__": pkg_name,
350 "__spec__": mod_spec,
351 })
352 if alter_sys:
353 expected_ns.update({
354 "run_argv0": mod_fname,
355 "run_name_in_sys_modules": True,
356 "module_in_sys_modules": True,
357 })
358 def create_ns(init_globals):
359 return run_module(pkg_name, init_globals, alter_sys=alter_sys)
360 try:
361 if verbose > 1: print("Running from source:", pkg_name)
362 self.check_code_execution(create_ns, expected_ns)
363 importlib.invalidate_caches()
364 __import__(mod_name)
365 os.remove(mod_fname)
366 if not sys.dont_write_bytecode:
367 make_legacy_pyc(mod_fname)
368 unload(mod_name) # In case loader caches paths
369 if verbose > 1: print("Running from compiled:", pkg_name)
370 importlib.invalidate_caches()
371 self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
372 self.check_code_execution(create_ns, expected_ns)
373 finally:
374 self._del_pkg(pkg_dir)
375 if verbose > 1: print("Package executed successfully")
376
377 def _add_relative_modules(self, base_dir, source, depth):
378 if depth <= 1:
379 raise ValueError("Relative module test needs depth > 1")
380 pkg_name = "__runpy_pkg__"
381 module_dir = base_dir
382 for i in range(depth):
383 parent_dir = module_dir
384 module_dir = os.path.join(module_dir, pkg_name)
385 # Add sibling module
386 sibling_fname = os.path.join(module_dir, "sibling.py")
387 create_empty_file(sibling_fname)
388 if verbose > 1: print(" Added sibling module:", sibling_fname)
389 # Add nephew module
390 uncle_dir = os.path.join(parent_dir, "uncle")
391 self._add_pkg_dir(uncle_dir)
392 if verbose > 1: print(" Added uncle package:", uncle_dir)
393 cousin_dir = os.path.join(uncle_dir, "cousin")
394 self._add_pkg_dir(cousin_dir)
395 if verbose > 1: print(" Added cousin package:", cousin_dir)
396 nephew_fname = os.path.join(cousin_dir, "nephew.py")
397 create_empty_file(nephew_fname)
398 if verbose > 1: print(" Added nephew module:", nephew_fname)
399
400 def _check_relative_imports(self, depth, run_name=None):
401 contents = r"""\
402 from __future__ import absolute_import
403 from . import sibling
404 from ..uncle.cousin import nephew
405 """
406 pkg_dir, mod_fname, mod_name, mod_spec = (
407 self._make_pkg(contents, depth))
408 if run_name is None:
409 expected_name = mod_name
410 else:
411 expected_name = run_name
412 try:
413 self._add_relative_modules(pkg_dir, contents, depth)
414 pkg_name = mod_name.rpartition('.')[0]
415 if verbose > 1: print("Running from source:", mod_name)
416 d1 = run_module(mod_name, run_name=run_name) # Read from source
417 self.assertEqual(d1["__name__"], expected_name)
418 self.assertEqual(d1["__package__"], pkg_name)
419 self.assertIn("sibling", d1)
420 self.assertIn("nephew", d1)
421 del d1 # Ensure __loader__ entry doesn't keep file open
422 importlib.invalidate_caches()
423 __import__(mod_name)
424 os.remove(mod_fname)
425 if not sys.dont_write_bytecode:
426 make_legacy_pyc(mod_fname)
427 unload(mod_name) # In case the loader caches paths
428 if verbose > 1: print("Running from compiled:", mod_name)
429 importlib.invalidate_caches()
430 d2 = run_module(mod_name, run_name=run_name) # Read from bytecode
431 self.assertEqual(d2["__name__"], expected_name)
432 self.assertEqual(d2["__package__"], pkg_name)
433 self.assertIn("sibling", d2)
434 self.assertIn("nephew", d2)
435 del d2 # Ensure __loader__ entry doesn't keep file open
436 finally:
437 self._del_pkg(pkg_dir)
438 if verbose > 1: print("Module executed successfully")
439
440 def test_run_module(self):
441 for depth in range(4):
442 if verbose > 1: print("Testing package depth:", depth)
443 self._check_module(depth)
444
445 def test_run_module_in_namespace_package(self):
446 for depth in range(1, 4):
447 if verbose > 1: print("Testing package depth:", depth)
448 self._check_module(depth, namespace=True, parent_namespaces=True)
449
450 def test_run_package(self):
451 for depth in range(1, 4):
452 if verbose > 1: print("Testing package depth:", depth)
453 self._check_package(depth)
454
455 def test_run_package_init_exceptions(self):
456 # These were previously wrapped in an ImportError; see Issue 14285
457 result = self._make_pkg("", 1, "__main__")
458 pkg_dir, _, mod_name, _ = result
459 mod_name = mod_name.replace(".__main__", "")
460 self.addCleanup(self._del_pkg, pkg_dir)
461 init = os.path.join(pkg_dir, "__runpy_pkg__", "__init__.py")
462
463 exceptions = (ImportError, AttributeError, TypeError, ValueError)
464 for exception in exceptions:
465 name = exception.__name__
466 with self.subTest(name):
467 source = "raise {0}('{0} in __init__.py.')".format(name)
468 with open(init, "wt", encoding="ascii") as mod_file:
469 mod_file.write(source)
470 try:
471 run_module(mod_name)
472 except exception as err:
473 self.assertNotIn("finding spec", format(err))
474 else:
475 self.fail("Nothing raised; expected {}".format(name))
476 try:
477 run_module(mod_name + ".submodule")
478 except exception as err:
479 self.assertNotIn("finding spec", format(err))
480 else:
481 self.fail("Nothing raised; expected {}".format(name))
482
483 def test_submodule_imported_warning(self):
484 pkg_dir, _, mod_name, _ = self._make_pkg("", 1)
485 try:
486 __import__(mod_name)
487 with self.assertWarnsRegex(RuntimeWarning,
488 r"found in sys\.modules"):
489 run_module(mod_name)
490 finally:
491 self._del_pkg(pkg_dir)
492
493 def test_package_imported_no_warning(self):
494 pkg_dir, _, mod_name, _ = self._make_pkg("", 1, "__main__")
495 self.addCleanup(self._del_pkg, pkg_dir)
496 package = mod_name.replace(".__main__", "")
497 # No warning should occur if we only imported the parent package
498 __import__(package)
499 self.assertIn(package, sys.modules)
500 with warnings.catch_warnings():
501 warnings.simplefilter("error", RuntimeWarning)
502 run_module(package)
503 # But the warning should occur if we imported the __main__ submodule
504 __import__(mod_name)
505 with self.assertWarnsRegex(RuntimeWarning, r"found in sys\.modules"):
506 run_module(package)
507
508 def test_run_package_in_namespace_package(self):
509 for depth in range(1, 4):
510 if verbose > 1: print("Testing package depth:", depth)
511 self._check_package(depth, parent_namespaces=True)
512
513 def test_run_namespace_package(self):
514 for depth in range(1, 4):
515 if verbose > 1: print("Testing package depth:", depth)
516 self._check_package(depth, namespace=True)
517
518 def test_run_namespace_package_in_namespace_package(self):
519 for depth in range(1, 4):
520 if verbose > 1: print("Testing package depth:", depth)
521 self._check_package(depth, namespace=True, parent_namespaces=True)
522
523 def test_run_module_alter_sys(self):
524 for depth in range(4):
525 if verbose > 1: print("Testing package depth:", depth)
526 self._check_module(depth, alter_sys=True)
527
528 def test_run_package_alter_sys(self):
529 for depth in range(1, 4):
530 if verbose > 1: print("Testing package depth:", depth)
531 self._check_package(depth, alter_sys=True)
532
533 def test_explicit_relative_import(self):
534 for depth in range(2, 5):
535 if verbose > 1: print("Testing relative imports at depth:", depth)
536 self._check_relative_imports(depth)
537
538 def test_main_relative_import(self):
539 for depth in range(2, 5):
540 if verbose > 1: print("Testing main relative imports at depth:", depth)
541 self._check_relative_imports(depth, "__main__")
542
543 def test_run_name(self):
544 depth = 1
545 run_name = "And now for something completely different"
546 pkg_dir, mod_fname, mod_name, mod_spec = (
547 self._make_pkg(example_source, depth))
548 forget(mod_name)
549 expected_ns = example_namespace.copy()
550 expected_ns.update({
551 "__name__": run_name,
552 "__file__": mod_fname,
553 "__cached__": importlib.util.cache_from_source(mod_fname),
554 "__package__": mod_name.rpartition(".")[0],
555 "__spec__": mod_spec,
556 })
557 def create_ns(init_globals):
558 return run_module(mod_name, init_globals, run_name)
559 try:
560 self.check_code_execution(create_ns, expected_ns)
561 finally:
562 self._del_pkg(pkg_dir)
563
564 def test_pkgutil_walk_packages(self):
565 # This is a dodgy hack to use the test_runpy infrastructure to test
566 # issue #15343. Issue #15348 declares this is indeed a dodgy hack ;)
567 import pkgutil
568 max_depth = 4
569 base_name = "__runpy_pkg__"
570 package_suffixes = ["uncle", "uncle.cousin"]
571 module_suffixes = ["uncle.cousin.nephew", base_name + ".sibling"]
572 expected_packages = set()
573 expected_modules = set()
574 for depth in range(1, max_depth):
575 pkg_name = ".".join([base_name] * depth)
576 expected_packages.add(pkg_name)
577 for name in package_suffixes:
578 expected_packages.add(pkg_name + "." + name)
579 for name in module_suffixes:
580 expected_modules.add(pkg_name + "." + name)
581 pkg_name = ".".join([base_name] * max_depth)
582 expected_packages.add(pkg_name)
583 expected_modules.add(pkg_name + ".runpy_test")
584 pkg_dir, mod_fname, mod_name, mod_spec = (
585 self._make_pkg("", max_depth))
586 self.addCleanup(self._del_pkg, pkg_dir)
587 for depth in range(2, max_depth+1):
588 self._add_relative_modules(pkg_dir, "", depth)
589 for moduleinfo in pkgutil.walk_packages([pkg_dir]):
590 self.assertIsInstance(moduleinfo, pkgutil.ModuleInfo)
591 self.assertIsInstance(moduleinfo.module_finder,
592 importlib.machinery.FileFinder)
593 if moduleinfo.ispkg:
594 expected_packages.remove(moduleinfo.name)
595 else:
596 expected_modules.remove(moduleinfo.name)
597 self.assertEqual(len(expected_packages), 0, expected_packages)
598 self.assertEqual(len(expected_modules), 0, expected_modules)
599
600 class RunPathTestCase(unittest.TestCase, CodeExecutionMixin):
601 """Unit tests for runpy.run_path"""
602
603 def _make_test_script(self, script_dir, script_basename,
604 source=None, omit_suffix=False):
605 if source is None:
606 source = example_source
607 return make_script(script_dir, script_basename,
608 source, omit_suffix)
609
610 def _check_script(self, script_name, expected_name, expected_file,
611 expected_argv0, mod_name=None,
612 expect_spec=True, check_loader=True):
613 # First check is without run_name
614 def create_ns(init_globals):
615 return run_path(script_name, init_globals)
616 expected_ns = example_namespace.copy()
617 if mod_name is None:
618 spec_name = expected_name
619 else:
620 spec_name = mod_name
621 if expect_spec:
622 mod_spec = importlib.util.spec_from_file_location(spec_name,
623 expected_file)
624 mod_cached = mod_spec.cached
625 if not check_loader:
626 mod_spec.loader = None
627 else:
628 mod_spec = mod_cached = None
629
630 expected_ns.update({
631 "__name__": expected_name,
632 "__file__": expected_file,
633 "__cached__": mod_cached,
634 "__package__": "",
635 "__spec__": mod_spec,
636 "run_argv0": expected_argv0,
637 "run_name_in_sys_modules": True,
638 "module_in_sys_modules": True,
639 })
640 self.check_code_execution(create_ns, expected_ns)
641 # Second check makes sure run_name works in all cases
642 run_name = "prove.issue15230.is.fixed"
643 def create_ns(init_globals):
644 return run_path(script_name, init_globals, run_name)
645 if expect_spec and mod_name is None:
646 mod_spec = importlib.util.spec_from_file_location(run_name,
647 expected_file)
648 if not check_loader:
649 mod_spec.loader = None
650 expected_ns["__spec__"] = mod_spec
651 expected_ns["__name__"] = run_name
652 expected_ns["__package__"] = run_name.rpartition(".")[0]
653 self.check_code_execution(create_ns, expected_ns)
654
655 def _check_import_error(self, script_name, msg):
656 msg = re.escape(msg)
657 self.assertRaisesRegex(ImportError, msg, run_path, script_name)
658
659 def test_basic_script(self):
660 with temp_dir() as script_dir:
661 mod_name = 'script'
662 script_name = self._make_test_script(script_dir, mod_name)
663 self._check_script(script_name, "<run_path>", script_name,
664 script_name, expect_spec=False)
665
666 def test_basic_script_with_pathlike_object(self):
667 with temp_dir() as script_dir:
668 mod_name = 'script'
669 script_name = self._make_test_script(script_dir, mod_name)
670 self._check_script(FakePath(script_name), "<run_path>",
671 script_name,
672 script_name,
673 expect_spec=False)
674
675 def test_basic_script_no_suffix(self):
676 with temp_dir() as script_dir:
677 mod_name = 'script'
678 script_name = self._make_test_script(script_dir, mod_name,
679 omit_suffix=True)
680 self._check_script(script_name, "<run_path>", script_name,
681 script_name, expect_spec=False)
682
683 def test_script_compiled(self):
684 with temp_dir() as script_dir:
685 mod_name = 'script'
686 script_name = self._make_test_script(script_dir, mod_name)
687 compiled_name = py_compile.compile(script_name, doraise=True)
688 os.remove(script_name)
689 self._check_script(compiled_name, "<run_path>", compiled_name,
690 compiled_name, expect_spec=False)
691
692 def test_directory(self):
693 with temp_dir() as script_dir:
694 mod_name = '__main__'
695 script_name = self._make_test_script(script_dir, mod_name)
696 self._check_script(script_dir, "<run_path>", script_name,
697 script_dir, mod_name=mod_name)
698
699 def test_directory_compiled(self):
700 with temp_dir() as script_dir:
701 mod_name = '__main__'
702 script_name = self._make_test_script(script_dir, mod_name)
703 compiled_name = py_compile.compile(script_name, doraise=True)
704 os.remove(script_name)
705 if not sys.dont_write_bytecode:
706 legacy_pyc = make_legacy_pyc(script_name)
707 self._check_script(script_dir, "<run_path>", legacy_pyc,
708 script_dir, mod_name=mod_name)
709
710 def test_directory_error(self):
711 with temp_dir() as script_dir:
712 mod_name = 'not_main'
713 script_name = self._make_test_script(script_dir, mod_name)
714 msg = "can't find '__main__' module in %r" % script_dir
715 self._check_import_error(script_dir, msg)
716
717 def test_zipfile(self):
718 with temp_dir() as script_dir:
719 mod_name = '__main__'
720 script_name = self._make_test_script(script_dir, mod_name)
721 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
722 self._check_script(zip_name, "<run_path>", fname, zip_name,
723 mod_name=mod_name, check_loader=False)
724
725 def test_zipfile_compiled(self):
726 with temp_dir() as script_dir:
727 mod_name = '__main__'
728 script_name = self._make_test_script(script_dir, mod_name)
729 compiled_name = py_compile.compile(script_name, doraise=True)
730 zip_name, fname = make_zip_script(script_dir, 'test_zip',
731 compiled_name)
732 self._check_script(zip_name, "<run_path>", fname, zip_name,
733 mod_name=mod_name, check_loader=False)
734
735 def test_zipfile_error(self):
736 with temp_dir() as script_dir:
737 mod_name = 'not_main'
738 script_name = self._make_test_script(script_dir, mod_name)
739 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
740 msg = "can't find '__main__' module in %r" % zip_name
741 self._check_import_error(zip_name, msg)
742
743 @no_tracing
744 @requires_resource('cpu')
745 def test_main_recursion_error(self):
746 with temp_dir() as script_dir, temp_dir() as dummy_dir:
747 mod_name = '__main__'
748 source = ("import runpy\n"
749 "runpy.run_path(%r)\n") % dummy_dir
750 script_name = self._make_test_script(script_dir, mod_name, source)
751 zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
752 with infinite_recursion(25):
753 self.assertRaises(RecursionError, run_path, zip_name)
754
755 def test_encoding(self):
756 with temp_dir() as script_dir:
757 filename = os.path.join(script_dir, 'script.py')
758 with open(filename, 'w', encoding='latin1') as f:
759 f.write("""
760 #coding:latin1
761 s = "non-ASCII: h\xe9"
762 """)
763 result = run_path(filename)
764 self.assertEqual(result['s'], "non-ASCII: h\xe9")
765
766
767 @force_not_colorized_test_class
768 class TestExit(unittest.TestCase):
769 STATUS_CONTROL_C_EXIT = 0xC000013A
770 EXPECTED_CODE = (
771 STATUS_CONTROL_C_EXIT
772 if sys.platform == "win32"
773 else -signal.SIGINT
774 )
775 @staticmethod
776 @contextlib.contextmanager
777 def tmp_path(*args, **kwargs):
778 with temp_dir() as tmp_fn:
779 yield pathlib.Path(tmp_fn)
780
781
782 def run(self, *args, **kwargs):
783 with self.tmp_path() as tmp:
784 self.ham = ham = tmp / "ham.py"
785 ham.write_text(
786 textwrap.dedent(
787 """\
788 raise KeyboardInterrupt
789 """
790 )
791 )
792 super().run(*args, **kwargs)
793
794 @requires_subprocess()
795 def assertSigInt(self, cmd, *args, **kwargs):
796 # Use -E to ignore PYTHONSAFEPATH
797 cmd = [sys.executable, '-E', *cmd]
798 proc = subprocess.run(cmd, *args, **kwargs, text=True, stderr=subprocess.PIPE)
799 self.assertTrue(proc.stderr.endswith("\nKeyboardInterrupt\n"), proc.stderr)
800 self.assertEqual(proc.returncode, self.EXPECTED_CODE)
801
802 def test_pymain_run_file(self):
803 self.assertSigInt([self.ham])
804
805 def test_pymain_run_file_runpy_run_module(self):
806 tmp = self.ham.parent
807 run_module = tmp / "run_module.py"
808 run_module.write_text(
809 textwrap.dedent(
810 """\
811 import runpy
812 runpy.run_module("ham")
813 """
814 )
815 )
816 self.assertSigInt([run_module], cwd=tmp)
817
818 def test_pymain_run_file_runpy_run_module_as_main(self):
819 tmp = self.ham.parent
820 run_module_as_main = tmp / "run_module_as_main.py"
821 run_module_as_main.write_text(
822 textwrap.dedent(
823 """\
824 import runpy
825 runpy._run_module_as_main("ham")
826 """
827 )
828 )
829 self.assertSigInt([run_module_as_main], cwd=tmp)
830
831 def test_pymain_run_command_run_module(self):
832 self.assertSigInt(
833 ["-c", "import runpy; runpy.run_module('ham')"],
834 cwd=self.ham.parent,
835 )
836
837 def test_pymain_run_command(self):
838 self.assertSigInt(["-c", "import ham"], cwd=self.ham.parent)
839
840 def test_pymain_run_stdin(self):
841 self.assertSigInt([], input="import ham", cwd=self.ham.parent)
842
843 def test_pymain_run_module(self):
844 ham = self.ham
845 self.assertSigInt(["-m", ham.stem], cwd=ham.parent)
846
847
848 if __name__ == "__main__":
849 unittest.main()