ยปCore Development>Code coverage>Lib/test/test_imp.py

Python code coverage for Lib/test/test_imp.py

#countcontent
1n/atry:
2n/a import _thread
3n/aexcept ImportError:
4n/a _thread = None
5n/aimport importlib
6n/aimport importlib.util
7n/aimport os
8n/aimport os.path
9n/aimport sys
10n/afrom test import support
11n/aimport unittest
12n/aimport warnings
13n/awith warnings.catch_warnings():
14n/a warnings.simplefilter('ignore', DeprecationWarning)
15n/a import imp
16n/a
17n/a
18n/adef requires_load_dynamic(meth):
19n/a """Decorator to skip a test if not running under CPython or lacking
20n/a imp.load_dynamic()."""
21n/a meth = support.cpython_only(meth)
22n/a return unittest.skipIf(not hasattr(imp, 'load_dynamic'),
23n/a 'imp.load_dynamic() required')(meth)
24n/a
25n/a
26n/a@unittest.skipIf(_thread is None, '_thread module is required')
27n/aclass LockTests(unittest.TestCase):
28n/a
29n/a """Very basic test of import lock functions."""
30n/a
31n/a def verify_lock_state(self, expected):
32n/a self.assertEqual(imp.lock_held(), expected,
33n/a "expected imp.lock_held() to be %r" % expected)
34n/a def testLock(self):
35n/a LOOPS = 50
36n/a
37n/a # The import lock may already be held, e.g. if the test suite is run
38n/a # via "import test.autotest".
39n/a lock_held_at_start = imp.lock_held()
40n/a self.verify_lock_state(lock_held_at_start)
41n/a
42n/a for i in range(LOOPS):
43n/a imp.acquire_lock()
44n/a self.verify_lock_state(True)
45n/a
46n/a for i in range(LOOPS):
47n/a imp.release_lock()
48n/a
49n/a # The original state should be restored now.
50n/a self.verify_lock_state(lock_held_at_start)
51n/a
52n/a if not lock_held_at_start:
53n/a try:
54n/a imp.release_lock()
55n/a except RuntimeError:
56n/a pass
57n/a else:
58n/a self.fail("release_lock() without lock should raise "
59n/a "RuntimeError")
60n/a
61n/aclass ImportTests(unittest.TestCase):
62n/a def setUp(self):
63n/a mod = importlib.import_module('test.encoded_modules')
64n/a self.test_strings = mod.test_strings
65n/a self.test_path = mod.__path__
66n/a
67n/a def test_import_encoded_module(self):
68n/a for modname, encoding, teststr in self.test_strings:
69n/a mod = importlib.import_module('test.encoded_modules.'
70n/a 'module_' + modname)
71n/a self.assertEqual(teststr, mod.test)
72n/a
73n/a def test_find_module_encoding(self):
74n/a for mod, encoding, _ in self.test_strings:
75n/a with imp.find_module('module_' + mod, self.test_path)[0] as fd:
76n/a self.assertEqual(fd.encoding, encoding)
77n/a
78n/a path = [os.path.dirname(__file__)]
79n/a with self.assertRaises(SyntaxError):
80n/a imp.find_module('badsyntax_pep3120', path)
81n/a
82n/a def test_issue1267(self):
83n/a for mod, encoding, _ in self.test_strings:
84n/a fp, filename, info = imp.find_module('module_' + mod,
85n/a self.test_path)
86n/a with fp:
87n/a self.assertNotEqual(fp, None)
88n/a self.assertEqual(fp.encoding, encoding)
89n/a self.assertEqual(fp.tell(), 0)
90n/a self.assertEqual(fp.readline(), '# test %s encoding\n'
91n/a % encoding)
92n/a
93n/a fp, filename, info = imp.find_module("tokenize")
94n/a with fp:
95n/a self.assertNotEqual(fp, None)
96n/a self.assertEqual(fp.encoding, "utf-8")
97n/a self.assertEqual(fp.tell(), 0)
98n/a self.assertEqual(fp.readline(),
99n/a '"""Tokenization help for Python programs.\n')
100n/a
101n/a def test_issue3594(self):
102n/a temp_mod_name = 'test_imp_helper'
103n/a sys.path.insert(0, '.')
104n/a try:
105n/a with open(temp_mod_name + '.py', 'w') as file:
106n/a file.write("# coding: cp1252\nu = 'test.test_imp'\n")
107n/a file, filename, info = imp.find_module(temp_mod_name)
108n/a file.close()
109n/a self.assertEqual(file.encoding, 'cp1252')
110n/a finally:
111n/a del sys.path[0]
112n/a support.unlink(temp_mod_name + '.py')
113n/a support.unlink(temp_mod_name + '.pyc')
114n/a
115n/a def test_issue5604(self):
116n/a # Test cannot cover imp.load_compiled function.
117n/a # Martin von Loewis note what shared library cannot have non-ascii
118n/a # character because init_xxx function cannot be compiled
119n/a # and issue never happens for dynamic modules.
120n/a # But sources modified to follow generic way for processing pathes.
121n/a
122n/a # the return encoding could be uppercase or None
123n/a fs_encoding = sys.getfilesystemencoding()
124n/a
125n/a # covers utf-8 and Windows ANSI code pages
126n/a # one non-space symbol from every page
127n/a # (http://en.wikipedia.org/wiki/Code_page)
128n/a known_locales = {
129n/a 'utf-8' : b'\xc3\xa4',
130n/a 'cp1250' : b'\x8C',
131n/a 'cp1251' : b'\xc0',
132n/a 'cp1252' : b'\xc0',
133n/a 'cp1253' : b'\xc1',
134n/a 'cp1254' : b'\xc0',
135n/a 'cp1255' : b'\xe0',
136n/a 'cp1256' : b'\xe0',
137n/a 'cp1257' : b'\xc0',
138n/a 'cp1258' : b'\xc0',
139n/a }
140n/a
141n/a if sys.platform == 'darwin':
142n/a self.assertEqual(fs_encoding, 'utf-8')
143n/a # Mac OS X uses the Normal Form D decomposition
144n/a # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
145n/a special_char = b'a\xcc\x88'
146n/a else:
147n/a special_char = known_locales.get(fs_encoding)
148n/a
149n/a if not special_char:
150n/a self.skipTest("can't run this test with %s as filesystem encoding"
151n/a % fs_encoding)
152n/a decoded_char = special_char.decode(fs_encoding)
153n/a temp_mod_name = 'test_imp_helper_' + decoded_char
154n/a test_package_name = 'test_imp_helper_package_' + decoded_char
155n/a init_file_name = os.path.join(test_package_name, '__init__.py')
156n/a try:
157n/a # if the curdir is not in sys.path the test fails when run with
158n/a # ./python ./Lib/test/regrtest.py test_imp
159n/a sys.path.insert(0, os.curdir)
160n/a with open(temp_mod_name + '.py', 'w') as file:
161n/a file.write('a = 1\n')
162n/a file, filename, info = imp.find_module(temp_mod_name)
163n/a with file:
164n/a self.assertIsNotNone(file)
165n/a self.assertTrue(filename[:-3].endswith(temp_mod_name))
166n/a self.assertEqual(info[0], '.py')
167n/a self.assertEqual(info[1], 'r')
168n/a self.assertEqual(info[2], imp.PY_SOURCE)
169n/a
170n/a mod = imp.load_module(temp_mod_name, file, filename, info)
171n/a self.assertEqual(mod.a, 1)
172n/a
173n/a with warnings.catch_warnings():
174n/a warnings.simplefilter('ignore')
175n/a mod = imp.load_source(temp_mod_name, temp_mod_name + '.py')
176n/a self.assertEqual(mod.a, 1)
177n/a
178n/a with warnings.catch_warnings():
179n/a warnings.simplefilter('ignore')
180n/a if not sys.dont_write_bytecode:
181n/a mod = imp.load_compiled(
182n/a temp_mod_name,
183n/a imp.cache_from_source(temp_mod_name + '.py'))
184n/a self.assertEqual(mod.a, 1)
185n/a
186n/a if not os.path.exists(test_package_name):
187n/a os.mkdir(test_package_name)
188n/a with open(init_file_name, 'w') as file:
189n/a file.write('b = 2\n')
190n/a with warnings.catch_warnings():
191n/a warnings.simplefilter('ignore')
192n/a package = imp.load_package(test_package_name, test_package_name)
193n/a self.assertEqual(package.b, 2)
194n/a finally:
195n/a del sys.path[0]
196n/a for ext in ('.py', '.pyc'):
197n/a support.unlink(temp_mod_name + ext)
198n/a support.unlink(init_file_name + ext)
199n/a support.rmtree(test_package_name)
200n/a support.rmtree('__pycache__')
201n/a
202n/a def test_issue9319(self):
203n/a path = os.path.dirname(__file__)
204n/a self.assertRaises(SyntaxError,
205n/a imp.find_module, "badsyntax_pep3120", [path])
206n/a
207n/a def test_load_from_source(self):
208n/a # Verify that the imp module can correctly load and find .py files
209n/a # XXX (ncoghlan): It would be nice to use support.CleanImport
210n/a # here, but that breaks because the os module registers some
211n/a # handlers in copy_reg on import. Since CleanImport doesn't
212n/a # revert that registration, the module is left in a broken
213n/a # state after reversion. Reinitialising the module contents
214n/a # and just reverting os.environ to its previous state is an OK
215n/a # workaround
216n/a orig_path = os.path
217n/a orig_getenv = os.getenv
218n/a with support.EnvironmentVarGuard():
219n/a x = imp.find_module("os")
220n/a self.addCleanup(x[0].close)
221n/a new_os = imp.load_module("os", *x)
222n/a self.assertIs(os, new_os)
223n/a self.assertIs(orig_path, new_os.path)
224n/a self.assertIsNot(orig_getenv, new_os.getenv)
225n/a
226n/a @requires_load_dynamic
227n/a def test_issue15828_load_extensions(self):
228n/a # Issue 15828 picked up that the adapter between the old imp API
229n/a # and importlib couldn't handle C extensions
230n/a example = "_heapq"
231n/a x = imp.find_module(example)
232n/a file_ = x[0]
233n/a if file_ is not None:
234n/a self.addCleanup(file_.close)
235n/a mod = imp.load_module(example, *x)
236n/a self.assertEqual(mod.__name__, example)
237n/a
238n/a @requires_load_dynamic
239n/a def test_issue16421_multiple_modules_in_one_dll(self):
240n/a # Issue 16421: loading several modules from the same compiled file fails
241n/a m = '_testimportmultiple'
242n/a fileobj, pathname, description = imp.find_module(m)
243n/a fileobj.close()
244n/a mod0 = imp.load_dynamic(m, pathname)
245n/a mod1 = imp.load_dynamic('_testimportmultiple_foo', pathname)
246n/a mod2 = imp.load_dynamic('_testimportmultiple_bar', pathname)
247n/a self.assertEqual(mod0.__name__, m)
248n/a self.assertEqual(mod1.__name__, '_testimportmultiple_foo')
249n/a self.assertEqual(mod2.__name__, '_testimportmultiple_bar')
250n/a with self.assertRaises(ImportError):
251n/a imp.load_dynamic('nonexistent', pathname)
252n/a
253n/a @requires_load_dynamic
254n/a def test_load_dynamic_ImportError_path(self):
255n/a # Issue #1559549 added `name` and `path` attributes to ImportError
256n/a # in order to provide better detail. Issue #10854 implemented those
257n/a # attributes on import failures of extensions on Windows.
258n/a path = 'bogus file path'
259n/a name = 'extension'
260n/a with self.assertRaises(ImportError) as err:
261n/a imp.load_dynamic(name, path)
262n/a self.assertIn(path, err.exception.path)
263n/a self.assertEqual(name, err.exception.name)
264n/a
265n/a @requires_load_dynamic
266n/a def test_load_module_extension_file_is_None(self):
267n/a # When loading an extension module and the file is None, open one
268n/a # on the behalf of imp.load_dynamic().
269n/a # Issue #15902
270n/a name = '_testimportmultiple'
271n/a found = imp.find_module(name)
272n/a if found[0] is not None:
273n/a found[0].close()
274n/a if found[2][2] != imp.C_EXTENSION:
275n/a self.skipTest("found module doesn't appear to be a C extension")
276n/a imp.load_module(name, None, *found[1:])
277n/a
278n/a @requires_load_dynamic
279n/a def test_issue24748_load_module_skips_sys_modules_check(self):
280n/a name = 'test.imp_dummy'
281n/a try:
282n/a del sys.modules[name]
283n/a except KeyError:
284n/a pass
285n/a try:
286n/a module = importlib.import_module(name)
287n/a spec = importlib.util.find_spec('_testmultiphase')
288n/a module = imp.load_dynamic(name, spec.origin)
289n/a self.assertEqual(module.__name__, name)
290n/a self.assertEqual(module.__spec__.name, name)
291n/a self.assertEqual(module.__spec__.origin, spec.origin)
292n/a self.assertRaises(AttributeError, getattr, module, 'dummy_name')
293n/a self.assertEqual(module.int_const, 1969)
294n/a self.assertIs(sys.modules[name], module)
295n/a finally:
296n/a try:
297n/a del sys.modules[name]
298n/a except KeyError:
299n/a pass
300n/a
301n/a @unittest.skipIf(sys.dont_write_bytecode,
302n/a "test meaningful only when writing bytecode")
303n/a def test_bug7732(self):
304n/a with support.temp_cwd():
305n/a source = support.TESTFN + '.py'
306n/a os.mkdir(source)
307n/a self.assertRaisesRegex(ImportError, '^No module',
308n/a imp.find_module, support.TESTFN, ["."])
309n/a
310n/a def test_multiple_calls_to_get_data(self):
311n/a # Issue #18755: make sure multiple calls to get_data() can succeed.
312n/a loader = imp._LoadSourceCompatibility('imp', imp.__file__,
313n/a open(imp.__file__))
314n/a loader.get_data(imp.__file__) # File should be closed
315n/a loader.get_data(imp.__file__) # Will need to create a newly opened file
316n/a
317n/a
318n/aclass ReloadTests(unittest.TestCase):
319n/a
320n/a """Very basic tests to make sure that imp.reload() operates just like
321n/a reload()."""
322n/a
323n/a def test_source(self):
324n/a # XXX (ncoghlan): It would be nice to use test.support.CleanImport
325n/a # here, but that breaks because the os module registers some
326n/a # handlers in copy_reg on import. Since CleanImport doesn't
327n/a # revert that registration, the module is left in a broken
328n/a # state after reversion. Reinitialising the module contents
329n/a # and just reverting os.environ to its previous state is an OK
330n/a # workaround
331n/a with support.EnvironmentVarGuard():
332n/a import os
333n/a imp.reload(os)
334n/a
335n/a def test_extension(self):
336n/a with support.CleanImport('time'):
337n/a import time
338n/a imp.reload(time)
339n/a
340n/a def test_builtin(self):
341n/a with support.CleanImport('marshal'):
342n/a import marshal
343n/a imp.reload(marshal)
344n/a
345n/a def test_with_deleted_parent(self):
346n/a # see #18681
347n/a from html import parser
348n/a html = sys.modules.pop('html')
349n/a def cleanup():
350n/a sys.modules['html'] = html
351n/a self.addCleanup(cleanup)
352n/a with self.assertRaisesRegex(ImportError, 'html'):
353n/a imp.reload(parser)
354n/a
355n/a
356n/aclass PEP3147Tests(unittest.TestCase):
357n/a """Tests of PEP 3147."""
358n/a
359n/a tag = imp.get_tag()
360n/a
361n/a @unittest.skipUnless(sys.implementation.cache_tag is not None,
362n/a 'requires sys.implementation.cache_tag not be None')
363n/a def test_cache_from_source(self):
364n/a # Given the path to a .py file, return the path to its PEP 3147
365n/a # defined .pyc file (i.e. under __pycache__).
366n/a path = os.path.join('foo', 'bar', 'baz', 'qux.py')
367n/a expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
368n/a 'qux.{}.pyc'.format(self.tag))
369n/a self.assertEqual(imp.cache_from_source(path, True), expect)
370n/a
371n/a @unittest.skipUnless(sys.implementation.cache_tag is not None,
372n/a 'requires sys.implementation.cache_tag to not be '
373n/a 'None')
374n/a def test_source_from_cache(self):
375n/a # Given the path to a PEP 3147 defined .pyc file, return the path to
376n/a # its source. This tests the good path.
377n/a path = os.path.join('foo', 'bar', 'baz', '__pycache__',
378n/a 'qux.{}.pyc'.format(self.tag))
379n/a expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
380n/a self.assertEqual(imp.source_from_cache(path), expect)
381n/a
382n/a
383n/aclass NullImporterTests(unittest.TestCase):
384n/a @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
385n/a "Need an undecodeable filename")
386n/a def test_unencodeable(self):
387n/a name = support.TESTFN_UNENCODABLE
388n/a os.mkdir(name)
389n/a try:
390n/a self.assertRaises(ImportError, imp.NullImporter, name)
391n/a finally:
392n/a os.rmdir(name)
393n/a
394n/a
395n/aif __name__ == "__main__":
396n/a unittest.main()