Repository URL to install this package:
# Test the runpy module
import unittest
import os
import os.path
import sys
import re
import tempfile
import importlib, importlib.machinery, importlib.util
import py_compile
import warnings
import pathlib
from test.support import (
forget, make_legacy_pyc, unload, verbose, no_tracing,
create_empty_file, temp_dir)
from test.support.script_helper import make_script, make_zip_script
import runpy
from runpy import _run_code, _run_module_code, run_module, run_path
# Note: This module can't safely test _run_module_as_main as it
# runs its tests in the current process, which would mess with the
# real __main__ module (usually test.regrtest)
# See test_cmd_line_script for a test that executes that code path
# Set up the test code and expected results
example_source = """\
# Check basic code execution
result = ['Top level assignment']
def f():
result.append('Lower level reference')
f()
del f
# Check the sys module
import sys
run_argv0 = sys.argv[0]
run_name_in_sys_modules = __name__ in sys.modules
module_in_sys_modules = (run_name_in_sys_modules and
globals() is sys.modules[__name__].__dict__)
# Check nested operation
import runpy
nested = runpy._run_module_code('x=1\\n', mod_name='<run>')
"""
implicit_namespace = {
"__name__": None,
"__file__": None,
"__cached__": None,
"__package__": None,
"__doc__": None,
"__spec__": None
}
example_namespace = {
"sys": sys,
"runpy": runpy,
"result": ["Top level assignment", "Lower level reference"],
"run_argv0": sys.argv[0],
"run_name_in_sys_modules": False,
"module_in_sys_modules": False,
"nested": dict(implicit_namespace,
x=1, __name__="<run>", __loader__=None),
}
example_namespace.update(implicit_namespace)
class CodeExecutionMixin:
# Issue #15230 (run_path not handling run_name correctly) highlighted a
# problem with the way arguments were being passed from higher level APIs
# down to lower level code. This mixin makes it easier to ensure full
# testing occurs at those upper layers as well, not just at the utility
# layer
# Figuring out the loader details in advance is hard to do, so we skip
# checking the full details of loader and loader_state
CHECKED_SPEC_ATTRIBUTES = ["name", "parent", "origin", "cached",
"has_location", "submodule_search_locations"]
def assertNamespaceMatches(self, result_ns, expected_ns):
"""Check two namespaces match.
Ignores any unspecified interpreter created names
"""
# Avoid side effects
result_ns = result_ns.copy()
expected_ns = expected_ns.copy()
# Impls are permitted to add extra names, so filter them out
for k in list(result_ns):
if k.startswith("__") and k.endswith("__"):
if k not in expected_ns:
result_ns.pop(k)
if k not in expected_ns["nested"]:
result_ns["nested"].pop(k)
# Spec equality includes the loader, so we take the spec out of the
# result namespace and check that separately
result_spec = result_ns.pop("__spec__")
expected_spec = expected_ns.pop("__spec__")
if expected_spec is None:
self.assertIsNone(result_spec)
else:
# If an expected loader is set, we just check we got the right
# type, rather than checking for full equality
if expected_spec.loader is not None:
self.assertEqual(type(result_spec.loader),
type(expected_spec.loader))
for attr in self.CHECKED_SPEC_ATTRIBUTES:
k = "__spec__." + attr
actual = (k, getattr(result_spec, attr))
expected = (k, getattr(expected_spec, attr))
self.assertEqual(actual, expected)
# For the rest, we still don't use direct dict comparison on the
# namespace, as the diffs are too hard to debug if anything breaks
self.assertEqual(set(result_ns), set(expected_ns))
for k in result_ns:
actual = (k, result_ns[k])
expected = (k, expected_ns[k])
self.assertEqual(actual, expected)
def check_code_execution(self, create_namespace, expected_namespace):
"""Check that an interface runs the example code correctly
First argument is a callable accepting the initial globals and
using them to create the actual namespace
Second argument is the expected result
"""
sentinel = object()
expected_ns = expected_namespace.copy()
run_name = expected_ns["__name__"]
saved_argv0 = sys.argv[0]
saved_mod = sys.modules.get(run_name, sentinel)
# Check without initial globals
result_ns = create_namespace(None)
self.assertNamespaceMatches(result_ns, expected_ns)
self.assertIs(sys.argv[0], saved_argv0)
self.assertIs(sys.modules.get(run_name, sentinel), saved_mod)
# And then with initial globals
initial_ns = {"sentinel": sentinel}
expected_ns["sentinel"] = sentinel
result_ns = create_namespace(initial_ns)
self.assertIsNot(result_ns, initial_ns)
self.assertNamespaceMatches(result_ns, expected_ns)
self.assertIs(sys.argv[0], saved_argv0)
self.assertIs(sys.modules.get(run_name, sentinel), saved_mod)
class ExecutionLayerTestCase(unittest.TestCase, CodeExecutionMixin):
"""Unit tests for runpy._run_code and runpy._run_module_code"""
def test_run_code(self):
expected_ns = example_namespace.copy()
expected_ns.update({
"__loader__": None,
})
def create_ns(init_globals):
return _run_code(example_source, {}, init_globals)
self.check_code_execution(create_ns, expected_ns)
def test_run_module_code(self):
mod_name = "<Nonsense>"
mod_fname = "Some other nonsense"
mod_loader = "Now you're just being silly"
mod_package = '' # Treat as a top level module
mod_spec = importlib.machinery.ModuleSpec(mod_name,
origin=mod_fname,
loader=mod_loader)
expected_ns = example_namespace.copy()
expected_ns.update({
"__name__": mod_name,
"__file__": mod_fname,
"__loader__": mod_loader,
"__package__": mod_package,
"__spec__": mod_spec,
"run_argv0": mod_fname,
"run_name_in_sys_modules": True,
"module_in_sys_modules": True,
})
def create_ns(init_globals):
return _run_module_code(example_source,
init_globals,
mod_name,
mod_spec)
self.check_code_execution(create_ns, expected_ns)
# TODO: Use self.addCleanup to get rid of a lot of try-finally blocks
class RunModuleTestCase(unittest.TestCase, CodeExecutionMixin):
"""Unit tests for runpy.run_module"""
def expect_import_error(self, mod_name):
try:
run_module(mod_name)
except ImportError:
pass
else:
self.fail("Expected import error for " + mod_name)
def test_invalid_names(self):
# Builtin module
self.expect_import_error("sys")
# Non-existent modules
self.expect_import_error("sys.imp.eric")
self.expect_import_error("os.path.half")
self.expect_import_error("a.bee")
# Relative names not allowed
self.expect_import_error(".howard")
self.expect_import_error("..eaten")
self.expect_import_error(".test_runpy")
self.expect_import_error(".unittest")
# Package without __main__.py
self.expect_import_error("multiprocessing")
def test_library_module(self):
self.assertEqual(run_module("runpy")["__name__"], "runpy")
def _add_pkg_dir(self, pkg_dir, namespace=False):
os.mkdir(pkg_dir)
if namespace:
return None
pkg_fname = os.path.join(pkg_dir, "__init__.py")
create_empty_file(pkg_fname)
return pkg_fname
def _make_pkg(self, source, depth, mod_base="runpy_test",
*, namespace=False, parent_namespaces=False):
# Enforce a couple of internal sanity checks on test cases
if (namespace or parent_namespaces) and not depth:
raise RuntimeError("Can't mark top level module as a "
"namespace package")
pkg_name = "__runpy_pkg__"
test_fname = mod_base+os.extsep+"py"
pkg_dir = sub_dir = os.path.realpath(tempfile.mkdtemp())
if verbose > 1: print(" Package tree in:", sub_dir)
sys.path.insert(0, pkg_dir)
if verbose > 1: print(" Updated sys.path:", sys.path[0])
if depth:
namespace_flags = [parent_namespaces] * depth
namespace_flags[-1] = namespace
for namespace_flag in namespace_flags:
sub_dir = os.path.join(sub_dir, pkg_name)
pkg_fname = self._add_pkg_dir(sub_dir, namespace_flag)
if verbose > 1: print(" Next level in:", sub_dir)
if verbose > 1: print(" Created:", pkg_fname)
mod_fname = os.path.join(sub_dir, test_fname)
with open(mod_fname, "w") as mod_file:
mod_file.write(source)
if verbose > 1: print(" Created:", mod_fname)
mod_name = (pkg_name+".")*depth + mod_base
mod_spec = importlib.util.spec_from_file_location(mod_name,
mod_fname)
return pkg_dir, mod_fname, mod_name, mod_spec
def _del_pkg(self, top):
for entry in list(sys.modules):
if entry.startswith("__runpy_pkg__"):
del sys.modules[entry]
if verbose > 1: print(" Removed sys.modules entries")
del sys.path[0]
if verbose > 1: print(" Removed sys.path entry")
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
try:
os.remove(os.path.join(root, name))
except OSError as ex:
if verbose > 1: print(ex) # Persist with cleaning up
for name in dirs:
fullname = os.path.join(root, name)
try:
os.rmdir(fullname)
except OSError as ex:
if verbose > 1: print(ex) # Persist with cleaning up
try:
os.rmdir(top)
if verbose > 1: print(" Removed package tree")
except OSError as ex:
if verbose > 1: print(ex) # Persist with cleaning up
def _fix_ns_for_legacy_pyc(self, ns, alter_sys):
char_to_add = "c"
ns["__file__"] += char_to_add
ns["__cached__"] = ns["__file__"]
spec = ns["__spec__"]
new_spec = importlib.util.spec_from_file_location(spec.name,
ns["__file__"])
ns["__spec__"] = new_spec
if alter_sys:
ns["run_argv0"] += char_to_add
def _check_module(self, depth, alter_sys=False,
*, namespace=False, parent_namespaces=False):
pkg_dir, mod_fname, mod_name, mod_spec = (
self._make_pkg(example_source, depth,
namespace=namespace,
parent_namespaces=parent_namespaces))
forget(mod_name)
expected_ns = example_namespace.copy()
expected_ns.update({
"__name__": mod_name,
"__file__": mod_fname,
"__cached__": mod_spec.cached,
"__package__": mod_name.rpartition(".")[0],
"__spec__": mod_spec,
})
if alter_sys:
expected_ns.update({
"run_argv0": mod_fname,
"run_name_in_sys_modules": True,
"module_in_sys_modules": True,
})
def create_ns(init_globals):
return run_module(mod_name, init_globals, alter_sys=alter_sys)
try:
if verbose > 1: print("Running from source:", mod_name)
self.check_code_execution(create_ns, expected_ns)
importlib.invalidate_caches()
__import__(mod_name)
os.remove(mod_fname)
if not sys.dont_write_bytecode:
make_legacy_pyc(mod_fname)
unload(mod_name) # In case loader caches paths
importlib.invalidate_caches()
if verbose > 1: print("Running from compiled:", mod_name)
self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
self.check_code_execution(create_ns, expected_ns)
finally:
self._del_pkg(pkg_dir)
if verbose > 1: print("Module executed successfully")
def _check_package(self, depth, alter_sys=False,
*, namespace=False, parent_namespaces=False):
pkg_dir, mod_fname, mod_name, mod_spec = (
self._make_pkg(example_source, depth, "__main__",
namespace=namespace,
parent_namespaces=parent_namespaces))
pkg_name = mod_name.rpartition(".")[0]
forget(mod_name)
expected_ns = example_namespace.copy()
expected_ns.update({
"__name__": mod_name,
"__file__": mod_fname,
"__cached__": importlib.util.cache_from_source(mod_fname),
"__package__": pkg_name,
"__spec__": mod_spec,
})
if alter_sys:
expected_ns.update({
"run_argv0": mod_fname,
"run_name_in_sys_modules": True,
Loading ...