blob: bf29e424d24a52104e76dd13ea5f70d870392d54 [file] [log] [blame]
Neal Norwitz2294c0d2003-02-12 23:02:21 +00001import imp
Brett Cannonc0499522012-05-11 14:48:41 -04002import importlib
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003import os
4import os.path
Barry Warsaw28a691b2010-04-17 00:19:56 +00005import shutil
Brett Cannon8a9583e2008-09-04 05:04:25 +00006import sys
Benjamin Petersonee8712c2008-05-20 21:35:26 +00007from test import support
Eric Snow7491f172013-08-14 18:03:34 -06008from test.test_importlib import util
Brett Cannonc0499522012-05-11 14:48:41 -04009import unittest
10import warnings
Neal Norwitz2294c0d2003-02-12 23:02:21 +000011
Thomas Wouters89f507f2006-12-13 04:49:30 +000012class LockTests(unittest.TestCase):
Tim Peters579bed72003-04-26 14:31:24 +000013
Thomas Wouters89f507f2006-12-13 04:49:30 +000014 """Very basic test of import lock functions."""
Tim Peters579bed72003-04-26 14:31:24 +000015
Thomas Wouters89f507f2006-12-13 04:49:30 +000016 def verify_lock_state(self, expected):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000017 self.assertEqual(imp.lock_held(), expected,
Thomas Wouters89f507f2006-12-13 04:49:30 +000018 "expected imp.lock_held() to be %r" % expected)
19 def testLock(self):
20 LOOPS = 50
Tim Peters579bed72003-04-26 14:31:24 +000021
Thomas Wouters89f507f2006-12-13 04:49:30 +000022 # The import lock may already be held, e.g. if the test suite is run
23 # via "import test.autotest".
24 lock_held_at_start = imp.lock_held()
25 self.verify_lock_state(lock_held_at_start)
Tim Peters579bed72003-04-26 14:31:24 +000026
Thomas Wouters89f507f2006-12-13 04:49:30 +000027 for i in range(LOOPS):
28 imp.acquire_lock()
29 self.verify_lock_state(True)
Tim Peters579bed72003-04-26 14:31:24 +000030
Thomas Wouters89f507f2006-12-13 04:49:30 +000031 for i in range(LOOPS):
Neal Norwitz2294c0d2003-02-12 23:02:21 +000032 imp.release_lock()
Thomas Wouters89f507f2006-12-13 04:49:30 +000033
34 # The original state should be restored now.
35 self.verify_lock_state(lock_held_at_start)
36
37 if not lock_held_at_start:
38 try:
39 imp.release_lock()
40 except RuntimeError:
41 pass
42 else:
43 self.fail("release_lock() without lock should raise "
44 "RuntimeError")
Neal Norwitz2294c0d2003-02-12 23:02:21 +000045
Guido van Rossumce3a72a2007-10-19 23:16:50 +000046class ImportTests(unittest.TestCase):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000047 def setUp(self):
48 mod = importlib.import_module('test.encoded_modules')
49 self.test_strings = mod.test_strings
50 self.test_path = mod.__path__
51
52 def test_import_encoded_module(self):
53 for modname, encoding, teststr in self.test_strings:
54 mod = importlib.import_module('test.encoded_modules.'
55 'module_' + modname)
56 self.assertEqual(teststr, mod.test)
Guido van Rossumce3a72a2007-10-19 23:16:50 +000057
58 def test_find_module_encoding(self):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000059 for mod, encoding, _ in self.test_strings:
Brett Cannon749afa92010-10-29 23:47:23 +000060 with imp.find_module('module_' + mod, self.test_path)[0] as fd:
61 self.assertEqual(fd.encoding, encoding)
Guido van Rossumce3a72a2007-10-19 23:16:50 +000062
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020063 path = [os.path.dirname(__file__)]
Brett Cannondd9a5692012-04-20 12:59:59 -040064 with self.assertRaises(SyntaxError):
65 imp.find_module('badsyntax_pep3120', path)
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020066
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
Brett Cannonc0499522012-05-11 14:48:41 -0400159 with warnings.catch_warnings():
160 warnings.simplefilter('ignore')
161 mod = imp.load_source(temp_mod_name, 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
Brett Cannonc0499522012-05-11 14:48:41 -0400164 with warnings.catch_warnings():
165 warnings.simplefilter('ignore')
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200166 if not sys.dont_write_bytecode:
167 mod = imp.load_compiled(
168 temp_mod_name,
169 imp.cache_from_source(temp_mod_name + '.py'))
Ezio Melotti435b5312010-03-06 01:20:49 +0000170 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000171
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000172 if not os.path.exists(test_package_name):
173 os.mkdir(test_package_name)
174 with open(init_file_name, 'w') as file:
175 file.write('b = 2\n')
Brett Cannonc0499522012-05-11 14:48:41 -0400176 with warnings.catch_warnings():
177 warnings.simplefilter('ignore')
178 package = imp.load_package(test_package_name, test_package_name)
Ezio Melotti435b5312010-03-06 01:20:49 +0000179 self.assertEqual(package.b, 2)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000180 finally:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000181 del sys.path[0]
Ezio Melotti435b5312010-03-06 01:20:49 +0000182 for ext in ('.py', '.pyc', '.pyo'):
183 support.unlink(temp_mod_name + ext)
184 support.unlink(init_file_name + ext)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000185 support.rmtree(test_package_name)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000186
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200187 def test_issue9319(self):
Antoine Pitrou11846902011-04-25 21:39:49 +0200188 path = os.path.dirname(__file__)
Victor Stinner7fdd0fe2011-04-23 01:24:11 +0200189 self.assertRaises(SyntaxError,
Antoine Pitrou11846902011-04-25 21:39:49 +0200190 imp.find_module, "badsyntax_pep3120", [path])
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200191
Nick Coghlan91b9f132012-09-01 00:13:45 +1000192 def test_load_from_source(self):
193 # Verify that the imp module can correctly load and find .py files
194 # XXX (ncoghlan): It would be nice to use support.CleanImport
195 # here, but that breaks because the os module registers some
196 # handlers in copy_reg on import. Since CleanImport doesn't
197 # revert that registration, the module is left in a broken
198 # state after reversion. Reinitialising the module contents
199 # and just reverting os.environ to its previous state is an OK
200 # workaround
201 orig_path = os.path
202 orig_getenv = os.getenv
203 with support.EnvironmentVarGuard():
204 x = imp.find_module("os")
205 self.addCleanup(x[0].close)
206 new_os = imp.load_module("os", *x)
207 self.assertIs(os, new_os)
208 self.assertIs(orig_path, new_os.path)
209 self.assertIsNot(orig_getenv, new_os.getenv)
210
211 @support.cpython_only
Brett Cannon9d0f7722013-05-03 10:37:08 -0400212 @unittest.skipIf(not hasattr(imp, 'load_dynamic'),
213 'imp.load_dynamic() required')
Nick Coghlan91b9f132012-09-01 00:13:45 +1000214 def test_issue15828_load_extensions(self):
215 # Issue 15828 picked up that the adapter between the old imp API
216 # and importlib couldn't handle C extensions
217 example = "_heapq"
218 x = imp.find_module(example)
Brett Cannon848cdfd2012-08-31 11:31:20 -0400219 file_ = x[0]
220 if file_ is not None:
221 self.addCleanup(file_.close)
Nick Coghlan91b9f132012-09-01 00:13:45 +1000222 mod = imp.load_module(example, *x)
223 self.assertEqual(mod.__name__, example)
224
Brett Cannonf0434e62012-04-20 15:22:50 -0400225 def test_load_dynamic_ImportError_path(self):
226 # Issue #1559549 added `name` and `path` attributes to ImportError
227 # in order to provide better detail. Issue #10854 implemented those
228 # attributes on import failures of extensions on Windows.
229 path = 'bogus file path'
230 name = 'extension'
231 with self.assertRaises(ImportError) as err:
232 imp.load_dynamic(name, path)
233 self.assertIn(path, err.exception.path)
234 self.assertEqual(name, err.exception.name)
235
Brett Cannon9d0f7722013-05-03 10:37:08 -0400236 @support.cpython_only
237 @unittest.skipIf(not hasattr(imp, 'load_dynamic'),
238 'imp.load_dynamic() required')
239 def test_load_module_extension_file_is_None(self):
240 # When loading an extension module and the file is None, open one
241 # on the behalf of imp.load_dynamic().
242 # Issue #15902
243 name = '_heapq'
244 found = imp.find_module(name)
Benjamin Petersonaa6f6882013-05-11 16:29:03 -0500245 if found[0] is not None:
246 found[0].close()
Brett Cannondea2ec42013-05-04 18:11:12 -0400247 if found[2][2] != imp.C_EXTENSION:
248 return
Brett Cannon9d0f7722013-05-03 10:37:08 -0400249 imp.load_module(name, None, *found[1:])
250
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000251
Nick Coghlan6ead5522009-10-18 13:19:33 +0000252class ReloadTests(unittest.TestCase):
253
254 """Very basic tests to make sure that imp.reload() operates just like
255 reload()."""
256
257 def test_source(self):
Florent Xicluna97133722010-03-20 20:31:34 +0000258 # XXX (ncoghlan): It would be nice to use test.support.CleanImport
Nick Coghlan6ead5522009-10-18 13:19:33 +0000259 # here, but that breaks because the os module registers some
260 # handlers in copy_reg on import. Since CleanImport doesn't
261 # revert that registration, the module is left in a broken
262 # state after reversion. Reinitialising the module contents
263 # and just reverting os.environ to its previous state is an OK
264 # workaround
265 with support.EnvironmentVarGuard():
266 import os
267 imp.reload(os)
268
269 def test_extension(self):
270 with support.CleanImport('time'):
271 import time
272 imp.reload(time)
273
274 def test_builtin(self):
275 with support.CleanImport('marshal'):
276 import marshal
277 imp.reload(marshal)
Christian Heimes13a7a212008-01-07 17:13:09 +0000278
Ezio Melotti056bafe2013-08-10 19:59:36 +0300279 def test_with_deleted_parent(self):
280 # see #18681
281 from html import parser
Serhiy Storchakab2122912013-08-11 20:12:20 +0300282 html = sys.modules.pop('html')
283 def cleanup():
284 sys.modules['html'] = html
Ezio Melotti056bafe2013-08-10 19:59:36 +0300285 self.addCleanup(cleanup)
286 with self.assertRaisesRegex(ImportError, 'html'):
287 imp.reload(parser)
288
Eric Snow7491f172013-08-14 18:03:34 -0600289 def test_module_replaced(self):
290 # see #18698
291 def code():
292 module = type(sys)('top_level')
293 module.spam = 3
294 sys.modules['top_level'] = module
295 mock = util.mock_modules('top_level',
296 module_code={'top_level': code})
297 with mock:
298 with util.import_state(meta_path=[mock]):
299 module = importlib.import_module('top_level')
300 reloaded = imp.reload(module)
301 actual = sys.modules['top_level']
302 self.assertEqual(actual.spam, 3)
303 self.assertEqual(reloaded.spam, 3)
304
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000305
Barry Warsaw28a691b2010-04-17 00:19:56 +0000306class PEP3147Tests(unittest.TestCase):
307 """Tests of PEP 3147."""
308
309 tag = imp.get_tag()
310
Brett Cannon19a2f592012-07-09 13:58:07 -0400311 @unittest.skipUnless(sys.implementation.cache_tag is not None,
312 'requires sys.implementation.cache_tag not be None')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000313 def test_cache_from_source(self):
314 # Given the path to a .py file, return the path to its PEP 3147
315 # defined .pyc file (i.e. under __pycache__).
Brett Cannon410e88d2012-04-22 13:29:47 -0400316 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
317 expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
318 'qux.{}.pyc'.format(self.tag))
319 self.assertEqual(imp.cache_from_source(path, True), expect)
320
Brett Cannon19a2f592012-07-09 13:58:07 -0400321 def test_cache_from_source_no_cache_tag(self):
322 # Non cache tag means NotImplementedError.
323 with support.swap_attr(sys.implementation, 'cache_tag', None):
324 with self.assertRaises(NotImplementedError):
325 imp.cache_from_source('whatever.py')
326
Brett Cannon410e88d2012-04-22 13:29:47 -0400327 def test_cache_from_source_no_dot(self):
328 # Directory with a dot, filename without dot.
329 path = os.path.join('foo.bar', 'file')
330 expect = os.path.join('foo.bar', '__pycache__',
331 'file{}.pyc'.format(self.tag))
332 self.assertEqual(imp.cache_from_source(path, True), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000333
334 def test_cache_from_source_optimized(self):
335 # Given the path to a .py file, return the path to its PEP 3147
336 # defined .pyo file (i.e. under __pycache__).
Brett Cannon410e88d2012-04-22 13:29:47 -0400337 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
338 expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
339 'qux.{}.pyo'.format(self.tag))
340 self.assertEqual(imp.cache_from_source(path, False), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000341
342 def test_cache_from_source_cwd(self):
Brett Cannon410e88d2012-04-22 13:29:47 -0400343 path = 'foo.py'
344 expect = os.path.join('__pycache__', 'foo.{}.pyc'.format(self.tag))
345 self.assertEqual(imp.cache_from_source(path, True), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000346
347 def test_cache_from_source_override(self):
348 # When debug_override is not None, it can be any true-ish or false-ish
349 # value.
Brett Cannon410e88d2012-04-22 13:29:47 -0400350 path = os.path.join('foo', 'bar', 'baz.py')
351 partial_expect = os.path.join('foo', 'bar', '__pycache__',
352 'baz.{}.py'.format(self.tag))
353 self.assertEqual(imp.cache_from_source(path, []), partial_expect + 'o')
354 self.assertEqual(imp.cache_from_source(path, [17]),
355 partial_expect + 'c')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000356 # However if the bool-ishness can't be determined, the exception
357 # propagates.
358 class Bearish:
359 def __bool__(self): raise RuntimeError
Brett Cannon410e88d2012-04-22 13:29:47 -0400360 with self.assertRaises(RuntimeError):
361 imp.cache_from_source('/foo/bar/baz.py', Bearish())
Barry Warsaw28a691b2010-04-17 00:19:56 +0000362
Brett Cannon410e88d2012-04-22 13:29:47 -0400363 @unittest.skipUnless(os.sep == '\\' and os.altsep == '/',
Barry Warsaw28a691b2010-04-17 00:19:56 +0000364 'test meaningful only where os.altsep is defined')
365 def test_sep_altsep_and_sep_cache_from_source(self):
366 # Windows path and PEP 3147 where sep is right of altsep.
367 self.assertEqual(
368 imp.cache_from_source('\\foo\\bar\\baz/qux.py', True),
Brett Cannon410e88d2012-04-22 13:29:47 -0400369 '\\foo\\bar\\baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000370
Brett Cannon19a2f592012-07-09 13:58:07 -0400371 @unittest.skipUnless(sys.implementation.cache_tag is not None,
372 'requires sys.implementation.cache_tag to not be '
373 'None')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000374 def test_source_from_cache(self):
375 # Given the path to a PEP 3147 defined .pyc file, return the path to
376 # its source. This tests the good path.
Brett Cannon410e88d2012-04-22 13:29:47 -0400377 path = os.path.join('foo', 'bar', 'baz', '__pycache__',
378 'qux.{}.pyc'.format(self.tag))
379 expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
380 self.assertEqual(imp.source_from_cache(path), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000381
Brett Cannon19a2f592012-07-09 13:58:07 -0400382 def test_source_from_cache_no_cache_tag(self):
383 # If sys.implementation.cache_tag is None, raise NotImplementedError.
384 path = os.path.join('blah', '__pycache__', 'whatever.pyc')
385 with support.swap_attr(sys.implementation, 'cache_tag', None):
386 with self.assertRaises(NotImplementedError):
387 imp.source_from_cache(path)
388
Barry Warsaw28a691b2010-04-17 00:19:56 +0000389 def test_source_from_cache_bad_path(self):
390 # When the path to a pyc file is not in PEP 3147 format, a ValueError
391 # is raised.
392 self.assertRaises(
393 ValueError, imp.source_from_cache, '/foo/bar/bazqux.pyc')
394
395 def test_source_from_cache_no_slash(self):
396 # No slashes at all in path -> ValueError
397 self.assertRaises(
398 ValueError, imp.source_from_cache, 'foo.cpython-32.pyc')
399
400 def test_source_from_cache_too_few_dots(self):
401 # Too few dots in final path component -> ValueError
402 self.assertRaises(
403 ValueError, imp.source_from_cache, '__pycache__/foo.pyc')
404
405 def test_source_from_cache_too_many_dots(self):
406 # Too many dots in final path component -> ValueError
407 self.assertRaises(
408 ValueError, imp.source_from_cache,
409 '__pycache__/foo.cpython-32.foo.pyc')
410
411 def test_source_from_cache_no__pycache__(self):
412 # Another problem with the path -> ValueError
413 self.assertRaises(
414 ValueError, imp.source_from_cache,
415 '/foo/bar/foo.cpython-32.foo.pyc')
416
417 def test_package___file__(self):
Antoine Pitrou06e37582012-06-23 17:27:56 +0200418 try:
419 m = __import__('pep3147')
420 except ImportError:
421 pass
422 else:
423 self.fail("pep3147 module already exists: %r" % (m,))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000424 # Test that a package's __file__ points to the right source directory.
425 os.mkdir('pep3147')
426 sys.path.insert(0, os.curdir)
427 def cleanup():
428 if sys.path[0] == os.curdir:
429 del sys.path[0]
430 shutil.rmtree('pep3147')
431 self.addCleanup(cleanup)
432 # Touch the __init__.py file.
Victor Stinnerbf816222011-06-30 23:25:47 +0200433 support.create_empty_file('pep3147/__init__.py')
Antoine Pitrou4f92a682012-02-26 18:09:50 +0100434 importlib.invalidate_caches()
Antoine Pitrouabe72d72012-02-22 01:11:31 +0100435 expected___file__ = os.sep.join(('.', 'pep3147', '__init__.py'))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000436 m = __import__('pep3147')
Antoine Pitrou9a4d7dd2012-02-27 22:01:25 +0100437 self.assertEqual(m.__file__, expected___file__, (m.__file__, m.__path__, sys.path, sys.path_importer_cache))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000438 # Ensure we load the pyc file.
Antoine Pitrou037615e2012-02-22 02:30:09 +0100439 support.unload('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000440 m = __import__('pep3147')
Antoine Pitrou037615e2012-02-22 02:30:09 +0100441 support.unload('pep3147')
Antoine Pitrou9a4d7dd2012-02-27 22:01:25 +0100442 self.assertEqual(m.__file__, expected___file__, (m.__file__, m.__path__, sys.path, sys.path_importer_cache))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000443
444
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000445class NullImporterTests(unittest.TestCase):
Victor Stinner09c449c2010-08-13 22:23:24 +0000446 @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000447 "Need an undecodeable filename")
448 def test_unencodeable(self):
Victor Stinner09c449c2010-08-13 22:23:24 +0000449 name = support.TESTFN_UNENCODABLE
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000450 os.mkdir(name)
451 try:
452 self.assertRaises(ImportError, imp.NullImporter, name)
453 finally:
454 os.rmdir(name)
455
456
Neal Norwitz996acf12003-02-17 14:51:41 +0000457def test_main():
Hirokazu Yamamoto36144092008-09-09 07:33:27 +0000458 tests = [
459 ImportTests,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000460 PEP3147Tests,
Nick Coghlan6ead5522009-10-18 13:19:33 +0000461 ReloadTests,
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000462 NullImporterTests,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000463 ]
Hirokazu Yamamoto36144092008-09-09 07:33:27 +0000464 try:
465 import _thread
466 except ImportError:
467 pass
468 else:
469 tests.append(LockTests)
470 support.run_unittest(*tests)
Neal Norwitz996acf12003-02-17 14:51:41 +0000471
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000472if __name__ == "__main__":
Neal Norwitz996acf12003-02-17 14:51:41 +0000473 test_main()