blob: 9fe8f432188f185dde838fb52cd0553a8d523db9 [file] [log] [blame]
Neal Norwitz2294c0d2003-02-12 23:02:21 +00001import imp
Guido van Rossum0ad59d42009-03-30 22:01:35 +00002import os
3import os.path
Barry Warsaw28a691b2010-04-17 00:19:56 +00004import shutil
Brett Cannon8a9583e2008-09-04 05:04:25 +00005import sys
Thomas Wouters89f507f2006-12-13 04:49:30 +00006import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00007from test import support
Alexander Belopolskye8f58322010-10-15 16:28:20 +00008import importlib
Neal Norwitz2294c0d2003-02-12 23:02:21 +00009
Thomas Wouters89f507f2006-12-13 04:49:30 +000010class LockTests(unittest.TestCase):
Tim Peters579bed72003-04-26 14:31:24 +000011
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 """Very basic test of import lock functions."""
Tim Peters579bed72003-04-26 14:31:24 +000013
Thomas Wouters89f507f2006-12-13 04:49:30 +000014 def verify_lock_state(self, expected):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000015 self.assertEqual(imp.lock_held(), expected,
Thomas Wouters89f507f2006-12-13 04:49:30 +000016 "expected imp.lock_held() to be %r" % expected)
17 def testLock(self):
18 LOOPS = 50
Tim Peters579bed72003-04-26 14:31:24 +000019
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 # The import lock may already be held, e.g. if the test suite is run
21 # via "import test.autotest".
22 lock_held_at_start = imp.lock_held()
23 self.verify_lock_state(lock_held_at_start)
Tim Peters579bed72003-04-26 14:31:24 +000024
Thomas Wouters89f507f2006-12-13 04:49:30 +000025 for i in range(LOOPS):
26 imp.acquire_lock()
27 self.verify_lock_state(True)
Tim Peters579bed72003-04-26 14:31:24 +000028
Thomas Wouters89f507f2006-12-13 04:49:30 +000029 for i in range(LOOPS):
Neal Norwitz2294c0d2003-02-12 23:02:21 +000030 imp.release_lock()
Thomas Wouters89f507f2006-12-13 04:49:30 +000031
32 # The original state should be restored now.
33 self.verify_lock_state(lock_held_at_start)
34
35 if not lock_held_at_start:
36 try:
37 imp.release_lock()
38 except RuntimeError:
39 pass
40 else:
41 self.fail("release_lock() without lock should raise "
42 "RuntimeError")
Neal Norwitz2294c0d2003-02-12 23:02:21 +000043
Guido van Rossumce3a72a2007-10-19 23:16:50 +000044class ImportTests(unittest.TestCase):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000045 def setUp(self):
46 mod = importlib.import_module('test.encoded_modules')
47 self.test_strings = mod.test_strings
48 self.test_path = mod.__path__
49
50 def test_import_encoded_module(self):
51 for modname, encoding, teststr in self.test_strings:
52 mod = importlib.import_module('test.encoded_modules.'
53 'module_' + modname)
54 self.assertEqual(teststr, mod.test)
Guido van Rossumce3a72a2007-10-19 23:16:50 +000055
56 def test_find_module_encoding(self):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000057 for mod, encoding, _ in self.test_strings:
Brett Cannon749afa92010-10-29 23:47:23 +000058 with imp.find_module('module_' + mod, self.test_path)[0] as fd:
59 self.assertEqual(fd.encoding, encoding)
Guido van Rossumce3a72a2007-10-19 23:16:50 +000060
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020061 path = [os.path.dirname(__file__)]
Brett Cannondd9a5692012-04-20 12:59:59 -040062 with self.assertRaises(SyntaxError):
63 imp.find_module('badsyntax_pep3120', path)
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020064
Guido van Rossum40d20bc2007-10-22 00:09:51 +000065 def test_issue1267(self):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000066 for mod, encoding, _ in self.test_strings:
67 fp, filename, info = imp.find_module('module_' + mod,
68 self.test_path)
Brett Cannon749afa92010-10-29 23:47:23 +000069 with fp:
70 self.assertNotEqual(fp, None)
71 self.assertEqual(fp.encoding, encoding)
72 self.assertEqual(fp.tell(), 0)
73 self.assertEqual(fp.readline(), '# test %s encoding\n'
74 % encoding)
Guido van Rossum40d20bc2007-10-22 00:09:51 +000075
76 fp, filename, info = imp.find_module("tokenize")
Brett Cannon749afa92010-10-29 23:47:23 +000077 with fp:
78 self.assertNotEqual(fp, None)
79 self.assertEqual(fp.encoding, "utf-8")
80 self.assertEqual(fp.tell(), 0)
81 self.assertEqual(fp.readline(),
82 '"""Tokenization help for Python programs.\n')
Guido van Rossum40d20bc2007-10-22 00:09:51 +000083
Brett Cannon8a9583e2008-09-04 05:04:25 +000084 def test_issue3594(self):
85 temp_mod_name = 'test_imp_helper'
86 sys.path.insert(0, '.')
87 try:
88 with open(temp_mod_name + '.py', 'w') as file:
89 file.write("# coding: cp1252\nu = 'test.test_imp'\n")
90 file, filename, info = imp.find_module(temp_mod_name)
91 file.close()
Ezio Melottib3aedd42010-11-20 19:04:17 +000092 self.assertEqual(file.encoding, 'cp1252')
Brett Cannon8a9583e2008-09-04 05:04:25 +000093 finally:
94 del sys.path[0]
95 support.unlink(temp_mod_name + '.py')
96 support.unlink(temp_mod_name + '.pyc')
97 support.unlink(temp_mod_name + '.pyo')
98
Guido van Rossum0ad59d42009-03-30 22:01:35 +000099 def test_issue5604(self):
100 # Test cannot cover imp.load_compiled function.
101 # Martin von Loewis note what shared library cannot have non-ascii
102 # character because init_xxx function cannot be compiled
103 # and issue never happens for dynamic modules.
104 # But sources modified to follow generic way for processing pathes.
105
Ezio Melotti435b5312010-03-06 01:20:49 +0000106 # the return encoding could be uppercase or None
107 fs_encoding = sys.getfilesystemencoding()
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000108
109 # covers utf-8 and Windows ANSI code pages
110 # one non-space symbol from every page
111 # (http://en.wikipedia.org/wiki/Code_page)
112 known_locales = {
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000113 'utf-8' : b'\xc3\xa4',
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000114 'cp1250' : b'\x8C',
115 'cp1251' : b'\xc0',
116 'cp1252' : b'\xc0',
117 'cp1253' : b'\xc1',
118 'cp1254' : b'\xc0',
119 'cp1255' : b'\xe0',
120 'cp1256' : b'\xe0',
121 'cp1257' : b'\xc0',
122 'cp1258' : b'\xc0',
123 }
124
Florent Xicluna21164ce2010-03-20 20:30:53 +0000125 if sys.platform == 'darwin':
126 self.assertEqual(fs_encoding, 'utf-8')
127 # Mac OS X uses the Normal Form D decomposition
128 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
129 special_char = b'a\xcc\x88'
130 else:
131 special_char = known_locales.get(fs_encoding)
132
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000133 if not special_char:
Ezio Melotti76e0d1a2010-03-05 15:08:19 +0000134 self.skipTest("can't run this test with %s as filesystem encoding"
135 % fs_encoding)
136 decoded_char = special_char.decode(fs_encoding)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000137 temp_mod_name = 'test_imp_helper_' + decoded_char
138 test_package_name = 'test_imp_helper_package_' + decoded_char
139 init_file_name = os.path.join(test_package_name, '__init__.py')
140 try:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000141 # if the curdir is not in sys.path the test fails when run with
142 # ./python ./Lib/test/regrtest.py test_imp
143 sys.path.insert(0, os.curdir)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000144 with open(temp_mod_name + '.py', 'w') as file:
145 file.write('a = 1\n')
146 file, filename, info = imp.find_module(temp_mod_name)
Brett Cannon749afa92010-10-29 23:47:23 +0000147 with file:
148 self.assertIsNotNone(file)
149 self.assertTrue(filename[:-3].endswith(temp_mod_name))
150 self.assertEqual(info[0], '.py')
151 self.assertEqual(info[1], 'U')
152 self.assertEqual(info[2], imp.PY_SOURCE)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000153
Brett Cannon749afa92010-10-29 23:47:23 +0000154 mod = imp.load_module(temp_mod_name, file, filename, info)
155 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000156
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000157 mod = imp.load_source(temp_mod_name, temp_mod_name + '.py')
Ezio Melotti435b5312010-03-06 01:20:49 +0000158 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000159
Barry Warsaw28a691b2010-04-17 00:19:56 +0000160 mod = imp.load_compiled(
161 temp_mod_name, imp.cache_from_source(temp_mod_name + '.py'))
Ezio Melotti435b5312010-03-06 01:20:49 +0000162 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000163
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000164 if not os.path.exists(test_package_name):
165 os.mkdir(test_package_name)
166 with open(init_file_name, 'w') as file:
167 file.write('b = 2\n')
168 package = imp.load_package(test_package_name, test_package_name)
Ezio Melotti435b5312010-03-06 01:20:49 +0000169 self.assertEqual(package.b, 2)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000170 finally:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000171 del sys.path[0]
Ezio Melotti435b5312010-03-06 01:20:49 +0000172 for ext in ('.py', '.pyc', '.pyo'):
173 support.unlink(temp_mod_name + ext)
174 support.unlink(init_file_name + ext)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000175 support.rmtree(test_package_name)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000176
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200177 def test_issue9319(self):
Antoine Pitrou11846902011-04-25 21:39:49 +0200178 path = os.path.dirname(__file__)
Victor Stinner7fdd0fe2011-04-23 01:24:11 +0200179 self.assertRaises(SyntaxError,
Antoine Pitrou11846902011-04-25 21:39:49 +0200180 imp.find_module, "badsyntax_pep3120", [path])
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200181
Brett Cannonf0434e62012-04-20 15:22:50 -0400182 def test_load_dynamic_ImportError_path(self):
183 # Issue #1559549 added `name` and `path` attributes to ImportError
184 # in order to provide better detail. Issue #10854 implemented those
185 # attributes on import failures of extensions on Windows.
186 path = 'bogus file path'
187 name = 'extension'
188 with self.assertRaises(ImportError) as err:
189 imp.load_dynamic(name, path)
190 self.assertIn(path, err.exception.path)
191 self.assertEqual(name, err.exception.name)
192
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000193
Nick Coghlan6ead5522009-10-18 13:19:33 +0000194class ReloadTests(unittest.TestCase):
195
196 """Very basic tests to make sure that imp.reload() operates just like
197 reload()."""
198
199 def test_source(self):
Florent Xicluna97133722010-03-20 20:31:34 +0000200 # XXX (ncoghlan): It would be nice to use test.support.CleanImport
Nick Coghlan6ead5522009-10-18 13:19:33 +0000201 # here, but that breaks because the os module registers some
202 # handlers in copy_reg on import. Since CleanImport doesn't
203 # revert that registration, the module is left in a broken
204 # state after reversion. Reinitialising the module contents
205 # and just reverting os.environ to its previous state is an OK
206 # workaround
207 with support.EnvironmentVarGuard():
208 import os
209 imp.reload(os)
210
211 def test_extension(self):
212 with support.CleanImport('time'):
213 import time
214 imp.reload(time)
215
216 def test_builtin(self):
217 with support.CleanImport('marshal'):
218 import marshal
219 imp.reload(marshal)
Christian Heimes13a7a212008-01-07 17:13:09 +0000220
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000221
Barry Warsaw28a691b2010-04-17 00:19:56 +0000222class PEP3147Tests(unittest.TestCase):
223 """Tests of PEP 3147."""
224
225 tag = imp.get_tag()
226
227 def test_cache_from_source(self):
228 # Given the path to a .py file, return the path to its PEP 3147
229 # defined .pyc file (i.e. under __pycache__).
230 self.assertEqual(
231 imp.cache_from_source('/foo/bar/baz/qux.py', True),
232 '/foo/bar/baz/__pycache__/qux.{}.pyc'.format(self.tag))
Victor Stinnerccbf4752011-03-14 15:05:12 -0400233 # Directory with a dot, filename without dot
234 self.assertEqual(
235 imp.cache_from_source('/foo.bar/file', True),
236 '/foo.bar/__pycache__/file{}.pyc'.format(self.tag))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000237
238 def test_cache_from_source_optimized(self):
239 # Given the path to a .py file, return the path to its PEP 3147
240 # defined .pyo file (i.e. under __pycache__).
241 self.assertEqual(
242 imp.cache_from_source('/foo/bar/baz/qux.py', False),
243 '/foo/bar/baz/__pycache__/qux.{}.pyo'.format(self.tag))
244
245 def test_cache_from_source_cwd(self):
246 self.assertEqual(imp.cache_from_source('foo.py', True),
247 os.sep.join(('__pycache__',
248 'foo.{}.pyc'.format(self.tag))))
249
250 def test_cache_from_source_override(self):
251 # When debug_override is not None, it can be any true-ish or false-ish
252 # value.
253 self.assertEqual(
254 imp.cache_from_source('/foo/bar/baz.py', []),
255 '/foo/bar/__pycache__/baz.{}.pyo'.format(self.tag))
256 self.assertEqual(
257 imp.cache_from_source('/foo/bar/baz.py', [17]),
258 '/foo/bar/__pycache__/baz.{}.pyc'.format(self.tag))
259 # However if the bool-ishness can't be determined, the exception
260 # propagates.
261 class Bearish:
262 def __bool__(self): raise RuntimeError
263 self.assertRaises(
264 RuntimeError,
265 imp.cache_from_source, '/foo/bar/baz.py', Bearish())
266
267 @unittest.skipIf(os.altsep is None,
268 'test meaningful only where os.altsep is defined')
269 def test_altsep_cache_from_source(self):
270 # Windows path and PEP 3147.
271 self.assertEqual(
272 imp.cache_from_source('\\foo\\bar\\baz\\qux.py', True),
273 '\\foo\\bar\\baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
274
275 @unittest.skipIf(os.altsep is None,
276 'test meaningful only where os.altsep is defined')
277 def test_altsep_and_sep_cache_from_source(self):
278 # Windows path and PEP 3147 where altsep is right of sep.
279 self.assertEqual(
280 imp.cache_from_source('\\foo\\bar/baz\\qux.py', True),
281 '\\foo\\bar/baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
282
283 @unittest.skipIf(os.altsep is None,
284 'test meaningful only where os.altsep is defined')
285 def test_sep_altsep_and_sep_cache_from_source(self):
286 # Windows path and PEP 3147 where sep is right of altsep.
287 self.assertEqual(
288 imp.cache_from_source('\\foo\\bar\\baz/qux.py', True),
289 '\\foo\\bar\\baz/__pycache__/qux.{}.pyc'.format(self.tag))
290
291 def test_source_from_cache(self):
292 # Given the path to a PEP 3147 defined .pyc file, return the path to
293 # its source. This tests the good path.
294 self.assertEqual(imp.source_from_cache(
295 '/foo/bar/baz/__pycache__/qux.{}.pyc'.format(self.tag)),
296 '/foo/bar/baz/qux.py')
297
298 def test_source_from_cache_bad_path(self):
299 # When the path to a pyc file is not in PEP 3147 format, a ValueError
300 # is raised.
301 self.assertRaises(
302 ValueError, imp.source_from_cache, '/foo/bar/bazqux.pyc')
303
304 def test_source_from_cache_no_slash(self):
305 # No slashes at all in path -> ValueError
306 self.assertRaises(
307 ValueError, imp.source_from_cache, 'foo.cpython-32.pyc')
308
309 def test_source_from_cache_too_few_dots(self):
310 # Too few dots in final path component -> ValueError
311 self.assertRaises(
312 ValueError, imp.source_from_cache, '__pycache__/foo.pyc')
313
314 def test_source_from_cache_too_many_dots(self):
315 # Too many dots in final path component -> ValueError
316 self.assertRaises(
317 ValueError, imp.source_from_cache,
318 '__pycache__/foo.cpython-32.foo.pyc')
319
320 def test_source_from_cache_no__pycache__(self):
321 # Another problem with the path -> ValueError
322 self.assertRaises(
323 ValueError, imp.source_from_cache,
324 '/foo/bar/foo.cpython-32.foo.pyc')
325
326 def test_package___file__(self):
327 # Test that a package's __file__ points to the right source directory.
328 os.mkdir('pep3147')
329 sys.path.insert(0, os.curdir)
330 def cleanup():
331 if sys.path[0] == os.curdir:
332 del sys.path[0]
333 shutil.rmtree('pep3147')
334 self.addCleanup(cleanup)
335 # Touch the __init__.py file.
Victor Stinnerbf816222011-06-30 23:25:47 +0200336 support.create_empty_file('pep3147/__init__.py')
Antoine Pitrou4f92a682012-02-26 18:09:50 +0100337 importlib.invalidate_caches()
Antoine Pitrouabe72d72012-02-22 01:11:31 +0100338 expected___file__ = os.sep.join(('.', 'pep3147', '__init__.py'))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000339 m = __import__('pep3147')
Antoine Pitrou9a4d7dd2012-02-27 22:01:25 +0100340 self.assertEqual(m.__file__, expected___file__, (m.__file__, m.__path__, sys.path, sys.path_importer_cache))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000341 # Ensure we load the pyc file.
Antoine Pitrou037615e2012-02-22 02:30:09 +0100342 support.unload('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000343 m = __import__('pep3147')
Antoine Pitrou037615e2012-02-22 02:30:09 +0100344 support.unload('pep3147')
Antoine Pitrou9a4d7dd2012-02-27 22:01:25 +0100345 self.assertEqual(m.__file__, expected___file__, (m.__file__, m.__path__, sys.path, sys.path_importer_cache))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000346
347
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000348class NullImporterTests(unittest.TestCase):
Victor Stinner09c449c2010-08-13 22:23:24 +0000349 @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000350 "Need an undecodeable filename")
351 def test_unencodeable(self):
Victor Stinner09c449c2010-08-13 22:23:24 +0000352 name = support.TESTFN_UNENCODABLE
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000353 os.mkdir(name)
354 try:
355 self.assertRaises(ImportError, imp.NullImporter, name)
356 finally:
357 os.rmdir(name)
358
359
Neal Norwitz996acf12003-02-17 14:51:41 +0000360def test_main():
Hirokazu Yamamoto36144092008-09-09 07:33:27 +0000361 tests = [
362 ImportTests,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000363 PEP3147Tests,
Nick Coghlan6ead5522009-10-18 13:19:33 +0000364 ReloadTests,
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000365 NullImporterTests,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000366 ]
Hirokazu Yamamoto36144092008-09-09 07:33:27 +0000367 try:
368 import _thread
369 except ImportError:
370 pass
371 else:
372 tests.append(LockTests)
373 support.run_unittest(*tests)
Neal Norwitz996acf12003-02-17 14:51:41 +0000374
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000375if __name__ == "__main__":
Neal Norwitz996acf12003-02-17 14:51:41 +0000376 test_main()