def exec_module(self, name, origname=None): with import_helper.frozen_modules(): is_package = self.machinery.FrozenImporter.is_package(name) code = _imp.get_frozen_object(name) spec = self.machinery.ModuleSpec( name, self.machinery.FrozenImporter, origin='frozen', is_package=is_package, loader_state=types.SimpleNamespace( data=marshal.dumps(code), origname=origname or name, ), ) module = types.ModuleType(name) module.__spec__ = spec assert not hasattr(module, 'initialized') with fresh(name): self.machinery.FrozenImporter.exec_module(module) with captured_stdout() as stdout: module.main() self.assertTrue(module.initialized) self.assertTrue(hasattr(module, '__spec__')) self.assertEqual(module.__spec__.origin, 'frozen') return module, stdout.getvalue()
def check_data(self, spec): with import_helper.frozen_modules(): expected = _imp.get_frozen_object(spec.name) data = spec.loader_state # We can't compare the marshaled data directly because # marshal.dumps() would mark "expected" as a ref, which slightly # changes the output. (See https://bugs.python.org/issue34093.) code = marshal.loads(data) self.assertEqual(code, expected)
def check_loader_state(self, spec, origname=None, filename=None): if not filename: if not origname: origname = spec.name actual = dict(vars(spec.loader_state)) # Check the code object used to import the frozen module. # We can't compare the marshaled data directly because # marshal.dumps() would mark "expected" (below) as a ref, # which slightly changes the output. # (See https://bugs.python.org/issue34093.) data = actual.pop('data') with import_helper.frozen_modules(): expected = _imp.get_frozen_object(spec.name) code = marshal.loads(data) self.assertEqual(code, expected) # Check the rest of spec.loader_state. expected = dict(origname=origname, ) self.assertDictEqual(actual, expected)
import _imp import time as import_time assert _imp.is_builtin("time") == True assert _imp.is_builtin("os") == False assert _imp.is_builtin("not existing module") == False assert _imp.is_frozen("__hello__") == True assert _imp.is_frozen("os") == False class FakeSpec: def __init__(self, name): self.name = name A = FakeSpec("time") imp_time = _imp.create_builtin(A) assert imp_time.sleep == import_time.sleep B = FakeSpec("not existing module") assert _imp.create_builtin(B) == None _imp.exec_builtin(imp_time) == 0 _imp.get_frozen_object("__hello__") hello = _imp.init_frozen("__hello__") assert hello.initialized == True
def get_code(cls, fullname): """Return the code object for the frozen module.""" return _imp.get_frozen_object(fullname)