blob: ee9ee1ad8c3bcc1237ac1339679e4cd1d8645cb4 [file] [log] [blame]
Brett Cannon14268532013-05-03 10:56:19 -04001try:
2 import _thread
3except ImportError:
4 _thread = None
Brett Cannonc0499522012-05-11 14:48:41 -04005import importlib
Nick Coghlan9d3c61c2015-09-05 21:05:05 +10006import importlib.util
Guido van Rossum0ad59d42009-03-30 22:01:35 +00007import os
8import os.path
Barry Warsaw28a691b2010-04-17 00:19:56 +00009import shutil
Brett Cannon8a9583e2008-09-04 05:04:25 +000010import sys
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011from test import support
Brett Cannonc0499522012-05-11 14:48:41 -040012import unittest
13import warnings
Brett Cannone4f41de2013-06-16 13:13:40 -040014with warnings.catch_warnings():
15 warnings.simplefilter('ignore', PendingDeprecationWarning)
16 import imp
Neal Norwitz2294c0d2003-02-12 23:02:21 +000017
Brett Cannon130e4812013-05-03 10:54:23 -040018
19def requires_load_dynamic(meth):
20 """Decorator to skip a test if not running under CPython or lacking
21 imp.load_dynamic()."""
22 meth = support.cpython_only(meth)
23 return unittest.skipIf(not hasattr(imp, 'load_dynamic'),
24 'imp.load_dynamic() required')(meth)
25
26
Brett Cannon14268532013-05-03 10:56:19 -040027@unittest.skipIf(_thread is None, '_thread module is required')
Thomas Wouters89f507f2006-12-13 04:49:30 +000028class LockTests(unittest.TestCase):
Tim Peters579bed72003-04-26 14:31:24 +000029
Thomas Wouters89f507f2006-12-13 04:49:30 +000030 """Very basic test of import lock functions."""
Tim Peters579bed72003-04-26 14:31:24 +000031
Thomas Wouters89f507f2006-12-13 04:49:30 +000032 def verify_lock_state(self, expected):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000033 self.assertEqual(imp.lock_held(), expected,
Thomas Wouters89f507f2006-12-13 04:49:30 +000034 "expected imp.lock_held() to be %r" % expected)
35 def testLock(self):
36 LOOPS = 50
Tim Peters579bed72003-04-26 14:31:24 +000037
Thomas Wouters89f507f2006-12-13 04:49:30 +000038 # The import lock may already be held, e.g. if the test suite is run
39 # via "import test.autotest".
40 lock_held_at_start = imp.lock_held()
41 self.verify_lock_state(lock_held_at_start)
Tim Peters579bed72003-04-26 14:31:24 +000042
Thomas Wouters89f507f2006-12-13 04:49:30 +000043 for i in range(LOOPS):
44 imp.acquire_lock()
45 self.verify_lock_state(True)
Tim Peters579bed72003-04-26 14:31:24 +000046
Thomas Wouters89f507f2006-12-13 04:49:30 +000047 for i in range(LOOPS):
Neal Norwitz2294c0d2003-02-12 23:02:21 +000048 imp.release_lock()
Thomas Wouters89f507f2006-12-13 04:49:30 +000049
50 # The original state should be restored now.
51 self.verify_lock_state(lock_held_at_start)
52
53 if not lock_held_at_start:
54 try:
55 imp.release_lock()
56 except RuntimeError:
57 pass
58 else:
59 self.fail("release_lock() without lock should raise "
60 "RuntimeError")
Neal Norwitz2294c0d2003-02-12 23:02:21 +000061
Guido van Rossumce3a72a2007-10-19 23:16:50 +000062class ImportTests(unittest.TestCase):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000063 def setUp(self):
64 mod = importlib.import_module('test.encoded_modules')
65 self.test_strings = mod.test_strings
66 self.test_path = mod.__path__
67
68 def test_import_encoded_module(self):
69 for modname, encoding, teststr in self.test_strings:
70 mod = importlib.import_module('test.encoded_modules.'
71 'module_' + modname)
72 self.assertEqual(teststr, mod.test)
Guido van Rossumce3a72a2007-10-19 23:16:50 +000073
74 def test_find_module_encoding(self):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000075 for mod, encoding, _ in self.test_strings:
Brett Cannon749afa92010-10-29 23:47:23 +000076 with imp.find_module('module_' + mod, self.test_path)[0] as fd:
77 self.assertEqual(fd.encoding, encoding)
Guido van Rossumce3a72a2007-10-19 23:16:50 +000078
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020079 path = [os.path.dirname(__file__)]
Brett Cannondd9a5692012-04-20 12:59:59 -040080 with self.assertRaises(SyntaxError):
81 imp.find_module('badsyntax_pep3120', path)
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020082
Guido van Rossum40d20bc2007-10-22 00:09:51 +000083 def test_issue1267(self):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000084 for mod, encoding, _ in self.test_strings:
85 fp, filename, info = imp.find_module('module_' + mod,
86 self.test_path)
Brett Cannon749afa92010-10-29 23:47:23 +000087 with fp:
88 self.assertNotEqual(fp, None)
89 self.assertEqual(fp.encoding, encoding)
90 self.assertEqual(fp.tell(), 0)
91 self.assertEqual(fp.readline(), '# test %s encoding\n'
92 % encoding)
Guido van Rossum40d20bc2007-10-22 00:09:51 +000093
94 fp, filename, info = imp.find_module("tokenize")
Brett Cannon749afa92010-10-29 23:47:23 +000095 with fp:
96 self.assertNotEqual(fp, None)
97 self.assertEqual(fp.encoding, "utf-8")
98 self.assertEqual(fp.tell(), 0)
99 self.assertEqual(fp.readline(),
100 '"""Tokenization help for Python programs.\n')
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000101
Brett Cannon8a9583e2008-09-04 05:04:25 +0000102 def test_issue3594(self):
103 temp_mod_name = 'test_imp_helper'
104 sys.path.insert(0, '.')
105 try:
106 with open(temp_mod_name + '.py', 'w') as file:
107 file.write("# coding: cp1252\nu = 'test.test_imp'\n")
108 file, filename, info = imp.find_module(temp_mod_name)
109 file.close()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000110 self.assertEqual(file.encoding, 'cp1252')
Brett Cannon8a9583e2008-09-04 05:04:25 +0000111 finally:
112 del sys.path[0]
113 support.unlink(temp_mod_name + '.py')
114 support.unlink(temp_mod_name + '.pyc')
Brett Cannon8a9583e2008-09-04 05:04:25 +0000115
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000116 def test_issue5604(self):
117 # Test cannot cover imp.load_compiled function.
118 # Martin von Loewis note what shared library cannot have non-ascii
119 # character because init_xxx function cannot be compiled
120 # and issue never happens for dynamic modules.
121 # But sources modified to follow generic way for processing pathes.
122
Ezio Melotti435b5312010-03-06 01:20:49 +0000123 # the return encoding could be uppercase or None
124 fs_encoding = sys.getfilesystemencoding()
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000125
126 # covers utf-8 and Windows ANSI code pages
127 # one non-space symbol from every page
128 # (http://en.wikipedia.org/wiki/Code_page)
129 known_locales = {
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000130 'utf-8' : b'\xc3\xa4',
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000131 'cp1250' : b'\x8C',
132 'cp1251' : b'\xc0',
133 'cp1252' : b'\xc0',
134 'cp1253' : b'\xc1',
135 'cp1254' : b'\xc0',
136 'cp1255' : b'\xe0',
137 'cp1256' : b'\xe0',
138 'cp1257' : b'\xc0',
139 'cp1258' : b'\xc0',
140 }
141
Florent Xicluna21164ce2010-03-20 20:30:53 +0000142 if sys.platform == 'darwin':
143 self.assertEqual(fs_encoding, 'utf-8')
144 # Mac OS X uses the Normal Form D decomposition
145 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
146 special_char = b'a\xcc\x88'
147 else:
148 special_char = known_locales.get(fs_encoding)
149
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000150 if not special_char:
Ezio Melotti76e0d1a2010-03-05 15:08:19 +0000151 self.skipTest("can't run this test with %s as filesystem encoding"
152 % fs_encoding)
153 decoded_char = special_char.decode(fs_encoding)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000154 temp_mod_name = 'test_imp_helper_' + decoded_char
155 test_package_name = 'test_imp_helper_package_' + decoded_char
156 init_file_name = os.path.join(test_package_name, '__init__.py')
157 try:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000158 # if the curdir is not in sys.path the test fails when run with
159 # ./python ./Lib/test/regrtest.py test_imp
160 sys.path.insert(0, os.curdir)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000161 with open(temp_mod_name + '.py', 'w') as file:
162 file.write('a = 1\n')
163 file, filename, info = imp.find_module(temp_mod_name)
Brett Cannon749afa92010-10-29 23:47:23 +0000164 with file:
165 self.assertIsNotNone(file)
166 self.assertTrue(filename[:-3].endswith(temp_mod_name))
167 self.assertEqual(info[0], '.py')
Serhiy Storchaka6787a382013-11-23 22:12:06 +0200168 self.assertEqual(info[1], 'r')
Brett Cannon749afa92010-10-29 23:47:23 +0000169 self.assertEqual(info[2], imp.PY_SOURCE)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000170
Brett Cannon749afa92010-10-29 23:47:23 +0000171 mod = imp.load_module(temp_mod_name, file, filename, info)
172 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000173
Brett Cannonc0499522012-05-11 14:48:41 -0400174 with warnings.catch_warnings():
175 warnings.simplefilter('ignore')
176 mod = imp.load_source(temp_mod_name, temp_mod_name + '.py')
Ezio Melotti435b5312010-03-06 01:20:49 +0000177 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000178
Brett Cannonc0499522012-05-11 14:48:41 -0400179 with warnings.catch_warnings():
180 warnings.simplefilter('ignore')
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200181 if not sys.dont_write_bytecode:
182 mod = imp.load_compiled(
183 temp_mod_name,
184 imp.cache_from_source(temp_mod_name + '.py'))
Ezio Melotti435b5312010-03-06 01:20:49 +0000185 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000186
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000187 if not os.path.exists(test_package_name):
188 os.mkdir(test_package_name)
189 with open(init_file_name, 'w') as file:
190 file.write('b = 2\n')
Brett Cannonc0499522012-05-11 14:48:41 -0400191 with warnings.catch_warnings():
192 warnings.simplefilter('ignore')
193 package = imp.load_package(test_package_name, test_package_name)
Ezio Melotti435b5312010-03-06 01:20:49 +0000194 self.assertEqual(package.b, 2)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000195 finally:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000196 del sys.path[0]
Brett Cannonf299abd2015-04-13 14:21:02 -0400197 for ext in ('.py', '.pyc'):
Ezio Melotti435b5312010-03-06 01:20:49 +0000198 support.unlink(temp_mod_name + ext)
199 support.unlink(init_file_name + ext)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000200 support.rmtree(test_package_name)
Victor Stinner047b7ae2014-10-05 17:37:41 +0200201 support.rmtree('__pycache__')
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000202
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200203 def test_issue9319(self):
Antoine Pitrou11846902011-04-25 21:39:49 +0200204 path = os.path.dirname(__file__)
Victor Stinner7fdd0fe2011-04-23 01:24:11 +0200205 self.assertRaises(SyntaxError,
Antoine Pitrou11846902011-04-25 21:39:49 +0200206 imp.find_module, "badsyntax_pep3120", [path])
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200207
Nick Coghlan91b9f132012-09-01 00:13:45 +1000208 def test_load_from_source(self):
209 # Verify that the imp module can correctly load and find .py files
210 # XXX (ncoghlan): It would be nice to use support.CleanImport
211 # here, but that breaks because the os module registers some
212 # handlers in copy_reg on import. Since CleanImport doesn't
213 # revert that registration, the module is left in a broken
214 # state after reversion. Reinitialising the module contents
215 # and just reverting os.environ to its previous state is an OK
216 # workaround
217 orig_path = os.path
218 orig_getenv = os.getenv
219 with support.EnvironmentVarGuard():
220 x = imp.find_module("os")
221 self.addCleanup(x[0].close)
222 new_os = imp.load_module("os", *x)
223 self.assertIs(os, new_os)
224 self.assertIs(orig_path, new_os.path)
225 self.assertIsNot(orig_getenv, new_os.getenv)
226
Brett Cannon130e4812013-05-03 10:54:23 -0400227 @requires_load_dynamic
Nick Coghlan91b9f132012-09-01 00:13:45 +1000228 def test_issue15828_load_extensions(self):
229 # Issue 15828 picked up that the adapter between the old imp API
230 # and importlib couldn't handle C extensions
231 example = "_heapq"
232 x = imp.find_module(example)
Brett Cannon848cdfd2012-08-31 11:31:20 -0400233 file_ = x[0]
234 if file_ is not None:
235 self.addCleanup(file_.close)
Nick Coghlan91b9f132012-09-01 00:13:45 +1000236 mod = imp.load_module(example, *x)
237 self.assertEqual(mod.__name__, example)
238
Brett Cannon130e4812013-05-03 10:54:23 -0400239 @requires_load_dynamic
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200240 def test_issue16421_multiple_modules_in_one_dll(self):
241 # Issue 16421: loading several modules from the same compiled file fails
242 m = '_testimportmultiple'
243 fileobj, pathname, description = imp.find_module(m)
244 fileobj.close()
245 mod0 = imp.load_dynamic(m, pathname)
Andrew Svetlovef9a43b2012-12-15 17:22:59 +0200246 mod1 = imp.load_dynamic('_testimportmultiple_foo', pathname)
247 mod2 = imp.load_dynamic('_testimportmultiple_bar', pathname)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200248 self.assertEqual(mod0.__name__, m)
Andrew Svetlovef9a43b2012-12-15 17:22:59 +0200249 self.assertEqual(mod1.__name__, '_testimportmultiple_foo')
250 self.assertEqual(mod2.__name__, '_testimportmultiple_bar')
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200251 with self.assertRaises(ImportError):
252 imp.load_dynamic('nonexistent', pathname)
253
Brett Cannon130e4812013-05-03 10:54:23 -0400254 @requires_load_dynamic
Brett Cannonf0434e62012-04-20 15:22:50 -0400255 def test_load_dynamic_ImportError_path(self):
256 # Issue #1559549 added `name` and `path` attributes to ImportError
257 # in order to provide better detail. Issue #10854 implemented those
258 # attributes on import failures of extensions on Windows.
259 path = 'bogus file path'
260 name = 'extension'
261 with self.assertRaises(ImportError) as err:
262 imp.load_dynamic(name, path)
263 self.assertIn(path, err.exception.path)
264 self.assertEqual(name, err.exception.name)
265
Brett Cannon130e4812013-05-03 10:54:23 -0400266 @requires_load_dynamic
Brett Cannon9d0f7722013-05-03 10:37:08 -0400267 def test_load_module_extension_file_is_None(self):
268 # When loading an extension module and the file is None, open one
269 # on the behalf of imp.load_dynamic().
270 # Issue #15902
Brett Cannon8772b182013-05-04 17:54:57 -0400271 name = '_testimportmultiple'
Brett Cannon9d0f7722013-05-03 10:37:08 -0400272 found = imp.find_module(name)
Benjamin Petersonaa6f6882013-05-11 16:29:03 -0500273 if found[0] is not None:
274 found[0].close()
Brett Cannon8772b182013-05-04 17:54:57 -0400275 if found[2][2] != imp.C_EXTENSION:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600276 self.skipTest("found module doesn't appear to be a C extension")
Brett Cannon9d0f7722013-05-03 10:37:08 -0400277 imp.load_module(name, None, *found[1:])
278
Nick Coghlan9d3c61c2015-09-05 21:05:05 +1000279 @requires_load_dynamic
280 def test_issue24748_load_module_skips_sys_modules_check(self):
281 name = 'test.imp_dummy'
282 try:
283 del sys.modules[name]
284 except KeyError:
285 pass
286 try:
287 module = importlib.import_module(name)
288 spec = importlib.util.find_spec('_testmultiphase')
289 module = imp.load_dynamic(name, spec.origin)
290 self.assertEqual(module.__name__, name)
291 self.assertEqual(module.__spec__.name, name)
292 self.assertEqual(module.__spec__.origin, spec.origin)
293 self.assertRaises(AttributeError, getattr, module, 'dummy_name')
294 self.assertEqual(module.int_const, 1969)
295 self.assertIs(sys.modules[name], module)
296 finally:
297 try:
298 del sys.modules[name]
299 except KeyError:
300 pass
301
Brett Cannon997487d2013-06-07 13:26:53 -0400302 @unittest.skipIf(sys.dont_write_bytecode,
303 "test meaningful only when writing bytecode")
304 def test_bug7732(self):
Antoine Pitroubb2c45e2013-08-19 23:31:18 +0200305 with support.temp_cwd():
306 source = support.TESTFN + '.py'
307 os.mkdir(source)
Brett Cannon997487d2013-06-07 13:26:53 -0400308 self.assertRaisesRegex(ImportError, '^No module',
309 imp.find_module, support.TESTFN, ["."])
Brett Cannon330cc522013-08-23 12:10:09 -0400310
Brett Cannona4975a92013-08-23 11:45:57 -0400311 def test_multiple_calls_to_get_data(self):
312 # Issue #18755: make sure multiple calls to get_data() can succeed.
313 loader = imp._LoadSourceCompatibility('imp', imp.__file__,
314 open(imp.__file__))
315 loader.get_data(imp.__file__) # File should be closed
316 loader.get_data(imp.__file__) # Will need to create a newly opened file
Brett Cannon997487d2013-06-07 13:26:53 -0400317
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000318
Nick Coghlan6ead5522009-10-18 13:19:33 +0000319class ReloadTests(unittest.TestCase):
320
321 """Very basic tests to make sure that imp.reload() operates just like
322 reload()."""
323
324 def test_source(self):
Florent Xicluna97133722010-03-20 20:31:34 +0000325 # XXX (ncoghlan): It would be nice to use test.support.CleanImport
Nick Coghlan6ead5522009-10-18 13:19:33 +0000326 # here, but that breaks because the os module registers some
327 # handlers in copy_reg on import. Since CleanImport doesn't
328 # revert that registration, the module is left in a broken
329 # state after reversion. Reinitialising the module contents
330 # and just reverting os.environ to its previous state is an OK
331 # workaround
332 with support.EnvironmentVarGuard():
333 import os
334 imp.reload(os)
335
336 def test_extension(self):
337 with support.CleanImport('time'):
338 import time
339 imp.reload(time)
340
341 def test_builtin(self):
342 with support.CleanImport('marshal'):
343 import marshal
344 imp.reload(marshal)
Christian Heimes13a7a212008-01-07 17:13:09 +0000345
Ezio Melotti056bafe2013-08-10 19:59:36 +0300346 def test_with_deleted_parent(self):
347 # see #18681
348 from html import parser
Serhiy Storchakab2122912013-08-11 20:12:20 +0300349 html = sys.modules.pop('html')
350 def cleanup():
351 sys.modules['html'] = html
Ezio Melotti056bafe2013-08-10 19:59:36 +0300352 self.addCleanup(cleanup)
353 with self.assertRaisesRegex(ImportError, 'html'):
354 imp.reload(parser)
355
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000356
Barry Warsaw28a691b2010-04-17 00:19:56 +0000357class PEP3147Tests(unittest.TestCase):
358 """Tests of PEP 3147."""
359
360 tag = imp.get_tag()
361
Brett Cannon19a2f592012-07-09 13:58:07 -0400362 @unittest.skipUnless(sys.implementation.cache_tag is not None,
363 'requires sys.implementation.cache_tag not be None')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000364 def test_cache_from_source(self):
365 # Given the path to a .py file, return the path to its PEP 3147
366 # defined .pyc file (i.e. under __pycache__).
Brett Cannon410e88d2012-04-22 13:29:47 -0400367 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
368 expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
369 'qux.{}.pyc'.format(self.tag))
370 self.assertEqual(imp.cache_from_source(path, True), expect)
371
Brett Cannon19a2f592012-07-09 13:58:07 -0400372 @unittest.skipUnless(sys.implementation.cache_tag is not None,
373 'requires sys.implementation.cache_tag to not be '
374 'None')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000375 def test_source_from_cache(self):
376 # Given the path to a PEP 3147 defined .pyc file, return the path to
377 # its source. This tests the good path.
Brett Cannon410e88d2012-04-22 13:29:47 -0400378 path = os.path.join('foo', 'bar', 'baz', '__pycache__',
379 'qux.{}.pyc'.format(self.tag))
380 expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
381 self.assertEqual(imp.source_from_cache(path), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000382
Barry Warsaw28a691b2010-04-17 00:19:56 +0000383
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000384class NullImporterTests(unittest.TestCase):
Victor Stinner09c449c2010-08-13 22:23:24 +0000385 @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000386 "Need an undecodeable filename")
387 def test_unencodeable(self):
Victor Stinner09c449c2010-08-13 22:23:24 +0000388 name = support.TESTFN_UNENCODABLE
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000389 os.mkdir(name)
390 try:
391 self.assertRaises(ImportError, imp.NullImporter, name)
392 finally:
393 os.rmdir(name)
394
395
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000396if __name__ == "__main__":
Brett Cannon95ea11f2013-05-03 10:57:08 -0400397 unittest.main()