blob: c71a4c755346a0766e1d2f319621c78f2660e717 [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
Neal Norwitz2294c0d2003-02-12 23:02:21 +00008
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):
45
46 def test_find_module_encoding(self):
Benjamin Peterson335d2c72010-07-05 14:59:40 +000047 fd = imp.find_module("pydoc")[0]
Guido van Rossumce3a72a2007-10-19 23:16:50 +000048 self.assertEqual(fd.encoding, "iso-8859-1")
49
Guido van Rossum40d20bc2007-10-22 00:09:51 +000050 def test_issue1267(self):
51 fp, filename, info = imp.find_module("pydoc")
52 self.assertNotEqual(fp, None)
53 self.assertEqual(fp.encoding, "iso-8859-1")
54 self.assertEqual(fp.tell(), 0)
Benjamin Peterson25bfc552010-03-11 23:59:55 +000055 self.assertEqual(fp.readline(), '#!/usr/bin/env python3\n')
Guido van Rossum40d20bc2007-10-22 00:09:51 +000056 fp.close()
57
58 fp, filename, info = imp.find_module("tokenize")
59 self.assertNotEqual(fp, None)
60 self.assertEqual(fp.encoding, "utf-8")
61 self.assertEqual(fp.tell(), 0)
62 self.assertEqual(fp.readline(),
63 '"""Tokenization help for Python programs.\n')
64 fp.close()
65
Brett Cannon8a9583e2008-09-04 05:04:25 +000066 def test_issue3594(self):
67 temp_mod_name = 'test_imp_helper'
68 sys.path.insert(0, '.')
69 try:
70 with open(temp_mod_name + '.py', 'w') as file:
71 file.write("# coding: cp1252\nu = 'test.test_imp'\n")
72 file, filename, info = imp.find_module(temp_mod_name)
73 file.close()
74 self.assertEquals(file.encoding, 'cp1252')
75 finally:
76 del sys.path[0]
77 support.unlink(temp_mod_name + '.py')
78 support.unlink(temp_mod_name + '.pyc')
79 support.unlink(temp_mod_name + '.pyo')
80
Guido van Rossum0ad59d42009-03-30 22:01:35 +000081 def test_issue5604(self):
82 # Test cannot cover imp.load_compiled function.
83 # Martin von Loewis note what shared library cannot have non-ascii
84 # character because init_xxx function cannot be compiled
85 # and issue never happens for dynamic modules.
86 # But sources modified to follow generic way for processing pathes.
87
Ezio Melotti435b5312010-03-06 01:20:49 +000088 # the return encoding could be uppercase or None
89 fs_encoding = sys.getfilesystemencoding()
Guido van Rossum0ad59d42009-03-30 22:01:35 +000090
91 # covers utf-8 and Windows ANSI code pages
92 # one non-space symbol from every page
93 # (http://en.wikipedia.org/wiki/Code_page)
94 known_locales = {
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +000095 'utf-8' : b'\xc3\xa4',
Guido van Rossum0ad59d42009-03-30 22:01:35 +000096 'cp1250' : b'\x8C',
97 'cp1251' : b'\xc0',
98 'cp1252' : b'\xc0',
99 'cp1253' : b'\xc1',
100 'cp1254' : b'\xc0',
101 'cp1255' : b'\xe0',
102 'cp1256' : b'\xe0',
103 'cp1257' : b'\xc0',
104 'cp1258' : b'\xc0',
105 }
106
Florent Xicluna21164ce2010-03-20 20:30:53 +0000107 if sys.platform == 'darwin':
108 self.assertEqual(fs_encoding, 'utf-8')
109 # Mac OS X uses the Normal Form D decomposition
110 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
111 special_char = b'a\xcc\x88'
112 else:
113 special_char = known_locales.get(fs_encoding)
114
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000115 if not special_char:
Ezio Melotti76e0d1a2010-03-05 15:08:19 +0000116 self.skipTest("can't run this test with %s as filesystem encoding"
117 % fs_encoding)
118 decoded_char = special_char.decode(fs_encoding)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000119 temp_mod_name = 'test_imp_helper_' + decoded_char
120 test_package_name = 'test_imp_helper_package_' + decoded_char
121 init_file_name = os.path.join(test_package_name, '__init__.py')
122 try:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000123 # if the curdir is not in sys.path the test fails when run with
124 # ./python ./Lib/test/regrtest.py test_imp
125 sys.path.insert(0, os.curdir)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000126 with open(temp_mod_name + '.py', 'w') as file:
127 file.write('a = 1\n')
128 file, filename, info = imp.find_module(temp_mod_name)
Ezio Melotti435b5312010-03-06 01:20:49 +0000129 self.assertIsNotNone(file)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000130 self.assertTrue(filename[:-3].endswith(temp_mod_name))
Ezio Melotti435b5312010-03-06 01:20:49 +0000131 self.assertEqual(info[0], '.py')
132 self.assertEqual(info[1], 'U')
133 self.assertEqual(info[2], imp.PY_SOURCE)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000134
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000135 mod = imp.load_module(temp_mod_name, file, filename, info)
Ezio Melotti435b5312010-03-06 01:20:49 +0000136 self.assertEqual(mod.a, 1)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000137 file.close()
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000138
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000139 mod = imp.load_source(temp_mod_name, temp_mod_name + '.py')
Ezio Melotti435b5312010-03-06 01:20:49 +0000140 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000141
Barry Warsaw28a691b2010-04-17 00:19:56 +0000142 mod = imp.load_compiled(
143 temp_mod_name, imp.cache_from_source(temp_mod_name + '.py'))
Ezio Melotti435b5312010-03-06 01:20:49 +0000144 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000145
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000146 if not os.path.exists(test_package_name):
147 os.mkdir(test_package_name)
148 with open(init_file_name, 'w') as file:
149 file.write('b = 2\n')
150 package = imp.load_package(test_package_name, test_package_name)
Ezio Melotti435b5312010-03-06 01:20:49 +0000151 self.assertEqual(package.b, 2)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000152 finally:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000153 del sys.path[0]
Ezio Melotti435b5312010-03-06 01:20:49 +0000154 for ext in ('.py', '.pyc', '.pyo'):
155 support.unlink(temp_mod_name + ext)
156 support.unlink(init_file_name + ext)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000157 support.rmtree(test_package_name)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000158
159
Nick Coghlan6ead5522009-10-18 13:19:33 +0000160class ReloadTests(unittest.TestCase):
161
162 """Very basic tests to make sure that imp.reload() operates just like
163 reload()."""
164
165 def test_source(self):
Florent Xicluna97133722010-03-20 20:31:34 +0000166 # XXX (ncoghlan): It would be nice to use test.support.CleanImport
Nick Coghlan6ead5522009-10-18 13:19:33 +0000167 # here, but that breaks because the os module registers some
168 # handlers in copy_reg on import. Since CleanImport doesn't
169 # revert that registration, the module is left in a broken
170 # state after reversion. Reinitialising the module contents
171 # and just reverting os.environ to its previous state is an OK
172 # workaround
173 with support.EnvironmentVarGuard():
174 import os
175 imp.reload(os)
176
177 def test_extension(self):
178 with support.CleanImport('time'):
179 import time
180 imp.reload(time)
181
182 def test_builtin(self):
183 with support.CleanImport('marshal'):
184 import marshal
185 imp.reload(marshal)
Christian Heimes13a7a212008-01-07 17:13:09 +0000186
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000187
Barry Warsaw28a691b2010-04-17 00:19:56 +0000188class PEP3147Tests(unittest.TestCase):
189 """Tests of PEP 3147."""
190
191 tag = imp.get_tag()
192
193 def test_cache_from_source(self):
194 # Given the path to a .py file, return the path to its PEP 3147
195 # defined .pyc file (i.e. under __pycache__).
196 self.assertEqual(
197 imp.cache_from_source('/foo/bar/baz/qux.py', True),
198 '/foo/bar/baz/__pycache__/qux.{}.pyc'.format(self.tag))
199
200 def test_cache_from_source_optimized(self):
201 # Given the path to a .py file, return the path to its PEP 3147
202 # defined .pyo file (i.e. under __pycache__).
203 self.assertEqual(
204 imp.cache_from_source('/foo/bar/baz/qux.py', False),
205 '/foo/bar/baz/__pycache__/qux.{}.pyo'.format(self.tag))
206
207 def test_cache_from_source_cwd(self):
208 self.assertEqual(imp.cache_from_source('foo.py', True),
209 os.sep.join(('__pycache__',
210 'foo.{}.pyc'.format(self.tag))))
211
212 def test_cache_from_source_override(self):
213 # When debug_override is not None, it can be any true-ish or false-ish
214 # value.
215 self.assertEqual(
216 imp.cache_from_source('/foo/bar/baz.py', []),
217 '/foo/bar/__pycache__/baz.{}.pyo'.format(self.tag))
218 self.assertEqual(
219 imp.cache_from_source('/foo/bar/baz.py', [17]),
220 '/foo/bar/__pycache__/baz.{}.pyc'.format(self.tag))
221 # However if the bool-ishness can't be determined, the exception
222 # propagates.
223 class Bearish:
224 def __bool__(self): raise RuntimeError
225 self.assertRaises(
226 RuntimeError,
227 imp.cache_from_source, '/foo/bar/baz.py', Bearish())
228
229 @unittest.skipIf(os.altsep is None,
230 'test meaningful only where os.altsep is defined')
231 def test_altsep_cache_from_source(self):
232 # Windows path and PEP 3147.
233 self.assertEqual(
234 imp.cache_from_source('\\foo\\bar\\baz\\qux.py', True),
235 '\\foo\\bar\\baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
236
237 @unittest.skipIf(os.altsep is None,
238 'test meaningful only where os.altsep is defined')
239 def test_altsep_and_sep_cache_from_source(self):
240 # Windows path and PEP 3147 where altsep is right of sep.
241 self.assertEqual(
242 imp.cache_from_source('\\foo\\bar/baz\\qux.py', True),
243 '\\foo\\bar/baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
244
245 @unittest.skipIf(os.altsep is None,
246 'test meaningful only where os.altsep is defined')
247 def test_sep_altsep_and_sep_cache_from_source(self):
248 # Windows path and PEP 3147 where sep is right of altsep.
249 self.assertEqual(
250 imp.cache_from_source('\\foo\\bar\\baz/qux.py', True),
251 '\\foo\\bar\\baz/__pycache__/qux.{}.pyc'.format(self.tag))
252
253 def test_source_from_cache(self):
254 # Given the path to a PEP 3147 defined .pyc file, return the path to
255 # its source. This tests the good path.
256 self.assertEqual(imp.source_from_cache(
257 '/foo/bar/baz/__pycache__/qux.{}.pyc'.format(self.tag)),
258 '/foo/bar/baz/qux.py')
259
260 def test_source_from_cache_bad_path(self):
261 # When the path to a pyc file is not in PEP 3147 format, a ValueError
262 # is raised.
263 self.assertRaises(
264 ValueError, imp.source_from_cache, '/foo/bar/bazqux.pyc')
265
266 def test_source_from_cache_no_slash(self):
267 # No slashes at all in path -> ValueError
268 self.assertRaises(
269 ValueError, imp.source_from_cache, 'foo.cpython-32.pyc')
270
271 def test_source_from_cache_too_few_dots(self):
272 # Too few dots in final path component -> ValueError
273 self.assertRaises(
274 ValueError, imp.source_from_cache, '__pycache__/foo.pyc')
275
276 def test_source_from_cache_too_many_dots(self):
277 # Too many dots in final path component -> ValueError
278 self.assertRaises(
279 ValueError, imp.source_from_cache,
280 '__pycache__/foo.cpython-32.foo.pyc')
281
282 def test_source_from_cache_no__pycache__(self):
283 # Another problem with the path -> ValueError
284 self.assertRaises(
285 ValueError, imp.source_from_cache,
286 '/foo/bar/foo.cpython-32.foo.pyc')
287
288 def test_package___file__(self):
289 # Test that a package's __file__ points to the right source directory.
290 os.mkdir('pep3147')
291 sys.path.insert(0, os.curdir)
292 def cleanup():
293 if sys.path[0] == os.curdir:
294 del sys.path[0]
295 shutil.rmtree('pep3147')
296 self.addCleanup(cleanup)
297 # Touch the __init__.py file.
298 with open('pep3147/__init__.py', 'w'):
299 pass
300 m = __import__('pep3147')
301 # Ensure we load the pyc file.
302 support.forget('pep3147')
303 m = __import__('pep3147')
304 self.assertEqual(m.__file__,
305 os.sep.join(('.', 'pep3147', '__init__.py')))
306
307
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000308class NullImporterTests(unittest.TestCase):
Victor Stinner09c449c2010-08-13 22:23:24 +0000309 @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000310 "Need an undecodeable filename")
311 def test_unencodeable(self):
Victor Stinner09c449c2010-08-13 22:23:24 +0000312 name = support.TESTFN_UNENCODABLE
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000313 os.mkdir(name)
314 try:
315 self.assertRaises(ImportError, imp.NullImporter, name)
316 finally:
317 os.rmdir(name)
318
319
Neal Norwitz996acf12003-02-17 14:51:41 +0000320def test_main():
Hirokazu Yamamoto36144092008-09-09 07:33:27 +0000321 tests = [
322 ImportTests,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000323 PEP3147Tests,
Nick Coghlan6ead5522009-10-18 13:19:33 +0000324 ReloadTests,
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000325 NullImporterTests,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000326 ]
Hirokazu Yamamoto36144092008-09-09 07:33:27 +0000327 try:
328 import _thread
329 except ImportError:
330 pass
331 else:
332 tests.append(LockTests)
333 support.run_unittest(*tests)
Neal Norwitz996acf12003-02-17 14:51:41 +0000334
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000335if __name__ == "__main__":
Neal Norwitz996acf12003-02-17 14:51:41 +0000336 test_main()