ยปCore Development>Code coverage>Lib/test/test_importlib/import_/test_relative_imports.py

Python code coverage for Lib/test/test_importlib/import_/test_relative_imports.py

#countcontent
1n/a"""Test relative imports (PEP 328)."""
2n/afrom .. import util
3n/aimport unittest
4n/aimport warnings
5n/a
6n/a
7n/aclass RelativeImports:
8n/a
9n/a """PEP 328 introduced relative imports. This allows for imports to occur
10n/a from within a package without having to specify the actual package name.
11n/a
12n/a A simple example is to import another module within the same package
13n/a [module from module]::
14n/a
15n/a # From pkg.mod1 with pkg.mod2 being a module.
16n/a from . import mod2
17n/a
18n/a This also works for getting an attribute from a module that is specified
19n/a in a relative fashion [attr from module]::
20n/a
21n/a # From pkg.mod1.
22n/a from .mod2 import attr
23n/a
24n/a But this is in no way restricted to working between modules; it works
25n/a from [package to module],::
26n/a
27n/a # From pkg, importing pkg.module which is a module.
28n/a from . import module
29n/a
30n/a [module to package],::
31n/a
32n/a # Pull attr from pkg, called from pkg.module which is a module.
33n/a from . import attr
34n/a
35n/a and [package to package]::
36n/a
37n/a # From pkg.subpkg1 (both pkg.subpkg[1,2] are packages).
38n/a from .. import subpkg2
39n/a
40n/a The number of dots used is in no way restricted [deep import]::
41n/a
42n/a # Import pkg.attr from pkg.pkg1.pkg2.pkg3.pkg4.pkg5.
43n/a from ...... import attr
44n/a
45n/a To prevent someone from accessing code that is outside of a package, one
46n/a cannot reach the location containing the root package itself::
47n/a
48n/a # From pkg.__init__ [too high from package]
49n/a from .. import top_level
50n/a
51n/a # From pkg.module [too high from module]
52n/a from .. import top_level
53n/a
54n/a Relative imports are the only type of import that allow for an empty
55n/a module name for an import [empty name].
56n/a
57n/a """
58n/a
59n/a def relative_import_test(self, create, globals_, callback):
60n/a """Abstract out boilerplace for setting up for an import test."""
61n/a uncache_names = []
62n/a for name in create:
63n/a if not name.endswith('.__init__'):
64n/a uncache_names.append(name)
65n/a else:
66n/a uncache_names.append(name[:-len('.__init__')])
67n/a with util.mock_spec(*create) as importer:
68n/a with util.import_state(meta_path=[importer]):
69n/a with warnings.catch_warnings():
70n/a warnings.simplefilter("ignore")
71n/a for global_ in globals_:
72n/a with util.uncache(*uncache_names):
73n/a callback(global_)
74n/a
75n/a
76n/a def test_module_from_module(self):
77n/a # [module from module]
78n/a create = 'pkg.__init__', 'pkg.mod2'
79n/a globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'}
80n/a def callback(global_):
81n/a self.__import__('pkg') # For __import__().
82n/a module = self.__import__('', global_, fromlist=['mod2'], level=1)
83n/a self.assertEqual(module.__name__, 'pkg')
84n/a self.assertTrue(hasattr(module, 'mod2'))
85n/a self.assertEqual(module.mod2.attr, 'pkg.mod2')
86n/a self.relative_import_test(create, globals_, callback)
87n/a
88n/a def test_attr_from_module(self):
89n/a # [attr from module]
90n/a create = 'pkg.__init__', 'pkg.mod2'
91n/a globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'}
92n/a def callback(global_):
93n/a self.__import__('pkg') # For __import__().
94n/a module = self.__import__('mod2', global_, fromlist=['attr'],
95n/a level=1)
96n/a self.assertEqual(module.__name__, 'pkg.mod2')
97n/a self.assertEqual(module.attr, 'pkg.mod2')
98n/a self.relative_import_test(create, globals_, callback)
99n/a
100n/a def test_package_to_module(self):
101n/a # [package to module]
102n/a create = 'pkg.__init__', 'pkg.module'
103n/a globals_ = ({'__package__': 'pkg'},
104n/a {'__name__': 'pkg', '__path__': ['blah']})
105n/a def callback(global_):
106n/a self.__import__('pkg') # For __import__().
107n/a module = self.__import__('', global_, fromlist=['module'],
108n/a level=1)
109n/a self.assertEqual(module.__name__, 'pkg')
110n/a self.assertTrue(hasattr(module, 'module'))
111n/a self.assertEqual(module.module.attr, 'pkg.module')
112n/a self.relative_import_test(create, globals_, callback)
113n/a
114n/a def test_module_to_package(self):
115n/a # [module to package]
116n/a create = 'pkg.__init__', 'pkg.module'
117n/a globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'}
118n/a def callback(global_):
119n/a self.__import__('pkg') # For __import__().
120n/a module = self.__import__('', global_, fromlist=['attr'], level=1)
121n/a self.assertEqual(module.__name__, 'pkg')
122n/a self.relative_import_test(create, globals_, callback)
123n/a
124n/a def test_package_to_package(self):
125n/a # [package to package]
126n/a create = ('pkg.__init__', 'pkg.subpkg1.__init__',
127n/a 'pkg.subpkg2.__init__')
128n/a globals_ = ({'__package__': 'pkg.subpkg1'},
129n/a {'__name__': 'pkg.subpkg1', '__path__': ['blah']})
130n/a def callback(global_):
131n/a module = self.__import__('', global_, fromlist=['subpkg2'],
132n/a level=2)
133n/a self.assertEqual(module.__name__, 'pkg')
134n/a self.assertTrue(hasattr(module, 'subpkg2'))
135n/a self.assertEqual(module.subpkg2.attr, 'pkg.subpkg2.__init__')
136n/a
137n/a def test_deep_import(self):
138n/a # [deep import]
139n/a create = ['pkg.__init__']
140n/a for count in range(1,6):
141n/a create.append('{0}.pkg{1}.__init__'.format(
142n/a create[-1][:-len('.__init__')], count))
143n/a globals_ = ({'__package__': 'pkg.pkg1.pkg2.pkg3.pkg4.pkg5'},
144n/a {'__name__': 'pkg.pkg1.pkg2.pkg3.pkg4.pkg5',
145n/a '__path__': ['blah']})
146n/a def callback(global_):
147n/a self.__import__(globals_[0]['__package__'])
148n/a module = self.__import__('', global_, fromlist=['attr'], level=6)
149n/a self.assertEqual(module.__name__, 'pkg')
150n/a self.relative_import_test(create, globals_, callback)
151n/a
152n/a def test_too_high_from_package(self):
153n/a # [too high from package]
154n/a create = ['top_level', 'pkg.__init__']
155n/a globals_ = ({'__package__': 'pkg'},
156n/a {'__name__': 'pkg', '__path__': ['blah']})
157n/a def callback(global_):
158n/a self.__import__('pkg')
159n/a with self.assertRaises(ValueError):
160n/a self.__import__('', global_, fromlist=['top_level'],
161n/a level=2)
162n/a self.relative_import_test(create, globals_, callback)
163n/a
164n/a def test_too_high_from_module(self):
165n/a # [too high from module]
166n/a create = ['top_level', 'pkg.__init__', 'pkg.module']
167n/a globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'}
168n/a def callback(global_):
169n/a self.__import__('pkg')
170n/a with self.assertRaises(ValueError):
171n/a self.__import__('', global_, fromlist=['top_level'],
172n/a level=2)
173n/a self.relative_import_test(create, globals_, callback)
174n/a
175n/a def test_empty_name_w_level_0(self):
176n/a # [empty name]
177n/a with self.assertRaises(ValueError):
178n/a self.__import__('')
179n/a
180n/a def test_import_from_different_package(self):
181n/a # Test importing from a different package than the caller.
182n/a # in pkg.subpkg1.mod
183n/a # from ..subpkg2 import mod
184n/a create = ['__runpy_pkg__.__init__',
185n/a '__runpy_pkg__.__runpy_pkg__.__init__',
186n/a '__runpy_pkg__.uncle.__init__',
187n/a '__runpy_pkg__.uncle.cousin.__init__',
188n/a '__runpy_pkg__.uncle.cousin.nephew']
189n/a globals_ = {'__package__': '__runpy_pkg__.__runpy_pkg__'}
190n/a def callback(global_):
191n/a self.__import__('__runpy_pkg__.__runpy_pkg__')
192n/a module = self.__import__('uncle.cousin', globals_, {},
193n/a fromlist=['nephew'],
194n/a level=2)
195n/a self.assertEqual(module.__name__, '__runpy_pkg__.uncle.cousin')
196n/a self.relative_import_test(create, globals_, callback)
197n/a
198n/a def test_import_relative_import_no_fromlist(self):
199n/a # Import a relative module w/ no fromlist.
200n/a create = ['crash.__init__', 'crash.mod']
201n/a globals_ = [{'__package__': 'crash', '__name__': 'crash'}]
202n/a def callback(global_):
203n/a self.__import__('crash')
204n/a mod = self.__import__('mod', global_, {}, [], 1)
205n/a self.assertEqual(mod.__name__, 'crash.mod')
206n/a self.relative_import_test(create, globals_, callback)
207n/a
208n/a def test_relative_import_no_globals(self):
209n/a # No globals for a relative import is an error.
210n/a with warnings.catch_warnings():
211n/a warnings.simplefilter("ignore")
212n/a with self.assertRaises(KeyError):
213n/a self.__import__('sys', level=1)
214n/a
215n/a def test_relative_import_no_package(self):
216n/a with self.assertRaises(ImportError):
217n/a self.__import__('a', {'__package__': '', '__spec__': None},
218n/a level=1)
219n/a
220n/a def test_relative_import_no_package_exists_absolute(self):
221n/a with self.assertRaises(ImportError):
222n/a self.__import__('sys', {'__package__': '', '__spec__': None},
223n/a level=1)
224n/a
225n/a
226n/a(Frozen_RelativeImports,
227n/a Source_RelativeImports
228n/a ) = util.test_both(RelativeImports, __import__=util.__import__)
229n/a
230n/a
231n/aif __name__ == '__main__':
232n/a unittest.main()