summaryrefslogtreecommitdiffstats
path: root/Lib/test
diff options
context:
space:
mode:
authorEric Snow <ericsnowcurrently@gmail.com>2021-10-14 21:32:18 (GMT)
committerGitHub <noreply@github.com>2021-10-14 21:32:18 (GMT)
commit79cf20e48d0b5d69d9fac2a0204b5ac2c366066a (patch)
tree25085badecbf93f53fb3a0efdaa1641390041c72 /Lib/test
parentb2af211e229df941d9b404f69547a264115156b5 (diff)
downloadcpython-79cf20e48d0b5d69d9fac2a0204b5ac2c366066a.zip
cpython-79cf20e48d0b5d69d9fac2a0204b5ac2c366066a.tar.gz
cpython-79cf20e48d0b5d69d9fac2a0204b5ac2c366066a.tar.bz2
bpo-21736: Set __file__ on frozen stdlib modules. (gh-28656)
Currently frozen modules do not have __file__ set. In their spec, origin is set to "frozen" and they are marked as not having a location. (Similarly, for frozen packages __path__ is set to an empty list.) However, for frozen stdlib modules we are able to extrapolate __file__ as long as we can determine the stdlib directory at runtime. (We now do so since gh-28586.) Having __file__ set is helpful for a number of reasons. Likewise, having a non-empty __path__ means we can import submodules of a frozen package from the filesystem (e.g. we could partially freeze the encodings module). This change sets __file__ (and adds to __path__) for frozen stdlib modules. It uses sys._stdlibdir (from gh-28586) and the frozen module alias information (from gh-28655). All that work is done in FrozenImporter (in Lib/importlib/_bootstrap.py). Also, if a frozen module is imported before importlib is bootstrapped (during interpreter initialization) then we fix up that module and its spec during the importlib bootstrapping step (i.e. imporlib._bootstrap._setup()) to match what gets set by FrozenImporter, including setting the file info (if the stdlib dir is known). To facilitate this, modules imported using PyImport_ImportFrozenModule() have __origname__ set using the frozen module alias info. __origname__ is popped off during importlib bootstrap. (To be clear, even with this change the new code to set __file__ during fixups in imporlib._bootstrap._setup() doesn't actually get triggered yet. This is because sys._stdlibdir hasn't been set yet in interpreter initialization at the point importlib is bootstrapped. However, we do fix up such modules at that point to otherwise match the result of importing through FrozenImporter, just not the __file__ and __path__ parts. Doing so will require changes in the order in which things happen during interpreter initialization. That can be addressed separately. Once it is, the file-related fixup code from this PR will kick in.) Here are things this change does not do: * set __file__ for non-stdlib modules (no way of knowing the parent dir) * set __file__ if the stdlib dir is not known (nor assume the expense of finding it) * relatedly, set __file__ if the stdlib is in a zip file * verify that the filename set to __file__ actually exists (too expensive) * update __path__ for frozen packages that alias a non-package (since there is no package dir) Other things this change skips, but we may do later: * set __file__ on modules imported using PyImport_ImportFrozenModule() * set co_filename when we unmarshal the frozen code object while importing the module (e.g. in FrozenImporter.exec_module()) -- this would allow tracebacks to show source lines * implement FrozenImporter.get_filename() and FrozenImporter.get_source() https://bugs.python.org/issue21736
Diffstat (limited to 'Lib/test')
-rw-r--r--Lib/test/test_frozen.py3
-rw-r--r--Lib/test/test_importlib/frozen/test_finder.py29
-rw-r--r--Lib/test/test_importlib/frozen/test_loader.py32
3 files changed, 36 insertions, 28 deletions
diff --git a/Lib/test/test_frozen.py b/Lib/test/test_frozen.py
index 029fd06..0b4a12b 100644
--- a/Lib/test/test_frozen.py
+++ b/Lib/test/test_frozen.py
@@ -39,9 +39,6 @@ class TestFrozen(unittest.TestCase):
self.assertIs(spam.__spec__.loader,
importlib.machinery.FrozenImporter)
- # This is not possible until frozen packages have __path__ set properly.
- # See https://bugs.python.org/issue21736.
- @unittest.expectedFailure
def test_unfrozen_submodule_in_frozen_package(self):
with import_helper.CleanImport('__phello__', '__phello__.spam'):
with import_helper.frozen_modules(enabled=True):
diff --git a/Lib/test/test_importlib/frozen/test_finder.py b/Lib/test/test_importlib/frozen/test_finder.py
index cd5586d..66080b2 100644
--- a/Lib/test/test_importlib/frozen/test_finder.py
+++ b/Lib/test/test_importlib/frozen/test_finder.py
@@ -44,30 +44,31 @@ class FindSpecTests(abc.FinderTests):
if not filename:
if not origname:
origname = spec.name
+ filename = resolve_stdlib_file(origname)
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,
+ filename=filename if origname else None,
)
self.assertDictEqual(actual, expected)
def check_search_locations(self, spec):
- # Frozen packages do not have any path entries.
- # (See https://bugs.python.org/issue21736.)
- expected = []
+ """This is only called when testing packages."""
+ missing = object()
+ filename = getattr(spec.loader_state, 'filename', missing)
+ origname = getattr(spec.loader_state, 'origname', None)
+ if not origname or filename is missing:
+ # We deal with this in check_loader_state().
+ return
+ if not filename:
+ expected = []
+ elif origname != spec.name and not origname.startswith('<'):
+ expected = []
+ else:
+ expected = [os.path.dirname(filename)]
self.assertListEqual(spec.submodule_search_locations, expected)
def test_module(self):
diff --git a/Lib/test/test_importlib/frozen/test_loader.py b/Lib/test/test_importlib/frozen/test_loader.py
index d6f39fa..f1ccb8a 100644
--- a/Lib/test/test_importlib/frozen/test_loader.py
+++ b/Lib/test/test_importlib/frozen/test_loader.py
@@ -3,10 +3,11 @@ from .. import util
machinery = util.import_importlib('importlib.machinery')
-from test.support import captured_stdout, import_helper
+from test.support import captured_stdout, import_helper, STDLIB_DIR
import _imp
import contextlib
import marshal
+import os.path
import types
import unittest
import warnings
@@ -30,20 +31,27 @@ def fresh(name, *, oldapi=False):
yield
+def resolve_stdlib_file(name, ispkg=False):
+ assert name
+ if ispkg:
+ return os.path.join(STDLIB_DIR, *name.split('.'), '__init__.py')
+ else:
+ return os.path.join(STDLIB_DIR, *name.split('.')) + '.py'
+
+
class ExecModuleTests(abc.LoaderTests):
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,
+ filename=resolve_stdlib_file(origname or name, is_package),
),
)
module = types.ModuleType(name)
@@ -68,7 +76,6 @@ class ExecModuleTests(abc.LoaderTests):
self.assertEqual(getattr(module, attr), value)
self.assertEqual(output, 'Hello world!\n')
self.assertTrue(hasattr(module, '__spec__'))
- self.assertIsNone(module.__spec__.loader_state.data)
self.assertEqual(module.__spec__.loader_state.origname, name)
def test_package(self):
@@ -82,7 +89,6 @@ class ExecModuleTests(abc.LoaderTests):
name=name, attr=attr, given=attr_value,
expected=value))
self.assertEqual(output, 'Hello world!\n')
- self.assertIsNone(module.__spec__.loader_state.data)
self.assertEqual(module.__spec__.loader_state.origname, name)
def test_lacking_parent(self):
@@ -139,36 +145,41 @@ class LoaderTests(abc.LoaderTests):
def test_module(self):
module, stdout = self.load_module('__hello__')
+ filename = resolve_stdlib_file('__hello__')
check = {'__name__': '__hello__',
'__package__': '',
'__loader__': self.machinery.FrozenImporter,
+ '__file__': filename,
}
for attr, value in check.items():
- self.assertEqual(getattr(module, attr), value)
+ self.assertEqual(getattr(module, attr, None), value)
self.assertEqual(stdout.getvalue(), 'Hello world!\n')
- self.assertFalse(hasattr(module, '__file__'))
def test_package(self):
module, stdout = self.load_module('__phello__')
+ filename = resolve_stdlib_file('__phello__', ispkg=True)
+ pkgdir = os.path.dirname(filename)
check = {'__name__': '__phello__',
'__package__': '__phello__',
- '__path__': [],
+ '__path__': [pkgdir],
'__loader__': self.machinery.FrozenImporter,
+ '__file__': filename,
}
for attr, value in check.items():
- attr_value = getattr(module, attr)
+ attr_value = getattr(module, attr, None)
self.assertEqual(attr_value, value,
"for __phello__.%s, %r != %r" %
(attr, attr_value, value))
self.assertEqual(stdout.getvalue(), 'Hello world!\n')
- self.assertFalse(hasattr(module, '__file__'))
def test_lacking_parent(self):
with util.uncache('__phello__'):
module, stdout = self.load_module('__phello__.spam')
+ filename = resolve_stdlib_file('__phello__.spam')
check = {'__name__': '__phello__.spam',
'__package__': '__phello__',
'__loader__': self.machinery.FrozenImporter,
+ '__file__': filename,
}
for attr, value in check.items():
attr_value = getattr(module, attr)
@@ -176,7 +187,6 @@ class LoaderTests(abc.LoaderTests):
"for __phello__.spam.%s, %r != %r" %
(attr, attr_value, value))
self.assertEqual(stdout.getvalue(), 'Hello world!\n')
- self.assertFalse(hasattr(module, '__file__'))
def test_module_reuse(self):
with fresh('__hello__', oldapi=True):