blob: 83fcf2259f60b03c584bd67d24f3bd44e3e0ba8c [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__)]
62 self.assertRaisesRegex(SyntaxError,
63 r"Non-UTF-8 code starting with '\\xf6'"
64 r" in file .*badsyntax_pep3120.py",
65 imp.find_module, 'badsyntax_pep3120', path)
66
Guido van Rossum40d20bc2007-10-22 00:09:51 +000067 def test_issue1267(self):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000068 for mod, encoding, _ in self.test_strings:
69 fp, filename, info = imp.find_module('module_' + mod,
70 self.test_path)
Brett Cannon749afa92010-10-29 23:47:23 +000071 with fp:
72 self.assertNotEqual(fp, None)
73 self.assertEqual(fp.encoding, encoding)
74 self.assertEqual(fp.tell(), 0)
75 self.assertEqual(fp.readline(), '# test %s encoding\n'
76 % encoding)
Guido van Rossum40d20bc2007-10-22 00:09:51 +000077
78 fp, filename, info = imp.find_module("tokenize")
Brett Cannon749afa92010-10-29 23:47:23 +000079 with fp:
80 self.assertNotEqual(fp, None)
81 self.assertEqual(fp.encoding, "utf-8")
82 self.assertEqual(fp.tell(), 0)
83 self.assertEqual(fp.readline(),
84 '"""Tokenization help for Python programs.\n')
Guido van Rossum40d20bc2007-10-22 00:09:51 +000085
Brett Cannon8a9583e2008-09-04 05:04:25 +000086 def test_issue3594(self):
87 temp_mod_name = 'test_imp_helper'
88 sys.path.insert(0, '.')
89 try:
90 with open(temp_mod_name + '.py', 'w') as file:
91 file.write("# coding: cp1252\nu = 'test.test_imp'\n")
92 file, filename, info = imp.find_module(temp_mod_name)
93 file.close()
Ezio Melottib3aedd42010-11-20 19:04:17 +000094 self.assertEqual(file.encoding, 'cp1252')
Brett Cannon8a9583e2008-09-04 05:04:25 +000095 finally:
96 del sys.path[0]
97 support.unlink(temp_mod_name + '.py')
98 support.unlink(temp_mod_name + '.pyc')
99 support.unlink(temp_mod_name + '.pyo')
100
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000101 def test_issue5604(self):
102 # Test cannot cover imp.load_compiled function.
103 # Martin von Loewis note what shared library cannot have non-ascii
104 # character because init_xxx function cannot be compiled
105 # and issue never happens for dynamic modules.
106 # But sources modified to follow generic way for processing pathes.
107
Ezio Melotti435b5312010-03-06 01:20:49 +0000108 # the return encoding could be uppercase or None
109 fs_encoding = sys.getfilesystemencoding()
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000110
111 # covers utf-8 and Windows ANSI code pages
112 # one non-space symbol from every page
113 # (http://en.wikipedia.org/wiki/Code_page)
114 known_locales = {
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000115 'utf-8' : b'\xc3\xa4',
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000116 'cp1250' : b'\x8C',
117 'cp1251' : b'\xc0',
118 'cp1252' : b'\xc0',
119 'cp1253' : b'\xc1',
120 'cp1254' : b'\xc0',
121 'cp1255' : b'\xe0',
122 'cp1256' : b'\xe0',
123 'cp1257' : b'\xc0',
124 'cp1258' : b'\xc0',
125 }
126
Florent Xicluna21164ce2010-03-20 20:30:53 +0000127 if sys.platform == 'darwin':
128 self.assertEqual(fs_encoding, 'utf-8')
129 # Mac OS X uses the Normal Form D decomposition
130 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
131 special_char = b'a\xcc\x88'
132 else:
133 special_char = known_locales.get(fs_encoding)
134
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000135 if not special_char:
Ezio Melotti76e0d1a2010-03-05 15:08:19 +0000136 self.skipTest("can't run this test with %s as filesystem encoding"
137 % fs_encoding)
138 decoded_char = special_char.decode(fs_encoding)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000139 temp_mod_name = 'test_imp_helper_' + decoded_char
140 test_package_name = 'test_imp_helper_package_' + decoded_char
141 init_file_name = os.path.join(test_package_name, '__init__.py')
142 try:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000143 # if the curdir is not in sys.path the test fails when run with
144 # ./python ./Lib/test/regrtest.py test_imp
145 sys.path.insert(0, os.curdir)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000146 with open(temp_mod_name + '.py', 'w') as file:
147 file.write('a = 1\n')
148 file, filename, info = imp.find_module(temp_mod_name)
Brett Cannon749afa92010-10-29 23:47:23 +0000149 with file:
150 self.assertIsNotNone(file)
151 self.assertTrue(filename[:-3].endswith(temp_mod_name))
152 self.assertEqual(info[0], '.py')
153 self.assertEqual(info[1], 'U')
154 self.assertEqual(info[2], imp.PY_SOURCE)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000155
Brett Cannon749afa92010-10-29 23:47:23 +0000156 mod = imp.load_module(temp_mod_name, file, filename, info)
157 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000158
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000159 mod = imp.load_source(temp_mod_name, temp_mod_name + '.py')
Ezio Melotti435b5312010-03-06 01:20:49 +0000160 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000161
Barry Warsaw28a691b2010-04-17 00:19:56 +0000162 mod = imp.load_compiled(
163 temp_mod_name, imp.cache_from_source(temp_mod_name + '.py'))
Ezio Melotti435b5312010-03-06 01:20:49 +0000164 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000165
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000166 if not os.path.exists(test_package_name):
167 os.mkdir(test_package_name)
168 with open(init_file_name, 'w') as file:
169 file.write('b = 2\n')
170 package = imp.load_package(test_package_name, test_package_name)
Ezio Melotti435b5312010-03-06 01:20:49 +0000171 self.assertEqual(package.b, 2)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000172 finally:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000173 del sys.path[0]
Ezio Melotti435b5312010-03-06 01:20:49 +0000174 for ext in ('.py', '.pyc', '.pyo'):
175 support.unlink(temp_mod_name + ext)
176 support.unlink(init_file_name + ext)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000177 support.rmtree(test_package_name)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000178
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200179 def test_issue9319(self):
Antoine Pitrou11846902011-04-25 21:39:49 +0200180 path = os.path.dirname(__file__)
Victor Stinner7fdd0fe2011-04-23 01:24:11 +0200181 self.assertRaises(SyntaxError,
Antoine Pitrou11846902011-04-25 21:39:49 +0200182 imp.find_module, "badsyntax_pep3120", [path])
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200183
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000184
Nick Coghlan6ead5522009-10-18 13:19:33 +0000185class ReloadTests(unittest.TestCase):
186
187 """Very basic tests to make sure that imp.reload() operates just like
188 reload()."""
189
190 def test_source(self):
Florent Xicluna97133722010-03-20 20:31:34 +0000191 # XXX (ncoghlan): It would be nice to use test.support.CleanImport
Nick Coghlan6ead5522009-10-18 13:19:33 +0000192 # here, but that breaks because the os module registers some
193 # handlers in copy_reg on import. Since CleanImport doesn't
194 # revert that registration, the module is left in a broken
195 # state after reversion. Reinitialising the module contents
196 # and just reverting os.environ to its previous state is an OK
197 # workaround
198 with support.EnvironmentVarGuard():
199 import os
200 imp.reload(os)
201
202 def test_extension(self):
203 with support.CleanImport('time'):
204 import time
205 imp.reload(time)
206
207 def test_builtin(self):
208 with support.CleanImport('marshal'):
209 import marshal
210 imp.reload(marshal)
Christian Heimes13a7a212008-01-07 17:13:09 +0000211
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000212
Barry Warsaw28a691b2010-04-17 00:19:56 +0000213class PEP3147Tests(unittest.TestCase):
214 """Tests of PEP 3147."""
215
216 tag = imp.get_tag()
217
218 def test_cache_from_source(self):
219 # Given the path to a .py file, return the path to its PEP 3147
220 # defined .pyc file (i.e. under __pycache__).
221 self.assertEqual(
222 imp.cache_from_source('/foo/bar/baz/qux.py', True),
223 '/foo/bar/baz/__pycache__/qux.{}.pyc'.format(self.tag))
Victor Stinnerccbf4752011-03-14 15:05:12 -0400224 # Directory with a dot, filename without dot
225 self.assertEqual(
226 imp.cache_from_source('/foo.bar/file', True),
227 '/foo.bar/__pycache__/file{}.pyc'.format(self.tag))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000228
229 def test_cache_from_source_optimized(self):
230 # Given the path to a .py file, return the path to its PEP 3147
231 # defined .pyo file (i.e. under __pycache__).
232 self.assertEqual(
233 imp.cache_from_source('/foo/bar/baz/qux.py', False),
234 '/foo/bar/baz/__pycache__/qux.{}.pyo'.format(self.tag))
235
236 def test_cache_from_source_cwd(self):
237 self.assertEqual(imp.cache_from_source('foo.py', True),
238 os.sep.join(('__pycache__',
239 'foo.{}.pyc'.format(self.tag))))
240
241 def test_cache_from_source_override(self):
242 # When debug_override is not None, it can be any true-ish or false-ish
243 # value.
244 self.assertEqual(
245 imp.cache_from_source('/foo/bar/baz.py', []),
246 '/foo/bar/__pycache__/baz.{}.pyo'.format(self.tag))
247 self.assertEqual(
248 imp.cache_from_source('/foo/bar/baz.py', [17]),
249 '/foo/bar/__pycache__/baz.{}.pyc'.format(self.tag))
250 # However if the bool-ishness can't be determined, the exception
251 # propagates.
252 class Bearish:
253 def __bool__(self): raise RuntimeError
254 self.assertRaises(
255 RuntimeError,
256 imp.cache_from_source, '/foo/bar/baz.py', Bearish())
257
258 @unittest.skipIf(os.altsep is None,
259 'test meaningful only where os.altsep is defined')
260 def test_altsep_cache_from_source(self):
261 # Windows path and PEP 3147.
262 self.assertEqual(
263 imp.cache_from_source('\\foo\\bar\\baz\\qux.py', True),
264 '\\foo\\bar\\baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
265
266 @unittest.skipIf(os.altsep is None,
267 'test meaningful only where os.altsep is defined')
268 def test_altsep_and_sep_cache_from_source(self):
269 # Windows path and PEP 3147 where altsep is right of sep.
270 self.assertEqual(
271 imp.cache_from_source('\\foo\\bar/baz\\qux.py', True),
272 '\\foo\\bar/baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
273
274 @unittest.skipIf(os.altsep is None,
275 'test meaningful only where os.altsep is defined')
276 def test_sep_altsep_and_sep_cache_from_source(self):
277 # Windows path and PEP 3147 where sep is right of altsep.
278 self.assertEqual(
279 imp.cache_from_source('\\foo\\bar\\baz/qux.py', True),
280 '\\foo\\bar\\baz/__pycache__/qux.{}.pyc'.format(self.tag))
281
282 def test_source_from_cache(self):
283 # Given the path to a PEP 3147 defined .pyc file, return the path to
284 # its source. This tests the good path.
285 self.assertEqual(imp.source_from_cache(
286 '/foo/bar/baz/__pycache__/qux.{}.pyc'.format(self.tag)),
287 '/foo/bar/baz/qux.py')
288
289 def test_source_from_cache_bad_path(self):
290 # When the path to a pyc file is not in PEP 3147 format, a ValueError
291 # is raised.
292 self.assertRaises(
293 ValueError, imp.source_from_cache, '/foo/bar/bazqux.pyc')
294
295 def test_source_from_cache_no_slash(self):
296 # No slashes at all in path -> ValueError
297 self.assertRaises(
298 ValueError, imp.source_from_cache, 'foo.cpython-32.pyc')
299
300 def test_source_from_cache_too_few_dots(self):
301 # Too few dots in final path component -> ValueError
302 self.assertRaises(
303 ValueError, imp.source_from_cache, '__pycache__/foo.pyc')
304
305 def test_source_from_cache_too_many_dots(self):
306 # Too many dots in final path component -> ValueError
307 self.assertRaises(
308 ValueError, imp.source_from_cache,
309 '__pycache__/foo.cpython-32.foo.pyc')
310
311 def test_source_from_cache_no__pycache__(self):
312 # Another problem with the path -> ValueError
313 self.assertRaises(
314 ValueError, imp.source_from_cache,
315 '/foo/bar/foo.cpython-32.foo.pyc')
316
317 def test_package___file__(self):
318 # Test that a package's __file__ points to the right source directory.
319 os.mkdir('pep3147')
320 sys.path.insert(0, os.curdir)
321 def cleanup():
322 if sys.path[0] == os.curdir:
323 del sys.path[0]
324 shutil.rmtree('pep3147')
325 self.addCleanup(cleanup)
326 # Touch the __init__.py file.
327 with open('pep3147/__init__.py', 'w'):
328 pass
329 m = __import__('pep3147')
330 # Ensure we load the pyc file.
331 support.forget('pep3147')
332 m = __import__('pep3147')
333 self.assertEqual(m.__file__,
334 os.sep.join(('.', 'pep3147', '__init__.py')))
335
336
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000337class NullImporterTests(unittest.TestCase):
Victor Stinner09c449c2010-08-13 22:23:24 +0000338 @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000339 "Need an undecodeable filename")
340 def test_unencodeable(self):
Victor Stinner09c449c2010-08-13 22:23:24 +0000341 name = support.TESTFN_UNENCODABLE
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000342 os.mkdir(name)
343 try:
344 self.assertRaises(ImportError, imp.NullImporter, name)
345 finally:
346 os.rmdir(name)
347
348
Neal Norwitz996acf12003-02-17 14:51:41 +0000349def test_main():
Hirokazu Yamamoto36144092008-09-09 07:33:27 +0000350 tests = [
351 ImportTests,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000352 PEP3147Tests,
Nick Coghlan6ead5522009-10-18 13:19:33 +0000353 ReloadTests,
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000354 NullImporterTests,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000355 ]
Hirokazu Yamamoto36144092008-09-09 07:33:27 +0000356 try:
357 import _thread
358 except ImportError:
359 pass
360 else:
361 tests.append(LockTests)
362 support.run_unittest(*tests)
Neal Norwitz996acf12003-02-17 14:51:41 +0000363
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000364if __name__ == "__main__":
Neal Norwitz996acf12003-02-17 14:51:41 +0000365 test_main()