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

Python code coverage for Lib/test/test_pkgimport.py

#countcontent
1n/aimport os
2n/aimport sys
3n/aimport shutil
4n/aimport string
5n/aimport random
6n/aimport tempfile
7n/aimport unittest
8n/a
9n/afrom importlib.util import cache_from_source
10n/afrom test.support import create_empty_file
11n/a
12n/aclass TestImport(unittest.TestCase):
13n/a
14n/a def __init__(self, *args, **kw):
15n/a self.package_name = 'PACKAGE_'
16n/a while self.package_name in sys.modules:
17n/a self.package_name += random.choose(string.ascii_letters)
18n/a self.module_name = self.package_name + '.foo'
19n/a unittest.TestCase.__init__(self, *args, **kw)
20n/a
21n/a def remove_modules(self):
22n/a for module_name in (self.package_name, self.module_name):
23n/a if module_name in sys.modules:
24n/a del sys.modules[module_name]
25n/a
26n/a def setUp(self):
27n/a self.test_dir = tempfile.mkdtemp()
28n/a sys.path.append(self.test_dir)
29n/a self.package_dir = os.path.join(self.test_dir,
30n/a self.package_name)
31n/a os.mkdir(self.package_dir)
32n/a create_empty_file(os.path.join(self.package_dir, '__init__.py'))
33n/a self.module_path = os.path.join(self.package_dir, 'foo.py')
34n/a
35n/a def tearDown(self):
36n/a shutil.rmtree(self.test_dir)
37n/a self.assertNotEqual(sys.path.count(self.test_dir), 0)
38n/a sys.path.remove(self.test_dir)
39n/a self.remove_modules()
40n/a
41n/a def rewrite_file(self, contents):
42n/a compiled_path = cache_from_source(self.module_path)
43n/a if os.path.exists(compiled_path):
44n/a os.remove(compiled_path)
45n/a with open(self.module_path, 'w') as f:
46n/a f.write(contents)
47n/a
48n/a def test_package_import__semantics(self):
49n/a
50n/a # Generate a couple of broken modules to try importing.
51n/a
52n/a # ...try loading the module when there's a SyntaxError
53n/a self.rewrite_file('for')
54n/a try: __import__(self.module_name)
55n/a except SyntaxError: pass
56n/a else: raise RuntimeError('Failed to induce SyntaxError') # self.fail()?
57n/a self.assertNotIn(self.module_name, sys.modules)
58n/a self.assertFalse(hasattr(sys.modules[self.package_name], 'foo'))
59n/a
60n/a # ...make up a variable name that isn't bound in __builtins__
61n/a var = 'a'
62n/a while var in dir(__builtins__):
63n/a var += random.choose(string.ascii_letters)
64n/a
65n/a # ...make a module that just contains that
66n/a self.rewrite_file(var)
67n/a
68n/a try: __import__(self.module_name)
69n/a except NameError: pass
70n/a else: raise RuntimeError('Failed to induce NameError.')
71n/a
72n/a # ...now change the module so that the NameError doesn't
73n/a # happen
74n/a self.rewrite_file('%s = 1' % var)
75n/a module = __import__(self.module_name).foo
76n/a self.assertEqual(getattr(module, var), 1)
77n/a
78n/a
79n/aif __name__ == "__main__":
80n/a unittest.main()