blob: dc6242325f329099f691eda57a5fc09da8103482 [file] [log] [blame]
Brett Cannon14268532013-05-03 10:56:19 -04001try:
2 import _thread
3except ImportError:
4 _thread = None
Neal Norwitz2294c0d2003-02-12 23:02:21 +00005import imp
Brett Cannonc0499522012-05-11 14:48:41 -04006import importlib
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
Neal Norwitz2294c0d2003-02-12 23:02:21 +000014
Brett Cannon130e4812013-05-03 10:54:23 -040015
16def requires_load_dynamic(meth):
17 """Decorator to skip a test if not running under CPython or lacking
18 imp.load_dynamic()."""
19 meth = support.cpython_only(meth)
20 return unittest.skipIf(not hasattr(imp, 'load_dynamic'),
21 'imp.load_dynamic() required')(meth)
22
23
Brett Cannon14268532013-05-03 10:56:19 -040024@unittest.skipIf(_thread is None, '_thread module is required')
Thomas Wouters89f507f2006-12-13 04:49:30 +000025class LockTests(unittest.TestCase):
Tim Peters579bed72003-04-26 14:31:24 +000026
Thomas Wouters89f507f2006-12-13 04:49:30 +000027 """Very basic test of import lock functions."""
Tim Peters579bed72003-04-26 14:31:24 +000028
Thomas Wouters89f507f2006-12-13 04:49:30 +000029 def verify_lock_state(self, expected):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000030 self.assertEqual(imp.lock_held(), expected,
Thomas Wouters89f507f2006-12-13 04:49:30 +000031 "expected imp.lock_held() to be %r" % expected)
32 def testLock(self):
33 LOOPS = 50
Tim Peters579bed72003-04-26 14:31:24 +000034
Thomas Wouters89f507f2006-12-13 04:49:30 +000035 # The import lock may already be held, e.g. if the test suite is run
36 # via "import test.autotest".
37 lock_held_at_start = imp.lock_held()
38 self.verify_lock_state(lock_held_at_start)
Tim Peters579bed72003-04-26 14:31:24 +000039
Thomas Wouters89f507f2006-12-13 04:49:30 +000040 for i in range(LOOPS):
41 imp.acquire_lock()
42 self.verify_lock_state(True)
Tim Peters579bed72003-04-26 14:31:24 +000043
Thomas Wouters89f507f2006-12-13 04:49:30 +000044 for i in range(LOOPS):
Neal Norwitz2294c0d2003-02-12 23:02:21 +000045 imp.release_lock()
Thomas Wouters89f507f2006-12-13 04:49:30 +000046
47 # The original state should be restored now.
48 self.verify_lock_state(lock_held_at_start)
49
50 if not lock_held_at_start:
51 try:
52 imp.release_lock()
53 except RuntimeError:
54 pass
55 else:
56 self.fail("release_lock() without lock should raise "
57 "RuntimeError")
Neal Norwitz2294c0d2003-02-12 23:02:21 +000058
Guido van Rossumce3a72a2007-10-19 23:16:50 +000059class ImportTests(unittest.TestCase):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000060 def setUp(self):
61 mod = importlib.import_module('test.encoded_modules')
62 self.test_strings = mod.test_strings
63 self.test_path = mod.__path__
64
65 def test_import_encoded_module(self):
66 for modname, encoding, teststr in self.test_strings:
67 mod = importlib.import_module('test.encoded_modules.'
68 'module_' + modname)
69 self.assertEqual(teststr, mod.test)
Guido van Rossumce3a72a2007-10-19 23:16:50 +000070
71 def test_find_module_encoding(self):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000072 for mod, encoding, _ in self.test_strings:
Brett Cannon749afa92010-10-29 23:47:23 +000073 with imp.find_module('module_' + mod, self.test_path)[0] as fd:
74 self.assertEqual(fd.encoding, encoding)
Guido van Rossumce3a72a2007-10-19 23:16:50 +000075
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020076 path = [os.path.dirname(__file__)]
Brett Cannondd9a5692012-04-20 12:59:59 -040077 with self.assertRaises(SyntaxError):
78 imp.find_module('badsyntax_pep3120', path)
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020079
Guido van Rossum40d20bc2007-10-22 00:09:51 +000080 def test_issue1267(self):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000081 for mod, encoding, _ in self.test_strings:
82 fp, filename, info = imp.find_module('module_' + mod,
83 self.test_path)
Brett Cannon749afa92010-10-29 23:47:23 +000084 with fp:
85 self.assertNotEqual(fp, None)
86 self.assertEqual(fp.encoding, encoding)
87 self.assertEqual(fp.tell(), 0)
88 self.assertEqual(fp.readline(), '# test %s encoding\n'
89 % encoding)
Guido van Rossum40d20bc2007-10-22 00:09:51 +000090
91 fp, filename, info = imp.find_module("tokenize")
Brett Cannon749afa92010-10-29 23:47:23 +000092 with fp:
93 self.assertNotEqual(fp, None)
94 self.assertEqual(fp.encoding, "utf-8")
95 self.assertEqual(fp.tell(), 0)
96 self.assertEqual(fp.readline(),
97 '"""Tokenization help for Python programs.\n')
Guido van Rossum40d20bc2007-10-22 00:09:51 +000098
Brett Cannon8a9583e2008-09-04 05:04:25 +000099 def test_issue3594(self):
100 temp_mod_name = 'test_imp_helper'
101 sys.path.insert(0, '.')
102 try:
103 with open(temp_mod_name + '.py', 'w') as file:
104 file.write("# coding: cp1252\nu = 'test.test_imp'\n")
105 file, filename, info = imp.find_module(temp_mod_name)
106 file.close()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000107 self.assertEqual(file.encoding, 'cp1252')
Brett Cannon8a9583e2008-09-04 05:04:25 +0000108 finally:
109 del sys.path[0]
110 support.unlink(temp_mod_name + '.py')
111 support.unlink(temp_mod_name + '.pyc')
112 support.unlink(temp_mod_name + '.pyo')
113
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000114 def test_issue5604(self):
115 # Test cannot cover imp.load_compiled function.
116 # Martin von Loewis note what shared library cannot have non-ascii
117 # character because init_xxx function cannot be compiled
118 # and issue never happens for dynamic modules.
119 # But sources modified to follow generic way for processing pathes.
120
Ezio Melotti435b5312010-03-06 01:20:49 +0000121 # the return encoding could be uppercase or None
122 fs_encoding = sys.getfilesystemencoding()
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000123
124 # covers utf-8 and Windows ANSI code pages
125 # one non-space symbol from every page
126 # (http://en.wikipedia.org/wiki/Code_page)
127 known_locales = {
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000128 'utf-8' : b'\xc3\xa4',
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000129 'cp1250' : b'\x8C',
130 'cp1251' : b'\xc0',
131 'cp1252' : b'\xc0',
132 'cp1253' : b'\xc1',
133 'cp1254' : b'\xc0',
134 'cp1255' : b'\xe0',
135 'cp1256' : b'\xe0',
136 'cp1257' : b'\xc0',
137 'cp1258' : b'\xc0',
138 }
139
Florent Xicluna21164ce2010-03-20 20:30:53 +0000140 if sys.platform == 'darwin':
141 self.assertEqual(fs_encoding, 'utf-8')
142 # Mac OS X uses the Normal Form D decomposition
143 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
144 special_char = b'a\xcc\x88'
145 else:
146 special_char = known_locales.get(fs_encoding)
147
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000148 if not special_char:
Ezio Melotti76e0d1a2010-03-05 15:08:19 +0000149 self.skipTest("can't run this test with %s as filesystem encoding"
150 % fs_encoding)
151 decoded_char = special_char.decode(fs_encoding)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000152 temp_mod_name = 'test_imp_helper_' + decoded_char
153 test_package_name = 'test_imp_helper_package_' + decoded_char
154 init_file_name = os.path.join(test_package_name, '__init__.py')
155 try:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000156 # if the curdir is not in sys.path the test fails when run with
157 # ./python ./Lib/test/regrtest.py test_imp
158 sys.path.insert(0, os.curdir)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000159 with open(temp_mod_name + '.py', 'w') as file:
160 file.write('a = 1\n')
161 file, filename, info = imp.find_module(temp_mod_name)
Brett Cannon749afa92010-10-29 23:47:23 +0000162 with file:
163 self.assertIsNotNone(file)
164 self.assertTrue(filename[:-3].endswith(temp_mod_name))
165 self.assertEqual(info[0], '.py')
166 self.assertEqual(info[1], 'U')
167 self.assertEqual(info[2], imp.PY_SOURCE)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000168
Brett Cannon749afa92010-10-29 23:47:23 +0000169 mod = imp.load_module(temp_mod_name, file, filename, info)
170 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000171
Brett Cannonc0499522012-05-11 14:48:41 -0400172 with warnings.catch_warnings():
173 warnings.simplefilter('ignore')
174 mod = imp.load_source(temp_mod_name, temp_mod_name + '.py')
Ezio Melotti435b5312010-03-06 01:20:49 +0000175 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000176
Brett Cannonc0499522012-05-11 14:48:41 -0400177 with warnings.catch_warnings():
178 warnings.simplefilter('ignore')
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200179 if not sys.dont_write_bytecode:
180 mod = imp.load_compiled(
181 temp_mod_name,
182 imp.cache_from_source(temp_mod_name + '.py'))
Ezio Melotti435b5312010-03-06 01:20:49 +0000183 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000184
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000185 if not os.path.exists(test_package_name):
186 os.mkdir(test_package_name)
187 with open(init_file_name, 'w') as file:
188 file.write('b = 2\n')
Brett Cannonc0499522012-05-11 14:48:41 -0400189 with warnings.catch_warnings():
190 warnings.simplefilter('ignore')
191 package = imp.load_package(test_package_name, test_package_name)
Ezio Melotti435b5312010-03-06 01:20:49 +0000192 self.assertEqual(package.b, 2)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000193 finally:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000194 del sys.path[0]
Ezio Melotti435b5312010-03-06 01:20:49 +0000195 for ext in ('.py', '.pyc', '.pyo'):
196 support.unlink(temp_mod_name + ext)
197 support.unlink(init_file_name + ext)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000198 support.rmtree(test_package_name)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000199
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200200 def test_issue9319(self):
Antoine Pitrou11846902011-04-25 21:39:49 +0200201 path = os.path.dirname(__file__)
Victor Stinner7fdd0fe2011-04-23 01:24:11 +0200202 self.assertRaises(SyntaxError,
Antoine Pitrou11846902011-04-25 21:39:49 +0200203 imp.find_module, "badsyntax_pep3120", [path])
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200204
Nick Coghlan91b9f132012-09-01 00:13:45 +1000205 def test_load_from_source(self):
206 # Verify that the imp module can correctly load and find .py files
207 # XXX (ncoghlan): It would be nice to use support.CleanImport
208 # here, but that breaks because the os module registers some
209 # handlers in copy_reg on import. Since CleanImport doesn't
210 # revert that registration, the module is left in a broken
211 # state after reversion. Reinitialising the module contents
212 # and just reverting os.environ to its previous state is an OK
213 # workaround
214 orig_path = os.path
215 orig_getenv = os.getenv
216 with support.EnvironmentVarGuard():
217 x = imp.find_module("os")
218 self.addCleanup(x[0].close)
219 new_os = imp.load_module("os", *x)
220 self.assertIs(os, new_os)
221 self.assertIs(orig_path, new_os.path)
222 self.assertIsNot(orig_getenv, new_os.getenv)
223
Brett Cannon130e4812013-05-03 10:54:23 -0400224 @requires_load_dynamic
Nick Coghlan91b9f132012-09-01 00:13:45 +1000225 def test_issue15828_load_extensions(self):
226 # Issue 15828 picked up that the adapter between the old imp API
227 # and importlib couldn't handle C extensions
228 example = "_heapq"
229 x = imp.find_module(example)
Brett Cannon848cdfd2012-08-31 11:31:20 -0400230 file_ = x[0]
231 if file_ is not None:
232 self.addCleanup(file_.close)
Nick Coghlan91b9f132012-09-01 00:13:45 +1000233 mod = imp.load_module(example, *x)
234 self.assertEqual(mod.__name__, example)
235
Brett Cannon130e4812013-05-03 10:54:23 -0400236 @requires_load_dynamic
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200237 def test_issue16421_multiple_modules_in_one_dll(self):
238 # Issue 16421: loading several modules from the same compiled file fails
239 m = '_testimportmultiple'
240 fileobj, pathname, description = imp.find_module(m)
241 fileobj.close()
242 mod0 = imp.load_dynamic(m, pathname)
Andrew Svetlovef9a43b2012-12-15 17:22:59 +0200243 mod1 = imp.load_dynamic('_testimportmultiple_foo', pathname)
244 mod2 = imp.load_dynamic('_testimportmultiple_bar', pathname)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200245 self.assertEqual(mod0.__name__, m)
Andrew Svetlovef9a43b2012-12-15 17:22:59 +0200246 self.assertEqual(mod1.__name__, '_testimportmultiple_foo')
247 self.assertEqual(mod2.__name__, '_testimportmultiple_bar')
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200248 with self.assertRaises(ImportError):
249 imp.load_dynamic('nonexistent', pathname)
250
Brett Cannon130e4812013-05-03 10:54:23 -0400251 @requires_load_dynamic
Brett Cannonf0434e62012-04-20 15:22:50 -0400252 def test_load_dynamic_ImportError_path(self):
253 # Issue #1559549 added `name` and `path` attributes to ImportError
254 # in order to provide better detail. Issue #10854 implemented those
255 # attributes on import failures of extensions on Windows.
256 path = 'bogus file path'
257 name = 'extension'
258 with self.assertRaises(ImportError) as err:
259 imp.load_dynamic(name, path)
260 self.assertIn(path, err.exception.path)
261 self.assertEqual(name, err.exception.name)
262
Brett Cannon130e4812013-05-03 10:54:23 -0400263 @requires_load_dynamic
Brett Cannon9d0f7722013-05-03 10:37:08 -0400264 def test_load_module_extension_file_is_None(self):
265 # When loading an extension module and the file is None, open one
266 # on the behalf of imp.load_dynamic().
267 # Issue #15902
Brett Cannon8772b182013-05-04 17:54:57 -0400268 name = '_testimportmultiple'
Brett Cannon9d0f7722013-05-03 10:37:08 -0400269 found = imp.find_module(name)
Benjamin Petersonaa6f6882013-05-11 16:29:03 -0500270 if found[0] is not None:
271 found[0].close()
Brett Cannon8772b182013-05-04 17:54:57 -0400272 if found[2][2] != imp.C_EXTENSION:
273 return
Brett Cannon9d0f7722013-05-03 10:37:08 -0400274 imp.load_module(name, None, *found[1:])
275
Brett Cannon997487d2013-06-07 13:26:53 -0400276 @unittest.skipIf(sys.dont_write_bytecode,
277 "test meaningful only when writing bytecode")
278 def test_bug7732(self):
279 source = support.TESTFN + '.py'
280 os.mkdir(source)
281 try:
282 self.assertRaisesRegex(ImportError, '^No module',
283 imp.find_module, support.TESTFN, ["."])
284 finally:
285 os.rmdir(source)
286
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000287
Nick Coghlan6ead5522009-10-18 13:19:33 +0000288class ReloadTests(unittest.TestCase):
289
290 """Very basic tests to make sure that imp.reload() operates just like
291 reload()."""
292
293 def test_source(self):
Florent Xicluna97133722010-03-20 20:31:34 +0000294 # XXX (ncoghlan): It would be nice to use test.support.CleanImport
Nick Coghlan6ead5522009-10-18 13:19:33 +0000295 # here, but that breaks because the os module registers some
296 # handlers in copy_reg on import. Since CleanImport doesn't
297 # revert that registration, the module is left in a broken
298 # state after reversion. Reinitialising the module contents
299 # and just reverting os.environ to its previous state is an OK
300 # workaround
301 with support.EnvironmentVarGuard():
302 import os
303 imp.reload(os)
304
305 def test_extension(self):
306 with support.CleanImport('time'):
307 import time
308 imp.reload(time)
309
310 def test_builtin(self):
311 with support.CleanImport('marshal'):
312 import marshal
313 imp.reload(marshal)
Christian Heimes13a7a212008-01-07 17:13:09 +0000314
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000315
Barry Warsaw28a691b2010-04-17 00:19:56 +0000316class PEP3147Tests(unittest.TestCase):
317 """Tests of PEP 3147."""
318
319 tag = imp.get_tag()
320
Brett Cannon19a2f592012-07-09 13:58:07 -0400321 @unittest.skipUnless(sys.implementation.cache_tag is not None,
322 'requires sys.implementation.cache_tag not be None')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000323 def test_cache_from_source(self):
324 # Given the path to a .py file, return the path to its PEP 3147
325 # defined .pyc file (i.e. under __pycache__).
Brett Cannon410e88d2012-04-22 13:29:47 -0400326 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
327 expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
328 'qux.{}.pyc'.format(self.tag))
329 self.assertEqual(imp.cache_from_source(path, True), expect)
330
Brett Cannon19a2f592012-07-09 13:58:07 -0400331 def test_cache_from_source_no_cache_tag(self):
332 # Non cache tag means NotImplementedError.
333 with support.swap_attr(sys.implementation, 'cache_tag', None):
334 with self.assertRaises(NotImplementedError):
335 imp.cache_from_source('whatever.py')
336
Brett Cannon410e88d2012-04-22 13:29:47 -0400337 def test_cache_from_source_no_dot(self):
338 # Directory with a dot, filename without dot.
339 path = os.path.join('foo.bar', 'file')
340 expect = os.path.join('foo.bar', '__pycache__',
341 'file{}.pyc'.format(self.tag))
342 self.assertEqual(imp.cache_from_source(path, True), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000343
344 def test_cache_from_source_optimized(self):
345 # Given the path to a .py file, return the path to its PEP 3147
346 # defined .pyo file (i.e. under __pycache__).
Brett Cannon410e88d2012-04-22 13:29:47 -0400347 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
348 expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
349 'qux.{}.pyo'.format(self.tag))
350 self.assertEqual(imp.cache_from_source(path, False), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000351
352 def test_cache_from_source_cwd(self):
Brett Cannon410e88d2012-04-22 13:29:47 -0400353 path = 'foo.py'
354 expect = os.path.join('__pycache__', 'foo.{}.pyc'.format(self.tag))
355 self.assertEqual(imp.cache_from_source(path, True), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000356
357 def test_cache_from_source_override(self):
358 # When debug_override is not None, it can be any true-ish or false-ish
359 # value.
Brett Cannon410e88d2012-04-22 13:29:47 -0400360 path = os.path.join('foo', 'bar', 'baz.py')
361 partial_expect = os.path.join('foo', 'bar', '__pycache__',
362 'baz.{}.py'.format(self.tag))
363 self.assertEqual(imp.cache_from_source(path, []), partial_expect + 'o')
364 self.assertEqual(imp.cache_from_source(path, [17]),
365 partial_expect + 'c')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000366 # However if the bool-ishness can't be determined, the exception
367 # propagates.
368 class Bearish:
369 def __bool__(self): raise RuntimeError
Brett Cannon410e88d2012-04-22 13:29:47 -0400370 with self.assertRaises(RuntimeError):
371 imp.cache_from_source('/foo/bar/baz.py', Bearish())
Barry Warsaw28a691b2010-04-17 00:19:56 +0000372
Brett Cannon410e88d2012-04-22 13:29:47 -0400373 @unittest.skipUnless(os.sep == '\\' and os.altsep == '/',
Barry Warsaw28a691b2010-04-17 00:19:56 +0000374 'test meaningful only where os.altsep is defined')
375 def test_sep_altsep_and_sep_cache_from_source(self):
376 # Windows path and PEP 3147 where sep is right of altsep.
377 self.assertEqual(
378 imp.cache_from_source('\\foo\\bar\\baz/qux.py', True),
Brett Cannon410e88d2012-04-22 13:29:47 -0400379 '\\foo\\bar\\baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000380
Brett Cannon19a2f592012-07-09 13:58:07 -0400381 @unittest.skipUnless(sys.implementation.cache_tag is not None,
382 'requires sys.implementation.cache_tag to not be '
383 'None')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000384 def test_source_from_cache(self):
385 # Given the path to a PEP 3147 defined .pyc file, return the path to
386 # its source. This tests the good path.
Brett Cannon410e88d2012-04-22 13:29:47 -0400387 path = os.path.join('foo', 'bar', 'baz', '__pycache__',
388 'qux.{}.pyc'.format(self.tag))
389 expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
390 self.assertEqual(imp.source_from_cache(path), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000391
Brett Cannon19a2f592012-07-09 13:58:07 -0400392 def test_source_from_cache_no_cache_tag(self):
393 # If sys.implementation.cache_tag is None, raise NotImplementedError.
394 path = os.path.join('blah', '__pycache__', 'whatever.pyc')
395 with support.swap_attr(sys.implementation, 'cache_tag', None):
396 with self.assertRaises(NotImplementedError):
397 imp.source_from_cache(path)
398
Barry Warsaw28a691b2010-04-17 00:19:56 +0000399 def test_source_from_cache_bad_path(self):
400 # When the path to a pyc file is not in PEP 3147 format, a ValueError
401 # is raised.
402 self.assertRaises(
403 ValueError, imp.source_from_cache, '/foo/bar/bazqux.pyc')
404
405 def test_source_from_cache_no_slash(self):
406 # No slashes at all in path -> ValueError
407 self.assertRaises(
408 ValueError, imp.source_from_cache, 'foo.cpython-32.pyc')
409
410 def test_source_from_cache_too_few_dots(self):
411 # Too few dots in final path component -> ValueError
412 self.assertRaises(
413 ValueError, imp.source_from_cache, '__pycache__/foo.pyc')
414
415 def test_source_from_cache_too_many_dots(self):
416 # Too many dots in final path component -> ValueError
417 self.assertRaises(
418 ValueError, imp.source_from_cache,
419 '__pycache__/foo.cpython-32.foo.pyc')
420
421 def test_source_from_cache_no__pycache__(self):
422 # Another problem with the path -> ValueError
423 self.assertRaises(
424 ValueError, imp.source_from_cache,
425 '/foo/bar/foo.cpython-32.foo.pyc')
426
427 def test_package___file__(self):
Antoine Pitrou06e37582012-06-23 17:27:56 +0200428 try:
429 m = __import__('pep3147')
430 except ImportError:
431 pass
432 else:
433 self.fail("pep3147 module already exists: %r" % (m,))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000434 # Test that a package's __file__ points to the right source directory.
435 os.mkdir('pep3147')
436 sys.path.insert(0, os.curdir)
437 def cleanup():
438 if sys.path[0] == os.curdir:
439 del sys.path[0]
440 shutil.rmtree('pep3147')
441 self.addCleanup(cleanup)
442 # Touch the __init__.py file.
Victor Stinnerbf816222011-06-30 23:25:47 +0200443 support.create_empty_file('pep3147/__init__.py')
Antoine Pitrou4f92a682012-02-26 18:09:50 +0100444 importlib.invalidate_caches()
Antoine Pitrouabe72d72012-02-22 01:11:31 +0100445 expected___file__ = os.sep.join(('.', 'pep3147', '__init__.py'))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000446 m = __import__('pep3147')
Antoine Pitrou9a4d7dd2012-02-27 22:01:25 +0100447 self.assertEqual(m.__file__, expected___file__, (m.__file__, m.__path__, sys.path, sys.path_importer_cache))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000448 # Ensure we load the pyc file.
Antoine Pitrou037615e2012-02-22 02:30:09 +0100449 support.unload('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000450 m = __import__('pep3147')
Antoine Pitrou037615e2012-02-22 02:30:09 +0100451 support.unload('pep3147')
Antoine Pitrou9a4d7dd2012-02-27 22:01:25 +0100452 self.assertEqual(m.__file__, expected___file__, (m.__file__, m.__path__, sys.path, sys.path_importer_cache))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000453
454
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000455class NullImporterTests(unittest.TestCase):
Victor Stinner09c449c2010-08-13 22:23:24 +0000456 @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000457 "Need an undecodeable filename")
458 def test_unencodeable(self):
Victor Stinner09c449c2010-08-13 22:23:24 +0000459 name = support.TESTFN_UNENCODABLE
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000460 os.mkdir(name)
461 try:
462 self.assertRaises(ImportError, imp.NullImporter, name)
463 finally:
464 os.rmdir(name)
465
466
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000467if __name__ == "__main__":
Brett Cannon95ea11f2013-05-03 10:57:08 -0400468 unittest.main()