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

Python code coverage for Lib/test/test_import.py

#countcontent
1n/a# We import importlib *ASAP* in order to test #15386
2n/aimport importlib
3n/aimport importlib.util
4n/afrom importlib._bootstrap import _get_sourcefile
5n/aimport builtins
6n/afrom test.test_importlib.import_ import util as importlib_util
7n/aimport marshal
8n/aimport os
9n/aimport platform
10n/aimport py_compile
11n/aimport random
12n/aimport stat
13n/aimport sys
14n/aimport unittest
15n/aimport unittest.mock as mock
16n/aimport textwrap
17n/aimport errno
18n/aimport shutil
19n/aimport contextlib
20n/a
21n/aimport test.support
22n/afrom test.support import (
23n/a EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython,
24n/a make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask,
25n/a unlink, unload, create_empty_file, cpython_only)
26n/afrom test import script_helper
27n/a
28n/a
29n/askip_if_dont_write_bytecode = unittest.skipIf(
30n/a sys.dont_write_bytecode,
31n/a "test meaningful only when writing bytecode")
32n/a
33n/adef remove_files(name):
34n/a for f in (name + ".py",
35n/a name + ".pyc",
36n/a name + ".pyo",
37n/a name + ".pyw",
38n/a name + "$py.class"):
39n/a unlink(f)
40n/a rmtree('__pycache__')
41n/a
42n/a
43n/a@contextlib.contextmanager
44n/adef _ready_to_import(name=None, source=""):
45n/a # sets up a temporary directory and removes it
46n/a # creates the module file
47n/a # temporarily clears the module from sys.modules (if any)
48n/a # reverts or removes the module when cleaning up
49n/a name = name or "spam"
50n/a with script_helper.temp_dir() as tempdir:
51n/a path = script_helper.make_script(tempdir, name, source)
52n/a old_module = sys.modules.pop(name, None)
53n/a try:
54n/a sys.path.insert(0, tempdir)
55n/a yield name, path
56n/a sys.path.remove(tempdir)
57n/a finally:
58n/a if old_module is not None:
59n/a sys.modules[name] = old_module
60n/a elif name in sys.modules:
61n/a del sys.modules[name]
62n/a
63n/a
64n/aclass ImportTests(unittest.TestCase):
65n/a
66n/a def setUp(self):
67n/a remove_files(TESTFN)
68n/a importlib.invalidate_caches()
69n/a
70n/a def tearDown(self):
71n/a unload(TESTFN)
72n/a
73n/a def test_case_sensitivity(self):
74n/a # Brief digression to test that import is case-sensitive: if we got
75n/a # this far, we know for sure that "random" exists.
76n/a with self.assertRaises(ImportError):
77n/a import RAnDoM
78n/a
79n/a def test_double_const(self):
80n/a # Another brief digression to test the accuracy of manifest float
81n/a # constants.
82n/a from test import double_const # don't blink -- that *was* the test
83n/a
84n/a def test_import(self):
85n/a def test_with_extension(ext):
86n/a # The extension is normally ".py", perhaps ".pyw".
87n/a source = TESTFN + ext
88n/a pyo = TESTFN + ".pyo"
89n/a if is_jython:
90n/a pyc = TESTFN + "$py.class"
91n/a else:
92n/a pyc = TESTFN + ".pyc"
93n/a
94n/a with open(source, "w") as f:
95n/a print("# This tests Python's ability to import a",
96n/a ext, "file.", file=f)
97n/a a = random.randrange(1000)
98n/a b = random.randrange(1000)
99n/a print("a =", a, file=f)
100n/a print("b =", b, file=f)
101n/a
102n/a if TESTFN in sys.modules:
103n/a del sys.modules[TESTFN]
104n/a importlib.invalidate_caches()
105n/a try:
106n/a try:
107n/a mod = __import__(TESTFN)
108n/a except ImportError as err:
109n/a self.fail("import from %s failed: %s" % (ext, err))
110n/a
111n/a self.assertEqual(mod.a, a,
112n/a "module loaded (%s) but contents invalid" % mod)
113n/a self.assertEqual(mod.b, b,
114n/a "module loaded (%s) but contents invalid" % mod)
115n/a finally:
116n/a forget(TESTFN)
117n/a unlink(source)
118n/a unlink(pyc)
119n/a unlink(pyo)
120n/a
121n/a sys.path.insert(0, os.curdir)
122n/a try:
123n/a test_with_extension(".py")
124n/a if sys.platform.startswith("win"):
125n/a for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]:
126n/a test_with_extension(ext)
127n/a finally:
128n/a del sys.path[0]
129n/a
130n/a def test_module_with_large_stack(self, module='longlist'):
131n/a # Regression test for http://bugs.python.org/issue561858.
132n/a filename = module + '.py'
133n/a
134n/a # Create a file with a list of 65000 elements.
135n/a with open(filename, 'w') as f:
136n/a f.write('d = [\n')
137n/a for i in range(65000):
138n/a f.write('"",\n')
139n/a f.write(']')
140n/a
141n/a try:
142n/a # Compile & remove .py file; we only need .pyc (or .pyo).
143n/a # Bytecode must be relocated from the PEP 3147 bytecode-only location.
144n/a py_compile.compile(filename)
145n/a finally:
146n/a unlink(filename)
147n/a
148n/a # Need to be able to load from current dir.
149n/a sys.path.append('')
150n/a importlib.invalidate_caches()
151n/a
152n/a try:
153n/a make_legacy_pyc(filename)
154n/a # This used to crash.
155n/a exec('import ' + module)
156n/a finally:
157n/a # Cleanup.
158n/a del sys.path[-1]
159n/a unlink(filename + 'c')
160n/a unlink(filename + 'o')
161n/a
162n/a def test_failing_import_sticks(self):
163n/a source = TESTFN + ".py"
164n/a with open(source, "w") as f:
165n/a print("a = 1/0", file=f)
166n/a
167n/a # New in 2.4, we shouldn't be able to import that no matter how often
168n/a # we try.
169n/a sys.path.insert(0, os.curdir)
170n/a importlib.invalidate_caches()
171n/a if TESTFN in sys.modules:
172n/a del sys.modules[TESTFN]
173n/a try:
174n/a for i in [1, 2, 3]:
175n/a self.assertRaises(ZeroDivisionError, __import__, TESTFN)
176n/a self.assertNotIn(TESTFN, sys.modules,
177n/a "damaged module in sys.modules on %i try" % i)
178n/a finally:
179n/a del sys.path[0]
180n/a remove_files(TESTFN)
181n/a
182n/a def test_import_name_binding(self):
183n/a # import x.y.z binds x in the current namespace
184n/a import test as x
185n/a import test.support
186n/a self.assertTrue(x is test, x.__name__)
187n/a self.assertTrue(hasattr(test.support, "__file__"))
188n/a
189n/a # import x.y.z as w binds z as w
190n/a import test.support as y
191n/a self.assertTrue(y is test.support, y.__name__)
192n/a
193n/a def test_failing_reload(self):
194n/a # A failing reload should leave the module object in sys.modules.
195n/a source = TESTFN + os.extsep + "py"
196n/a with open(source, "w") as f:
197n/a f.write("a = 1\nb=2\n")
198n/a
199n/a sys.path.insert(0, os.curdir)
200n/a try:
201n/a mod = __import__(TESTFN)
202n/a self.assertIn(TESTFN, sys.modules)
203n/a self.assertEqual(mod.a, 1, "module has wrong attribute values")
204n/a self.assertEqual(mod.b, 2, "module has wrong attribute values")
205n/a
206n/a # On WinXP, just replacing the .py file wasn't enough to
207n/a # convince reload() to reparse it. Maybe the timestamp didn't
208n/a # move enough. We force it to get reparsed by removing the
209n/a # compiled file too.
210n/a remove_files(TESTFN)
211n/a
212n/a # Now damage the module.
213n/a with open(source, "w") as f:
214n/a f.write("a = 10\nb=20//0\n")
215n/a
216n/a self.assertRaises(ZeroDivisionError, importlib.reload, mod)
217n/a # But we still expect the module to be in sys.modules.
218n/a mod = sys.modules.get(TESTFN)
219n/a self.assertIsNot(mod, None, "expected module to be in sys.modules")
220n/a
221n/a # We should have replaced a w/ 10, but the old b value should
222n/a # stick.
223n/a self.assertEqual(mod.a, 10, "module has wrong attribute values")
224n/a self.assertEqual(mod.b, 2, "module has wrong attribute values")
225n/a
226n/a finally:
227n/a del sys.path[0]
228n/a remove_files(TESTFN)
229n/a unload(TESTFN)
230n/a
231n/a @skip_if_dont_write_bytecode
232n/a def test_file_to_source(self):
233n/a # check if __file__ points to the source file where available
234n/a source = TESTFN + ".py"
235n/a with open(source, "w") as f:
236n/a f.write("test = None\n")
237n/a
238n/a sys.path.insert(0, os.curdir)
239n/a try:
240n/a mod = __import__(TESTFN)
241n/a self.assertTrue(mod.__file__.endswith('.py'))
242n/a os.remove(source)
243n/a del sys.modules[TESTFN]
244n/a make_legacy_pyc(source)
245n/a importlib.invalidate_caches()
246n/a mod = __import__(TESTFN)
247n/a base, ext = os.path.splitext(mod.__file__)
248n/a self.assertIn(ext, ('.pyc', '.pyo'))
249n/a finally:
250n/a del sys.path[0]
251n/a remove_files(TESTFN)
252n/a if TESTFN in sys.modules:
253n/a del sys.modules[TESTFN]
254n/a
255n/a def test_import_name_binding(self):
256n/a # import x.y.z binds x in the current namespace.
257n/a import test as x
258n/a import test.support
259n/a self.assertIs(x, test, x.__name__)
260n/a self.assertTrue(hasattr(test.support, "__file__"))
261n/a
262n/a # import x.y.z as w binds z as w.
263n/a import test.support as y
264n/a self.assertIs(y, test.support, y.__name__)
265n/a
266n/a def test_import_by_filename(self):
267n/a path = os.path.abspath(TESTFN)
268n/a encoding = sys.getfilesystemencoding()
269n/a try:
270n/a path.encode(encoding)
271n/a except UnicodeEncodeError:
272n/a self.skipTest('path is not encodable to {}'.format(encoding))
273n/a with self.assertRaises(ImportError) as c:
274n/a __import__(path)
275n/a
276n/a def test_import_in_del_does_not_crash(self):
277n/a # Issue 4236
278n/a testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\
279n/a import sys
280n/a class C:
281n/a def __del__(self):
282n/a import importlib
283n/a sys.argv.insert(0, C())
284n/a """))
285n/a script_helper.assert_python_ok(testfn)
286n/a
287n/a def test_timestamp_overflow(self):
288n/a # A modification timestamp larger than 2**32 should not be a problem
289n/a # when importing a module (issue #11235).
290n/a sys.path.insert(0, os.curdir)
291n/a try:
292n/a source = TESTFN + ".py"
293n/a compiled = importlib.util.cache_from_source(source)
294n/a with open(source, 'w') as f:
295n/a pass
296n/a try:
297n/a os.utime(source, (2 ** 33 - 5, 2 ** 33 - 5))
298n/a except OverflowError:
299n/a self.skipTest("cannot set modification time to large integer")
300n/a except OSError as e:
301n/a if e.errno != getattr(errno, 'EOVERFLOW', None):
302n/a raise
303n/a self.skipTest("cannot set modification time to large integer ({})".format(e))
304n/a __import__(TESTFN)
305n/a # The pyc file was created.
306n/a os.stat(compiled)
307n/a finally:
308n/a del sys.path[0]
309n/a remove_files(TESTFN)
310n/a
311n/a def test_bogus_fromlist(self):
312n/a try:
313n/a __import__('http', fromlist=['blah'])
314n/a except ImportError:
315n/a self.fail("fromlist must allow bogus names")
316n/a
317n/a @cpython_only
318n/a def test_delete_builtins_import(self):
319n/a args = ["-c", "del __builtins__.__import__; import os"]
320n/a popen = script_helper.spawn_python(*args)
321n/a stdout, stderr = popen.communicate()
322n/a self.assertIn(b"ImportError", stdout)
323n/a
324n/a def test_from_import_message_for_nonexistent_module(self):
325n/a with self.assertRaisesRegexp(ImportError, "^No module named 'bogus'"):
326n/a from bogus import foo
327n/a
328n/a def test_from_import_message_for_existing_module(self):
329n/a with self.assertRaisesRegexp(ImportError, "^cannot import name 'bogus'"):
330n/a from re import bogus
331n/a
332n/a
333n/a@skip_if_dont_write_bytecode
334n/aclass FilePermissionTests(unittest.TestCase):
335n/a # tests for file mode on cached .pyc/.pyo files
336n/a
337n/a @unittest.skipUnless(os.name == 'posix',
338n/a "test meaningful only on posix systems")
339n/a def test_creation_mode(self):
340n/a mask = 0o022
341n/a with temp_umask(mask), _ready_to_import() as (name, path):
342n/a cached_path = importlib.util.cache_from_source(path)
343n/a module = __import__(name)
344n/a if not os.path.exists(cached_path):
345n/a self.fail("__import__ did not result in creation of "
346n/a "either a .pyc or .pyo file")
347n/a stat_info = os.stat(cached_path)
348n/a
349n/a # Check that the umask is respected, and the executable bits
350n/a # aren't set.
351n/a self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)),
352n/a oct(0o666 & ~mask))
353n/a
354n/a @unittest.skipUnless(os.name == 'posix',
355n/a "test meaningful only on posix systems")
356n/a def test_cached_mode_issue_2051(self):
357n/a # permissions of .pyc should match those of .py, regardless of mask
358n/a mode = 0o600
359n/a with temp_umask(0o022), _ready_to_import() as (name, path):
360n/a cached_path = importlib.util.cache_from_source(path)
361n/a os.chmod(path, mode)
362n/a __import__(name)
363n/a if not os.path.exists(cached_path):
364n/a self.fail("__import__ did not result in creation of "
365n/a "either a .pyc or .pyo file")
366n/a stat_info = os.stat(cached_path)
367n/a
368n/a self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), oct(mode))
369n/a
370n/a @unittest.skipUnless(os.name == 'posix',
371n/a "test meaningful only on posix systems")
372n/a def test_cached_readonly(self):
373n/a mode = 0o400
374n/a with temp_umask(0o022), _ready_to_import() as (name, path):
375n/a cached_path = importlib.util.cache_from_source(path)
376n/a os.chmod(path, mode)
377n/a __import__(name)
378n/a if not os.path.exists(cached_path):
379n/a self.fail("__import__ did not result in creation of "
380n/a "either a .pyc or .pyo file")
381n/a stat_info = os.stat(cached_path)
382n/a
383n/a expected = mode | 0o200 # Account for fix for issue #6074
384n/a self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), oct(expected))
385n/a
386n/a def test_pyc_always_writable(self):
387n/a # Initially read-only .pyc files on Windows used to cause problems
388n/a # with later updates, see issue #6074 for details
389n/a with _ready_to_import() as (name, path):
390n/a # Write a Python file, make it read-only and import it
391n/a with open(path, 'w') as f:
392n/a f.write("x = 'original'\n")
393n/a # Tweak the mtime of the source to ensure pyc gets updated later
394n/a s = os.stat(path)
395n/a os.utime(path, (s.st_atime, s.st_mtime-100000000))
396n/a os.chmod(path, 0o400)
397n/a m = __import__(name)
398n/a self.assertEqual(m.x, 'original')
399n/a # Change the file and then reimport it
400n/a os.chmod(path, 0o600)
401n/a with open(path, 'w') as f:
402n/a f.write("x = 'rewritten'\n")
403n/a unload(name)
404n/a importlib.invalidate_caches()
405n/a m = __import__(name)
406n/a self.assertEqual(m.x, 'rewritten')
407n/a # Now delete the source file and check the pyc was rewritten
408n/a unlink(path)
409n/a unload(name)
410n/a importlib.invalidate_caches()
411n/a if __debug__:
412n/a bytecode_only = path + "c"
413n/a else:
414n/a bytecode_only = path + "o"
415n/a os.rename(importlib.util.cache_from_source(path), bytecode_only)
416n/a m = __import__(name)
417n/a self.assertEqual(m.x, 'rewritten')
418n/a
419n/a
420n/aclass PycRewritingTests(unittest.TestCase):
421n/a # Test that the `co_filename` attribute on code objects always points
422n/a # to the right file, even when various things happen (e.g. both the .py
423n/a # and the .pyc file are renamed).
424n/a
425n/a module_name = "unlikely_module_name"
426n/a module_source = """
427n/aimport sys
428n/acode_filename = sys._getframe().f_code.co_filename
429n/amodule_filename = __file__
430n/aconstant = 1
431n/adef func():
432n/a pass
433n/afunc_filename = func.__code__.co_filename
434n/a"""
435n/a dir_name = os.path.abspath(TESTFN)
436n/a file_name = os.path.join(dir_name, module_name) + os.extsep + "py"
437n/a compiled_name = importlib.util.cache_from_source(file_name)
438n/a
439n/a def setUp(self):
440n/a self.sys_path = sys.path[:]
441n/a self.orig_module = sys.modules.pop(self.module_name, None)
442n/a os.mkdir(self.dir_name)
443n/a with open(self.file_name, "w") as f:
444n/a f.write(self.module_source)
445n/a sys.path.insert(0, self.dir_name)
446n/a importlib.invalidate_caches()
447n/a
448n/a def tearDown(self):
449n/a sys.path[:] = self.sys_path
450n/a if self.orig_module is not None:
451n/a sys.modules[self.module_name] = self.orig_module
452n/a else:
453n/a unload(self.module_name)
454n/a unlink(self.file_name)
455n/a unlink(self.compiled_name)
456n/a rmtree(self.dir_name)
457n/a
458n/a def import_module(self):
459n/a ns = globals()
460n/a __import__(self.module_name, ns, ns)
461n/a return sys.modules[self.module_name]
462n/a
463n/a def test_basics(self):
464n/a mod = self.import_module()
465n/a self.assertEqual(mod.module_filename, self.file_name)
466n/a self.assertEqual(mod.code_filename, self.file_name)
467n/a self.assertEqual(mod.func_filename, self.file_name)
468n/a del sys.modules[self.module_name]
469n/a mod = self.import_module()
470n/a self.assertEqual(mod.module_filename, self.file_name)
471n/a self.assertEqual(mod.code_filename, self.file_name)
472n/a self.assertEqual(mod.func_filename, self.file_name)
473n/a
474n/a def test_incorrect_code_name(self):
475n/a py_compile.compile(self.file_name, dfile="another_module.py")
476n/a mod = self.import_module()
477n/a self.assertEqual(mod.module_filename, self.file_name)
478n/a self.assertEqual(mod.code_filename, self.file_name)
479n/a self.assertEqual(mod.func_filename, self.file_name)
480n/a
481n/a def test_module_without_source(self):
482n/a target = "another_module.py"
483n/a py_compile.compile(self.file_name, dfile=target)
484n/a os.remove(self.file_name)
485n/a pyc_file = make_legacy_pyc(self.file_name)
486n/a importlib.invalidate_caches()
487n/a mod = self.import_module()
488n/a self.assertEqual(mod.module_filename, pyc_file)
489n/a self.assertEqual(mod.code_filename, target)
490n/a self.assertEqual(mod.func_filename, target)
491n/a
492n/a def test_foreign_code(self):
493n/a py_compile.compile(self.file_name)
494n/a with open(self.compiled_name, "rb") as f:
495n/a header = f.read(12)
496n/a code = marshal.load(f)
497n/a constants = list(code.co_consts)
498n/a foreign_code = importlib.import_module.__code__
499n/a pos = constants.index(1)
500n/a constants[pos] = foreign_code
501n/a code = type(code)(code.co_argcount, code.co_kwonlyargcount,
502n/a code.co_nlocals, code.co_stacksize,
503n/a code.co_flags, code.co_code, tuple(constants),
504n/a code.co_names, code.co_varnames, code.co_filename,
505n/a code.co_name, code.co_firstlineno, code.co_lnotab,
506n/a code.co_freevars, code.co_cellvars)
507n/a with open(self.compiled_name, "wb") as f:
508n/a f.write(header)
509n/a marshal.dump(code, f)
510n/a mod = self.import_module()
511n/a self.assertEqual(mod.constant.co_filename, foreign_code.co_filename)
512n/a
513n/a
514n/aclass PathsTests(unittest.TestCase):
515n/a SAMPLES = ('test', 'test\u00e4\u00f6\u00fc\u00df', 'test\u00e9\u00e8',
516n/a 'test\u00b0\u00b3\u00b2')
517n/a path = TESTFN
518n/a
519n/a def setUp(self):
520n/a os.mkdir(self.path)
521n/a self.syspath = sys.path[:]
522n/a
523n/a def tearDown(self):
524n/a rmtree(self.path)
525n/a sys.path[:] = self.syspath
526n/a
527n/a # Regression test for http://bugs.python.org/issue1293.
528n/a def test_trailing_slash(self):
529n/a with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
530n/a f.write("testdata = 'test_trailing_slash'")
531n/a sys.path.append(self.path+'/')
532n/a mod = __import__("test_trailing_slash")
533n/a self.assertEqual(mod.testdata, 'test_trailing_slash')
534n/a unload("test_trailing_slash")
535n/a
536n/a # Regression test for http://bugs.python.org/issue3677.
537n/a @unittest.skipUnless(sys.platform == 'win32', 'Windows-specific')
538n/a def test_UNC_path(self):
539n/a with open(os.path.join(self.path, 'test_unc_path.py'), 'w') as f:
540n/a f.write("testdata = 'test_unc_path'")
541n/a importlib.invalidate_caches()
542n/a # Create the UNC path, like \\myhost\c$\foo\bar.
543n/a path = os.path.abspath(self.path)
544n/a import socket
545n/a hn = socket.gethostname()
546n/a drive = path[0]
547n/a unc = "\\\\%s\\%s$"%(hn, drive)
548n/a unc += path[2:]
549n/a try:
550n/a os.listdir(unc)
551n/a except OSError as e:
552n/a if e.errno in (errno.EPERM, errno.EACCES):
553n/a # See issue #15338
554n/a self.skipTest("cannot access administrative share %r" % (unc,))
555n/a raise
556n/a sys.path.insert(0, unc)
557n/a try:
558n/a mod = __import__("test_unc_path")
559n/a except ImportError as e:
560n/a self.fail("could not import 'test_unc_path' from %r: %r"
561n/a % (unc, e))
562n/a self.assertEqual(mod.testdata, 'test_unc_path')
563n/a self.assertTrue(mod.__file__.startswith(unc), mod.__file__)
564n/a unload("test_unc_path")
565n/a
566n/a
567n/aclass RelativeImportTests(unittest.TestCase):
568n/a
569n/a def tearDown(self):
570n/a unload("test.relimport")
571n/a setUp = tearDown
572n/a
573n/a def test_relimport_star(self):
574n/a # This will import * from .test_import.
575n/a from . import relimport
576n/a self.assertTrue(hasattr(relimport, "RelativeImportTests"))
577n/a
578n/a def test_issue3221(self):
579n/a # Note for mergers: the 'absolute' tests from the 2.x branch
580n/a # are missing in Py3k because implicit relative imports are
581n/a # a thing of the past
582n/a #
583n/a # Regression test for http://bugs.python.org/issue3221.
584n/a def check_relative():
585n/a exec("from . import relimport", ns)
586n/a
587n/a # Check relative import OK with __package__ and __name__ correct
588n/a ns = dict(__package__='test', __name__='test.notarealmodule')
589n/a check_relative()
590n/a
591n/a # Check relative import OK with only __name__ wrong
592n/a ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')
593n/a check_relative()
594n/a
595n/a # Check relative import fails with only __package__ wrong
596n/a ns = dict(__package__='foo', __name__='test.notarealmodule')
597n/a self.assertRaises(SystemError, check_relative)
598n/a
599n/a # Check relative import fails with __package__ and __name__ wrong
600n/a ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
601n/a self.assertRaises(SystemError, check_relative)
602n/a
603n/a # Check relative import fails with package set to a non-string
604n/a ns = dict(__package__=object())
605n/a self.assertRaises(TypeError, check_relative)
606n/a
607n/a def test_absolute_import_without_future(self):
608n/a # If explicit relative import syntax is used, then do not try
609n/a # to perform an absolute import in the face of failure.
610n/a # Issue #7902.
611n/a with self.assertRaises(ImportError):
612n/a from .os import sep
613n/a self.fail("explicit relative import triggered an "
614n/a "implicit absolute import")
615n/a
616n/a
617n/aclass OverridingImportBuiltinTests(unittest.TestCase):
618n/a def test_override_builtin(self):
619n/a # Test that overriding builtins.__import__ can bypass sys.modules.
620n/a import os
621n/a
622n/a def foo():
623n/a import os
624n/a return os
625n/a self.assertEqual(foo(), os) # Quick sanity check.
626n/a
627n/a with swap_attr(builtins, "__import__", lambda *x: 5):
628n/a self.assertEqual(foo(), 5)
629n/a
630n/a # Test what happens when we shadow __import__ in globals(); this
631n/a # currently does not impact the import process, but if this changes,
632n/a # other code will need to change, so keep this test as a tripwire.
633n/a with swap_item(globals(), "__import__", lambda *x: 5):
634n/a self.assertEqual(foo(), os)
635n/a
636n/a
637n/aclass PycacheTests(unittest.TestCase):
638n/a # Test the various PEP 3147 related behaviors.
639n/a
640n/a tag = sys.implementation.cache_tag
641n/a
642n/a def _clean(self):
643n/a forget(TESTFN)
644n/a rmtree('__pycache__')
645n/a unlink(self.source)
646n/a
647n/a def setUp(self):
648n/a self.source = TESTFN + '.py'
649n/a self._clean()
650n/a with open(self.source, 'w') as fp:
651n/a print('# This is a test file written by test_import.py', file=fp)
652n/a sys.path.insert(0, os.curdir)
653n/a importlib.invalidate_caches()
654n/a
655n/a def tearDown(self):
656n/a assert sys.path[0] == os.curdir, 'Unexpected sys.path[0]'
657n/a del sys.path[0]
658n/a self._clean()
659n/a
660n/a @skip_if_dont_write_bytecode
661n/a def test_import_pyc_path(self):
662n/a self.assertFalse(os.path.exists('__pycache__'))
663n/a __import__(TESTFN)
664n/a self.assertTrue(os.path.exists('__pycache__'))
665n/a self.assertTrue(os.path.exists(os.path.join(
666n/a '__pycache__', '{}.{}.py{}'.format(
667n/a TESTFN, self.tag, 'c' if __debug__ else 'o'))))
668n/a
669n/a @unittest.skipUnless(os.name == 'posix',
670n/a "test meaningful only on posix systems")
671n/a @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
672n/a "due to varying filesystem permission semantics (issue #11956)")
673n/a @skip_if_dont_write_bytecode
674n/a def test_unwritable_directory(self):
675n/a # When the umask causes the new __pycache__ directory to be
676n/a # unwritable, the import still succeeds but no .pyc file is written.
677n/a with temp_umask(0o222):
678n/a __import__(TESTFN)
679n/a self.assertTrue(os.path.exists('__pycache__'))
680n/a self.assertFalse(os.path.exists(os.path.join(
681n/a '__pycache__', '{}.{}.pyc'.format(TESTFN, self.tag))))
682n/a
683n/a @skip_if_dont_write_bytecode
684n/a def test_missing_source(self):
685n/a # With PEP 3147 cache layout, removing the source but leaving the pyc
686n/a # file does not satisfy the import.
687n/a __import__(TESTFN)
688n/a pyc_file = importlib.util.cache_from_source(self.source)
689n/a self.assertTrue(os.path.exists(pyc_file))
690n/a os.remove(self.source)
691n/a forget(TESTFN)
692n/a self.assertRaises(ImportError, __import__, TESTFN)
693n/a
694n/a @skip_if_dont_write_bytecode
695n/a def test_missing_source_legacy(self):
696n/a # Like test_missing_source() except that for backward compatibility,
697n/a # when the pyc file lives where the py file would have been (and named
698n/a # without the tag), it is importable. The __file__ of the imported
699n/a # module is the pyc location.
700n/a __import__(TESTFN)
701n/a # pyc_file gets removed in _clean() via tearDown().
702n/a pyc_file = make_legacy_pyc(self.source)
703n/a os.remove(self.source)
704n/a unload(TESTFN)
705n/a importlib.invalidate_caches()
706n/a m = __import__(TESTFN)
707n/a self.assertEqual(m.__file__,
708n/a os.path.join(os.curdir, os.path.relpath(pyc_file)))
709n/a
710n/a def test___cached__(self):
711n/a # Modules now also have an __cached__ that points to the pyc file.
712n/a m = __import__(TESTFN)
713n/a pyc_file = importlib.util.cache_from_source(TESTFN + '.py')
714n/a self.assertEqual(m.__cached__, os.path.join(os.curdir, pyc_file))
715n/a
716n/a @skip_if_dont_write_bytecode
717n/a def test___cached___legacy_pyc(self):
718n/a # Like test___cached__() except that for backward compatibility,
719n/a # when the pyc file lives where the py file would have been (and named
720n/a # without the tag), it is importable. The __cached__ of the imported
721n/a # module is the pyc location.
722n/a __import__(TESTFN)
723n/a # pyc_file gets removed in _clean() via tearDown().
724n/a pyc_file = make_legacy_pyc(self.source)
725n/a os.remove(self.source)
726n/a unload(TESTFN)
727n/a importlib.invalidate_caches()
728n/a m = __import__(TESTFN)
729n/a self.assertEqual(m.__cached__,
730n/a os.path.join(os.curdir, os.path.relpath(pyc_file)))
731n/a
732n/a @skip_if_dont_write_bytecode
733n/a def test_package___cached__(self):
734n/a # Like test___cached__ but for packages.
735n/a def cleanup():
736n/a rmtree('pep3147')
737n/a unload('pep3147.foo')
738n/a unload('pep3147')
739n/a os.mkdir('pep3147')
740n/a self.addCleanup(cleanup)
741n/a # Touch the __init__.py
742n/a with open(os.path.join('pep3147', '__init__.py'), 'w'):
743n/a pass
744n/a with open(os.path.join('pep3147', 'foo.py'), 'w'):
745n/a pass
746n/a importlib.invalidate_caches()
747n/a m = __import__('pep3147.foo')
748n/a init_pyc = importlib.util.cache_from_source(
749n/a os.path.join('pep3147', '__init__.py'))
750n/a self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
751n/a foo_pyc = importlib.util.cache_from_source(os.path.join('pep3147', 'foo.py'))
752n/a self.assertEqual(sys.modules['pep3147.foo'].__cached__,
753n/a os.path.join(os.curdir, foo_pyc))
754n/a
755n/a def test_package___cached___from_pyc(self):
756n/a # Like test___cached__ but ensuring __cached__ when imported from a
757n/a # PEP 3147 pyc file.
758n/a def cleanup():
759n/a rmtree('pep3147')
760n/a unload('pep3147.foo')
761n/a unload('pep3147')
762n/a os.mkdir('pep3147')
763n/a self.addCleanup(cleanup)
764n/a # Touch the __init__.py
765n/a with open(os.path.join('pep3147', '__init__.py'), 'w'):
766n/a pass
767n/a with open(os.path.join('pep3147', 'foo.py'), 'w'):
768n/a pass
769n/a importlib.invalidate_caches()
770n/a m = __import__('pep3147.foo')
771n/a unload('pep3147.foo')
772n/a unload('pep3147')
773n/a importlib.invalidate_caches()
774n/a m = __import__('pep3147.foo')
775n/a init_pyc = importlib.util.cache_from_source(
776n/a os.path.join('pep3147', '__init__.py'))
777n/a self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
778n/a foo_pyc = importlib.util.cache_from_source(os.path.join('pep3147', 'foo.py'))
779n/a self.assertEqual(sys.modules['pep3147.foo'].__cached__,
780n/a os.path.join(os.curdir, foo_pyc))
781n/a
782n/a def test_recompute_pyc_same_second(self):
783n/a # Even when the source file doesn't change timestamp, a change in
784n/a # source size is enough to trigger recomputation of the pyc file.
785n/a __import__(TESTFN)
786n/a unload(TESTFN)
787n/a with open(self.source, 'a') as fp:
788n/a print("x = 5", file=fp)
789n/a m = __import__(TESTFN)
790n/a self.assertEqual(m.x, 5)
791n/a
792n/a
793n/aclass TestSymbolicallyLinkedPackage(unittest.TestCase):
794n/a package_name = 'sample'
795n/a tagged = package_name + '-tagged'
796n/a
797n/a def setUp(self):
798n/a test.support.rmtree(self.tagged)
799n/a test.support.rmtree(self.package_name)
800n/a self.orig_sys_path = sys.path[:]
801n/a
802n/a # create a sample package; imagine you have a package with a tag and
803n/a # you want to symbolically link it from its untagged name.
804n/a os.mkdir(self.tagged)
805n/a self.addCleanup(test.support.rmtree, self.tagged)
806n/a init_file = os.path.join(self.tagged, '__init__.py')
807n/a test.support.create_empty_file(init_file)
808n/a assert os.path.exists(init_file)
809n/a
810n/a # now create a symlink to the tagged package
811n/a # sample -> sample-tagged
812n/a os.symlink(self.tagged, self.package_name, target_is_directory=True)
813n/a self.addCleanup(test.support.unlink, self.package_name)
814n/a importlib.invalidate_caches()
815n/a
816n/a self.assertEqual(os.path.isdir(self.package_name), True)
817n/a
818n/a assert os.path.isfile(os.path.join(self.package_name, '__init__.py'))
819n/a
820n/a def tearDown(self):
821n/a sys.path[:] = self.orig_sys_path
822n/a
823n/a # regression test for issue6727
824n/a @unittest.skipUnless(
825n/a not hasattr(sys, 'getwindowsversion')
826n/a or sys.getwindowsversion() >= (6, 0),
827n/a "Windows Vista or later required")
828n/a @test.support.skip_unless_symlink
829n/a def test_symlinked_dir_importable(self):
830n/a # make sure sample can only be imported from the current directory.
831n/a sys.path[:] = ['.']
832n/a assert os.path.exists(self.package_name)
833n/a assert os.path.exists(os.path.join(self.package_name, '__init__.py'))
834n/a
835n/a # Try to import the package
836n/a importlib.import_module(self.package_name)
837n/a
838n/a
839n/a@cpython_only
840n/aclass ImportlibBootstrapTests(unittest.TestCase):
841n/a # These tests check that importlib is bootstrapped.
842n/a
843n/a def test_frozen_importlib(self):
844n/a mod = sys.modules['_frozen_importlib']
845n/a self.assertTrue(mod)
846n/a
847n/a def test_frozen_importlib_is_bootstrap(self):
848n/a from importlib import _bootstrap
849n/a mod = sys.modules['_frozen_importlib']
850n/a self.assertIs(mod, _bootstrap)
851n/a self.assertEqual(mod.__name__, 'importlib._bootstrap')
852n/a self.assertEqual(mod.__package__, 'importlib')
853n/a self.assertTrue(mod.__file__.endswith('_bootstrap.py'), mod.__file__)
854n/a
855n/a def test_there_can_be_only_one(self):
856n/a # Issue #15386 revealed a tricky loophole in the bootstrapping
857n/a # This test is technically redundant, since the bug caused importing
858n/a # this test module to crash completely, but it helps prove the point
859n/a from importlib import machinery
860n/a mod = sys.modules['_frozen_importlib']
861n/a self.assertIs(machinery.FileFinder, mod.FileFinder)
862n/a
863n/a
864n/a@cpython_only
865n/aclass GetSourcefileTests(unittest.TestCase):
866n/a
867n/a """Test importlib._bootstrap._get_sourcefile() as used by the C API.
868n/a
869n/a Because of the peculiarities of the need of this function, the tests are
870n/a knowingly whitebox tests.
871n/a
872n/a """
873n/a
874n/a def test_get_sourcefile(self):
875n/a # Given a valid bytecode path, return the path to the corresponding
876n/a # source file if it exists.
877n/a with mock.patch('importlib._bootstrap._path_isfile') as _path_isfile:
878n/a _path_isfile.return_value = True;
879n/a path = TESTFN + '.pyc'
880n/a expect = TESTFN + '.py'
881n/a self.assertEqual(_get_sourcefile(path), expect)
882n/a
883n/a def test_get_sourcefile_no_source(self):
884n/a # Given a valid bytecode path without a corresponding source path,
885n/a # return the original bytecode path.
886n/a with mock.patch('importlib._bootstrap._path_isfile') as _path_isfile:
887n/a _path_isfile.return_value = False;
888n/a path = TESTFN + '.pyc'
889n/a self.assertEqual(_get_sourcefile(path), path)
890n/a
891n/a def test_get_sourcefile_bad_ext(self):
892n/a # Given a path with an invalid bytecode extension, return the
893n/a # bytecode path passed as the argument.
894n/a path = TESTFN + '.bad_ext'
895n/a self.assertEqual(_get_sourcefile(path), path)
896n/a
897n/a
898n/aclass ImportTracebackTests(unittest.TestCase):
899n/a
900n/a def setUp(self):
901n/a os.mkdir(TESTFN)
902n/a self.old_path = sys.path[:]
903n/a sys.path.insert(0, TESTFN)
904n/a
905n/a def tearDown(self):
906n/a sys.path[:] = self.old_path
907n/a rmtree(TESTFN)
908n/a
909n/a def create_module(self, mod, contents, ext=".py"):
910n/a fname = os.path.join(TESTFN, mod + ext)
911n/a with open(fname, "w") as f:
912n/a f.write(contents)
913n/a self.addCleanup(unload, mod)
914n/a importlib.invalidate_caches()
915n/a return fname
916n/a
917n/a def assert_traceback(self, tb, files):
918n/a deduped_files = []
919n/a while tb:
920n/a code = tb.tb_frame.f_code
921n/a fn = code.co_filename
922n/a if not deduped_files or fn != deduped_files[-1]:
923n/a deduped_files.append(fn)
924n/a tb = tb.tb_next
925n/a self.assertEqual(len(deduped_files), len(files), deduped_files)
926n/a for fn, pat in zip(deduped_files, files):
927n/a self.assertIn(pat, fn)
928n/a
929n/a def test_nonexistent_module(self):
930n/a try:
931n/a # assertRaises() clears __traceback__
932n/a import nonexistent_xyzzy
933n/a except ImportError as e:
934n/a tb = e.__traceback__
935n/a else:
936n/a self.fail("ImportError should have been raised")
937n/a self.assert_traceback(tb, [__file__])
938n/a
939n/a def test_nonexistent_module_nested(self):
940n/a self.create_module("foo", "import nonexistent_xyzzy")
941n/a try:
942n/a import foo
943n/a except ImportError as e:
944n/a tb = e.__traceback__
945n/a else:
946n/a self.fail("ImportError should have been raised")
947n/a self.assert_traceback(tb, [__file__, 'foo.py'])
948n/a
949n/a def test_exec_failure(self):
950n/a self.create_module("foo", "1/0")
951n/a try:
952n/a import foo
953n/a except ZeroDivisionError as e:
954n/a tb = e.__traceback__
955n/a else:
956n/a self.fail("ZeroDivisionError should have been raised")
957n/a self.assert_traceback(tb, [__file__, 'foo.py'])
958n/a
959n/a def test_exec_failure_nested(self):
960n/a self.create_module("foo", "import bar")
961n/a self.create_module("bar", "1/0")
962n/a try:
963n/a import foo
964n/a except ZeroDivisionError as e:
965n/a tb = e.__traceback__
966n/a else:
967n/a self.fail("ZeroDivisionError should have been raised")
968n/a self.assert_traceback(tb, [__file__, 'foo.py', 'bar.py'])
969n/a
970n/a # A few more examples from issue #15425
971n/a def test_syntax_error(self):
972n/a self.create_module("foo", "invalid syntax is invalid")
973n/a try:
974n/a import foo
975n/a except SyntaxError as e:
976n/a tb = e.__traceback__
977n/a else:
978n/a self.fail("SyntaxError should have been raised")
979n/a self.assert_traceback(tb, [__file__])
980n/a
981n/a def _setup_broken_package(self, parent, child):
982n/a pkg_name = "_parent_foo"
983n/a self.addCleanup(unload, pkg_name)
984n/a pkg_path = os.path.join(TESTFN, pkg_name)
985n/a os.mkdir(pkg_path)
986n/a # Touch the __init__.py
987n/a init_path = os.path.join(pkg_path, '__init__.py')
988n/a with open(init_path, 'w') as f:
989n/a f.write(parent)
990n/a bar_path = os.path.join(pkg_path, 'bar.py')
991n/a with open(bar_path, 'w') as f:
992n/a f.write(child)
993n/a importlib.invalidate_caches()
994n/a return init_path, bar_path
995n/a
996n/a def test_broken_submodule(self):
997n/a init_path, bar_path = self._setup_broken_package("", "1/0")
998n/a try:
999n/a import _parent_foo.bar
1000n/a except ZeroDivisionError as e:
1001n/a tb = e.__traceback__
1002n/a else:
1003n/a self.fail("ZeroDivisionError should have been raised")
1004n/a self.assert_traceback(tb, [__file__, bar_path])
1005n/a
1006n/a def test_broken_from(self):
1007n/a init_path, bar_path = self._setup_broken_package("", "1/0")
1008n/a try:
1009n/a from _parent_foo import bar
1010n/a except ZeroDivisionError as e:
1011n/a tb = e.__traceback__
1012n/a else:
1013n/a self.fail("ImportError should have been raised")
1014n/a self.assert_traceback(tb, [__file__, bar_path])
1015n/a
1016n/a def test_broken_parent(self):
1017n/a init_path, bar_path = self._setup_broken_package("1/0", "")
1018n/a try:
1019n/a import _parent_foo.bar
1020n/a except ZeroDivisionError as e:
1021n/a tb = e.__traceback__
1022n/a else:
1023n/a self.fail("ZeroDivisionError should have been raised")
1024n/a self.assert_traceback(tb, [__file__, init_path])
1025n/a
1026n/a def test_broken_parent_from(self):
1027n/a init_path, bar_path = self._setup_broken_package("1/0", "")
1028n/a try:
1029n/a from _parent_foo import bar
1030n/a except ZeroDivisionError as e:
1031n/a tb = e.__traceback__
1032n/a else:
1033n/a self.fail("ZeroDivisionError should have been raised")
1034n/a self.assert_traceback(tb, [__file__, init_path])
1035n/a
1036n/a @cpython_only
1037n/a def test_import_bug(self):
1038n/a # We simulate a bug in importlib and check that it's not stripped
1039n/a # away from the traceback.
1040n/a self.create_module("foo", "")
1041n/a importlib = sys.modules['_frozen_importlib']
1042n/a old_load_module = importlib.SourceLoader.load_module
1043n/a try:
1044n/a def load_module(*args):
1045n/a 1/0
1046n/a importlib.SourceLoader.load_module = load_module
1047n/a try:
1048n/a import foo
1049n/a except ZeroDivisionError as e:
1050n/a tb = e.__traceback__
1051n/a else:
1052n/a self.fail("ZeroDivisionError should have been raised")
1053n/a self.assert_traceback(tb, [__file__, '<frozen importlib', __file__])
1054n/a finally:
1055n/a importlib.SourceLoader.load_module = old_load_module
1056n/a
1057n/a
1058n/aif __name__ == '__main__':
1059n/a # Test needs to be a package, so we can do relative imports.
1060n/a unittest.main()