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

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

#countcontent
1n/a"""PEP 366 ("Main module explicit relative imports") specifies the
2n/asemantics for the __package__ attribute on modules. This attribute is
3n/aused, when available, to detect which package a module belongs to (instead
4n/aof using the typical __path__/__name__ test).
5n/a
6n/a"""
7n/aimport unittest
8n/aimport warnings
9n/afrom .. import util
10n/a
11n/a
12n/aclass Using__package__:
13n/a
14n/a """Use of __package__ supercedes the use of __name__/__path__ to calculate
15n/a what package a module belongs to. The basic algorithm is [__package__]::
16n/a
17n/a def resolve_name(name, package, level):
18n/a level -= 1
19n/a base = package.rsplit('.', level)[0]
20n/a return '{0}.{1}'.format(base, name)
21n/a
22n/a But since there is no guarantee that __package__ has been set (or not been
23n/a set to None [None]), there has to be a way to calculate the attribute's value
24n/a [__name__]::
25n/a
26n/a def calc_package(caller_name, has___path__):
27n/a if has__path__:
28n/a return caller_name
29n/a else:
30n/a return caller_name.rsplit('.', 1)[0]
31n/a
32n/a Then the normal algorithm for relative name imports can proceed as if
33n/a __package__ had been set.
34n/a
35n/a """
36n/a
37n/a def import_module(self, globals_):
38n/a with self.mock_modules('pkg.__init__', 'pkg.fake') as importer:
39n/a with util.import_state(meta_path=[importer]):
40n/a self.__import__('pkg.fake')
41n/a module = self.__import__('',
42n/a globals=globals_,
43n/a fromlist=['attr'], level=2)
44n/a return module
45n/a
46n/a def test_using___package__(self):
47n/a # [__package__]
48n/a module = self.import_module({'__package__': 'pkg.fake'})
49n/a self.assertEqual(module.__name__, 'pkg')
50n/a
51n/a def test_using___name__(self):
52n/a # [__name__]
53n/a with warnings.catch_warnings():
54n/a warnings.simplefilter("ignore")
55n/a module = self.import_module({'__name__': 'pkg.fake',
56n/a '__path__': []})
57n/a self.assertEqual(module.__name__, 'pkg')
58n/a
59n/a def test_warn_when_using___name__(self):
60n/a with self.assertWarns(ImportWarning):
61n/a self.import_module({'__name__': 'pkg.fake', '__path__': []})
62n/a
63n/a def test_None_as___package__(self):
64n/a # [None]
65n/a with warnings.catch_warnings():
66n/a warnings.simplefilter("ignore")
67n/a module = self.import_module({
68n/a '__name__': 'pkg.fake', '__path__': [], '__package__': None })
69n/a self.assertEqual(module.__name__, 'pkg')
70n/a
71n/a def test_spec_fallback(self):
72n/a # If __package__ isn't defined, fall back on __spec__.parent.
73n/a module = self.import_module({'__spec__': FakeSpec('pkg.fake')})
74n/a self.assertEqual(module.__name__, 'pkg')
75n/a
76n/a def test_warn_when_package_and_spec_disagree(self):
77n/a # Raise an ImportWarning if __package__ != __spec__.parent.
78n/a with self.assertWarns(ImportWarning):
79n/a self.import_module({'__package__': 'pkg.fake',
80n/a '__spec__': FakeSpec('pkg.fakefake')})
81n/a
82n/a def test_bad__package__(self):
83n/a globals = {'__package__': '<not real>'}
84n/a with self.assertRaises(SystemError):
85n/a self.__import__('', globals, {}, ['relimport'], 1)
86n/a
87n/a def test_bunk__package__(self):
88n/a globals = {'__package__': 42}
89n/a with self.assertRaises(TypeError):
90n/a self.__import__('', globals, {}, ['relimport'], 1)
91n/a
92n/a
93n/aclass FakeSpec:
94n/a def __init__(self, parent):
95n/a self.parent = parent
96n/a
97n/a
98n/aclass Using__package__PEP302(Using__package__):
99n/a mock_modules = util.mock_modules
100n/a
101n/a
102n/a(Frozen_UsingPackagePEP302,
103n/a Source_UsingPackagePEP302
104n/a ) = util.test_both(Using__package__PEP302, __import__=util.__import__)
105n/a
106n/a
107n/aclass Using__package__PEP451(Using__package__):
108n/a mock_modules = util.mock_spec
109n/a
110n/a
111n/a(Frozen_UsingPackagePEP451,
112n/a Source_UsingPackagePEP451
113n/a ) = util.test_both(Using__package__PEP451, __import__=util.__import__)
114n/a
115n/a
116n/aclass Setting__package__:
117n/a
118n/a """Because __package__ is a new feature, it is not always set by a loader.
119n/a Import will set it as needed to help with the transition to relying on
120n/a __package__.
121n/a
122n/a For a top-level module, __package__ is set to None [top-level]. For a
123n/a package __name__ is used for __package__ [package]. For submodules the
124n/a value is __name__.rsplit('.', 1)[0] [submodule].
125n/a
126n/a """
127n/a
128n/a __import__ = util.__import__['Source']
129n/a
130n/a # [top-level]
131n/a def test_top_level(self):
132n/a with self.mock_modules('top_level') as mock:
133n/a with util.import_state(meta_path=[mock]):
134n/a del mock['top_level'].__package__
135n/a module = self.__import__('top_level')
136n/a self.assertEqual(module.__package__, '')
137n/a
138n/a # [package]
139n/a def test_package(self):
140n/a with self.mock_modules('pkg.__init__') as mock:
141n/a with util.import_state(meta_path=[mock]):
142n/a del mock['pkg'].__package__
143n/a module = self.__import__('pkg')
144n/a self.assertEqual(module.__package__, 'pkg')
145n/a
146n/a # [submodule]
147n/a def test_submodule(self):
148n/a with self.mock_modules('pkg.__init__', 'pkg.mod') as mock:
149n/a with util.import_state(meta_path=[mock]):
150n/a del mock['pkg.mod'].__package__
151n/a pkg = self.__import__('pkg.mod')
152n/a module = getattr(pkg, 'mod')
153n/a self.assertEqual(module.__package__, 'pkg')
154n/a
155n/aclass Setting__package__PEP302(Setting__package__, unittest.TestCase):
156n/a mock_modules = util.mock_modules
157n/a
158n/aclass Setting__package__PEP451(Setting__package__, unittest.TestCase):
159n/a mock_modules = util.mock_spec
160n/a
161n/a
162n/aif __name__ == '__main__':
163n/a unittest.main()