blob: 80b9ec38c5d0cac31ba47b433578b1258ff1ad6c [file] [log] [blame]
Brett Cannon14268532013-05-03 10:56:19 -04001try:
2 import _thread
3except ImportError:
4 _thread = None
Brett Cannonc0499522012-05-11 14:48:41 -04005import importlib
Guido van Rossum0ad59d42009-03-30 22:01:35 +00006import os
7import os.path
Barry Warsaw28a691b2010-04-17 00:19:56 +00008import shutil
Brett Cannon8a9583e2008-09-04 05:04:25 +00009import sys
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
Brett Cannonc0499522012-05-11 14:48:41 -040011import unittest
12import warnings
Brett Cannone4f41de2013-06-16 13:13:40 -040013with warnings.catch_warnings():
14 warnings.simplefilter('ignore', PendingDeprecationWarning)
15 import imp
Neal Norwitz2294c0d2003-02-12 23:02:21 +000016
Brett Cannon130e4812013-05-03 10:54:23 -040017
18def requires_load_dynamic(meth):
19 """Decorator to skip a test if not running under CPython or lacking
20 imp.load_dynamic()."""
21 meth = support.cpython_only(meth)
22 return unittest.skipIf(not hasattr(imp, 'load_dynamic'),
23 'imp.load_dynamic() required')(meth)
24
25
Brett Cannon14268532013-05-03 10:56:19 -040026@unittest.skipIf(_thread is None, '_thread module is required')
Thomas Wouters89f507f2006-12-13 04:49:30 +000027class LockTests(unittest.TestCase):
Tim Peters579bed72003-04-26 14:31:24 +000028
Thomas Wouters89f507f2006-12-13 04:49:30 +000029 """Very basic test of import lock functions."""
Tim Peters579bed72003-04-26 14:31:24 +000030
Thomas Wouters89f507f2006-12-13 04:49:30 +000031 def verify_lock_state(self, expected):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000032 self.assertEqual(imp.lock_held(), expected,
Thomas Wouters89f507f2006-12-13 04:49:30 +000033 "expected imp.lock_held() to be %r" % expected)
34 def testLock(self):
35 LOOPS = 50
Tim Peters579bed72003-04-26 14:31:24 +000036
Thomas Wouters89f507f2006-12-13 04:49:30 +000037 # The import lock may already be held, e.g. if the test suite is run
38 # via "import test.autotest".
39 lock_held_at_start = imp.lock_held()
40 self.verify_lock_state(lock_held_at_start)
Tim Peters579bed72003-04-26 14:31:24 +000041
Thomas Wouters89f507f2006-12-13 04:49:30 +000042 for i in range(LOOPS):
43 imp.acquire_lock()
44 self.verify_lock_state(True)
Tim Peters579bed72003-04-26 14:31:24 +000045
Thomas Wouters89f507f2006-12-13 04:49:30 +000046 for i in range(LOOPS):
Neal Norwitz2294c0d2003-02-12 23:02:21 +000047 imp.release_lock()
Thomas Wouters89f507f2006-12-13 04:49:30 +000048
49 # The original state should be restored now.
50 self.verify_lock_state(lock_held_at_start)
51
52 if not lock_held_at_start:
53 try:
54 imp.release_lock()
55 except RuntimeError:
56 pass
57 else:
58 self.fail("release_lock() without lock should raise "
59 "RuntimeError")
Neal Norwitz2294c0d2003-02-12 23:02:21 +000060
Guido van Rossumce3a72a2007-10-19 23:16:50 +000061class ImportTests(unittest.TestCase):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000062 def setUp(self):
63 mod = importlib.import_module('test.encoded_modules')
64 self.test_strings = mod.test_strings
65 self.test_path = mod.__path__
66
67 def test_import_encoded_module(self):
68 for modname, encoding, teststr in self.test_strings:
69 mod = importlib.import_module('test.encoded_modules.'
70 'module_' + modname)
71 self.assertEqual(teststr, mod.test)
Guido van Rossumce3a72a2007-10-19 23:16:50 +000072
73 def test_find_module_encoding(self):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000074 for mod, encoding, _ in self.test_strings:
Brett Cannon749afa92010-10-29 23:47:23 +000075 with imp.find_module('module_' + mod, self.test_path)[0] as fd:
76 self.assertEqual(fd.encoding, encoding)
Guido van Rossumce3a72a2007-10-19 23:16:50 +000077
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020078 path = [os.path.dirname(__file__)]
Brett Cannondd9a5692012-04-20 12:59:59 -040079 with self.assertRaises(SyntaxError):
80 imp.find_module('badsyntax_pep3120', path)
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020081
Guido van Rossum40d20bc2007-10-22 00:09:51 +000082 def test_issue1267(self):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000083 for mod, encoding, _ in self.test_strings:
84 fp, filename, info = imp.find_module('module_' + mod,
85 self.test_path)
Brett Cannon749afa92010-10-29 23:47:23 +000086 with fp:
87 self.assertNotEqual(fp, None)
88 self.assertEqual(fp.encoding, encoding)
89 self.assertEqual(fp.tell(), 0)
90 self.assertEqual(fp.readline(), '# test %s encoding\n'
91 % encoding)
Guido van Rossum40d20bc2007-10-22 00:09:51 +000092
93 fp, filename, info = imp.find_module("tokenize")
Brett Cannon749afa92010-10-29 23:47:23 +000094 with fp:
95 self.assertNotEqual(fp, None)
96 self.assertEqual(fp.encoding, "utf-8")
97 self.assertEqual(fp.tell(), 0)
98 self.assertEqual(fp.readline(),
99 '"""Tokenization help for Python programs.\n')
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000100
Brett Cannon8a9583e2008-09-04 05:04:25 +0000101 def test_issue3594(self):
102 temp_mod_name = 'test_imp_helper'
103 sys.path.insert(0, '.')
104 try:
105 with open(temp_mod_name + '.py', 'w') as file:
106 file.write("# coding: cp1252\nu = 'test.test_imp'\n")
107 file, filename, info = imp.find_module(temp_mod_name)
108 file.close()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000109 self.assertEqual(file.encoding, 'cp1252')
Brett Cannon8a9583e2008-09-04 05:04:25 +0000110 finally:
111 del sys.path[0]
112 support.unlink(temp_mod_name + '.py')
113 support.unlink(temp_mod_name + '.pyc')
114 support.unlink(temp_mod_name + '.pyo')
115
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000116 def test_issue5604(self):
117 # Test cannot cover imp.load_compiled function.
118 # Martin von Loewis note what shared library cannot have non-ascii
119 # character because init_xxx function cannot be compiled
120 # and issue never happens for dynamic modules.
121 # But sources modified to follow generic way for processing pathes.
122
Ezio Melotti435b5312010-03-06 01:20:49 +0000123 # the return encoding could be uppercase or None
124 fs_encoding = sys.getfilesystemencoding()
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000125
126 # covers utf-8 and Windows ANSI code pages
127 # one non-space symbol from every page
128 # (http://en.wikipedia.org/wiki/Code_page)
129 known_locales = {
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000130 'utf-8' : b'\xc3\xa4',
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000131 'cp1250' : b'\x8C',
132 'cp1251' : b'\xc0',
133 'cp1252' : b'\xc0',
134 'cp1253' : b'\xc1',
135 'cp1254' : b'\xc0',
136 'cp1255' : b'\xe0',
137 'cp1256' : b'\xe0',
138 'cp1257' : b'\xc0',
139 'cp1258' : b'\xc0',
140 }
141
Florent Xicluna21164ce2010-03-20 20:30:53 +0000142 if sys.platform == 'darwin':
143 self.assertEqual(fs_encoding, 'utf-8')
144 # Mac OS X uses the Normal Form D decomposition
145 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
146 special_char = b'a\xcc\x88'
147 else:
148 special_char = known_locales.get(fs_encoding)
149
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000150 if not special_char:
Ezio Melotti76e0d1a2010-03-05 15:08:19 +0000151 self.skipTest("can't run this test with %s as filesystem encoding"
152 % fs_encoding)
153 decoded_char = special_char.decode(fs_encoding)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000154 temp_mod_name = 'test_imp_helper_' + decoded_char
155 test_package_name = 'test_imp_helper_package_' + decoded_char
156 init_file_name = os.path.join(test_package_name, '__init__.py')
157 try:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000158 # if the curdir is not in sys.path the test fails when run with
159 # ./python ./Lib/test/regrtest.py test_imp
160 sys.path.insert(0, os.curdir)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000161 with open(temp_mod_name + '.py', 'w') as file:
162 file.write('a = 1\n')
163 file, filename, info = imp.find_module(temp_mod_name)
Brett Cannon749afa92010-10-29 23:47:23 +0000164 with file:
165 self.assertIsNotNone(file)
166 self.assertTrue(filename[:-3].endswith(temp_mod_name))
167 self.assertEqual(info[0], '.py')
Serhiy Storchaka6787a382013-11-23 22:12:06 +0200168 self.assertEqual(info[1], 'r')
Brett Cannon749afa92010-10-29 23:47:23 +0000169 self.assertEqual(info[2], imp.PY_SOURCE)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000170
Brett Cannon749afa92010-10-29 23:47:23 +0000171 mod = imp.load_module(temp_mod_name, file, filename, info)
172 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000173
Brett Cannonc0499522012-05-11 14:48:41 -0400174 with warnings.catch_warnings():
175 warnings.simplefilter('ignore')
176 mod = imp.load_source(temp_mod_name, temp_mod_name + '.py')
Ezio Melotti435b5312010-03-06 01:20:49 +0000177 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000178
Brett Cannonc0499522012-05-11 14:48:41 -0400179 with warnings.catch_warnings():
180 warnings.simplefilter('ignore')
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200181 if not sys.dont_write_bytecode:
182 mod = imp.load_compiled(
183 temp_mod_name,
184 imp.cache_from_source(temp_mod_name + '.py'))
Ezio Melotti435b5312010-03-06 01:20:49 +0000185 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000186
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000187 if not os.path.exists(test_package_name):
188 os.mkdir(test_package_name)
189 with open(init_file_name, 'w') as file:
190 file.write('b = 2\n')
Brett Cannonc0499522012-05-11 14:48:41 -0400191 with warnings.catch_warnings():
192 warnings.simplefilter('ignore')
193 package = imp.load_package(test_package_name, test_package_name)
Ezio Melotti435b5312010-03-06 01:20:49 +0000194 self.assertEqual(package.b, 2)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000195 finally:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000196 del sys.path[0]
Ezio Melotti435b5312010-03-06 01:20:49 +0000197 for ext in ('.py', '.pyc', '.pyo'):
198 support.unlink(temp_mod_name + ext)
199 support.unlink(init_file_name + ext)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000200 support.rmtree(test_package_name)
Victor Stinner047b7ae2014-10-05 17:37:41 +0200201 support.rmtree('__pycache__')
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000202
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200203 def test_issue9319(self):
Antoine Pitrou11846902011-04-25 21:39:49 +0200204 path = os.path.dirname(__file__)
Victor Stinner7fdd0fe2011-04-23 01:24:11 +0200205 self.assertRaises(SyntaxError,
Antoine Pitrou11846902011-04-25 21:39:49 +0200206 imp.find_module, "badsyntax_pep3120", [path])
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200207
Nick Coghlan91b9f132012-09-01 00:13:45 +1000208 def test_load_from_source(self):
209 # Verify that the imp module can correctly load and find .py files
210 # XXX (ncoghlan): It would be nice to use support.CleanImport
211 # here, but that breaks because the os module registers some
212 # handlers in copy_reg on import. Since CleanImport doesn't
213 # revert that registration, the module is left in a broken
214 # state after reversion. Reinitialising the module contents
215 # and just reverting os.environ to its previous state is an OK
216 # workaround
217 orig_path = os.path
218 orig_getenv = os.getenv
219 with support.EnvironmentVarGuard():
220 x = imp.find_module("os")
221 self.addCleanup(x[0].close)
222 new_os = imp.load_module("os", *x)
223 self.assertIs(os, new_os)
224 self.assertIs(orig_path, new_os.path)
225 self.assertIsNot(orig_getenv, new_os.getenv)
226
Brett Cannon130e4812013-05-03 10:54:23 -0400227 @requires_load_dynamic
Nick Coghlan91b9f132012-09-01 00:13:45 +1000228 def test_issue15828_load_extensions(self):
229 # Issue 15828 picked up that the adapter between the old imp API
230 # and importlib couldn't handle C extensions
231 example = "_heapq"
232 x = imp.find_module(example)
Brett Cannon848cdfd2012-08-31 11:31:20 -0400233 file_ = x[0]
234 if file_ is not None:
235 self.addCleanup(file_.close)
Nick Coghlan91b9f132012-09-01 00:13:45 +1000236 mod = imp.load_module(example, *x)
237 self.assertEqual(mod.__name__, example)
238
Brett Cannon130e4812013-05-03 10:54:23 -0400239 @requires_load_dynamic
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200240 def test_issue16421_multiple_modules_in_one_dll(self):
241 # Issue 16421: loading several modules from the same compiled file fails
242 m = '_testimportmultiple'
243 fileobj, pathname, description = imp.find_module(m)
244 fileobj.close()
245 mod0 = imp.load_dynamic(m, pathname)
Andrew Svetlovef9a43b2012-12-15 17:22:59 +0200246 mod1 = imp.load_dynamic('_testimportmultiple_foo', pathname)
247 mod2 = imp.load_dynamic('_testimportmultiple_bar', pathname)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200248 self.assertEqual(mod0.__name__, m)
Andrew Svetlovef9a43b2012-12-15 17:22:59 +0200249 self.assertEqual(mod1.__name__, '_testimportmultiple_foo')
250 self.assertEqual(mod2.__name__, '_testimportmultiple_bar')
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200251 with self.assertRaises(ImportError):
252 imp.load_dynamic('nonexistent', pathname)
253
Brett Cannon130e4812013-05-03 10:54:23 -0400254 @requires_load_dynamic
Brett Cannonf0434e62012-04-20 15:22:50 -0400255 def test_load_dynamic_ImportError_path(self):
256 # Issue #1559549 added `name` and `path` attributes to ImportError
257 # in order to provide better detail. Issue #10854 implemented those
258 # attributes on import failures of extensions on Windows.
259 path = 'bogus file path'
260 name = 'extension'
261 with self.assertRaises(ImportError) as err:
262 imp.load_dynamic(name, path)
263 self.assertIn(path, err.exception.path)
264 self.assertEqual(name, err.exception.name)
265
Brett Cannon130e4812013-05-03 10:54:23 -0400266 @requires_load_dynamic
Brett Cannon9d0f7722013-05-03 10:37:08 -0400267 def test_load_module_extension_file_is_None(self):
268 # When loading an extension module and the file is None, open one
269 # on the behalf of imp.load_dynamic().
270 # Issue #15902
Brett Cannon8772b182013-05-04 17:54:57 -0400271 name = '_testimportmultiple'
Brett Cannon9d0f7722013-05-03 10:37:08 -0400272 found = imp.find_module(name)
Benjamin Petersonaa6f6882013-05-11 16:29:03 -0500273 if found[0] is not None:
274 found[0].close()
Brett Cannon8772b182013-05-04 17:54:57 -0400275 if found[2][2] != imp.C_EXTENSION:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600276 self.skipTest("found module doesn't appear to be a C extension")
Brett Cannon9d0f7722013-05-03 10:37:08 -0400277 imp.load_module(name, None, *found[1:])
278
Brett Cannon997487d2013-06-07 13:26:53 -0400279 @unittest.skipIf(sys.dont_write_bytecode,
280 "test meaningful only when writing bytecode")
281 def test_bug7732(self):
Antoine Pitroubb2c45e2013-08-19 23:31:18 +0200282 with support.temp_cwd():
283 source = support.TESTFN + '.py'
284 os.mkdir(source)
Brett Cannon997487d2013-06-07 13:26:53 -0400285 self.assertRaisesRegex(ImportError, '^No module',
286 imp.find_module, support.TESTFN, ["."])
Brett Cannon330cc522013-08-23 12:10:09 -0400287
Brett Cannona4975a92013-08-23 11:45:57 -0400288 def test_multiple_calls_to_get_data(self):
289 # Issue #18755: make sure multiple calls to get_data() can succeed.
290 loader = imp._LoadSourceCompatibility('imp', imp.__file__,
291 open(imp.__file__))
292 loader.get_data(imp.__file__) # File should be closed
293 loader.get_data(imp.__file__) # Will need to create a newly opened file
Brett Cannon997487d2013-06-07 13:26:53 -0400294
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000295
Nick Coghlan6ead5522009-10-18 13:19:33 +0000296class ReloadTests(unittest.TestCase):
297
298 """Very basic tests to make sure that imp.reload() operates just like
299 reload()."""
300
301 def test_source(self):
Florent Xicluna97133722010-03-20 20:31:34 +0000302 # XXX (ncoghlan): It would be nice to use test.support.CleanImport
Nick Coghlan6ead5522009-10-18 13:19:33 +0000303 # here, but that breaks because the os module registers some
304 # handlers in copy_reg on import. Since CleanImport doesn't
305 # revert that registration, the module is left in a broken
306 # state after reversion. Reinitialising the module contents
307 # and just reverting os.environ to its previous state is an OK
308 # workaround
309 with support.EnvironmentVarGuard():
310 import os
311 imp.reload(os)
312
313 def test_extension(self):
314 with support.CleanImport('time'):
315 import time
316 imp.reload(time)
317
318 def test_builtin(self):
319 with support.CleanImport('marshal'):
320 import marshal
321 imp.reload(marshal)
Christian Heimes13a7a212008-01-07 17:13:09 +0000322
Ezio Melotti056bafe2013-08-10 19:59:36 +0300323 def test_with_deleted_parent(self):
324 # see #18681
325 from html import parser
Serhiy Storchakab2122912013-08-11 20:12:20 +0300326 html = sys.modules.pop('html')
327 def cleanup():
328 sys.modules['html'] = html
Ezio Melotti056bafe2013-08-10 19:59:36 +0300329 self.addCleanup(cleanup)
330 with self.assertRaisesRegex(ImportError, 'html'):
331 imp.reload(parser)
332
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000333
Barry Warsaw28a691b2010-04-17 00:19:56 +0000334class PEP3147Tests(unittest.TestCase):
335 """Tests of PEP 3147."""
336
337 tag = imp.get_tag()
338
Brett Cannon19a2f592012-07-09 13:58:07 -0400339 @unittest.skipUnless(sys.implementation.cache_tag is not None,
340 'requires sys.implementation.cache_tag not be None')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000341 def test_cache_from_source(self):
342 # Given the path to a .py file, return the path to its PEP 3147
343 # defined .pyc file (i.e. under __pycache__).
Brett Cannon410e88d2012-04-22 13:29:47 -0400344 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
345 expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
346 'qux.{}.pyc'.format(self.tag))
347 self.assertEqual(imp.cache_from_source(path, True), expect)
348
Brett Cannon19a2f592012-07-09 13:58:07 -0400349 def test_cache_from_source_no_cache_tag(self):
350 # Non cache tag means NotImplementedError.
351 with support.swap_attr(sys.implementation, 'cache_tag', None):
352 with self.assertRaises(NotImplementedError):
353 imp.cache_from_source('whatever.py')
354
Brett Cannon410e88d2012-04-22 13:29:47 -0400355 def test_cache_from_source_no_dot(self):
356 # Directory with a dot, filename without dot.
357 path = os.path.join('foo.bar', 'file')
358 expect = os.path.join('foo.bar', '__pycache__',
359 'file{}.pyc'.format(self.tag))
360 self.assertEqual(imp.cache_from_source(path, True), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000361
362 def test_cache_from_source_optimized(self):
363 # Given the path to a .py file, return the path to its PEP 3147
364 # defined .pyo file (i.e. under __pycache__).
Brett Cannon410e88d2012-04-22 13:29:47 -0400365 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
366 expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
367 'qux.{}.pyo'.format(self.tag))
368 self.assertEqual(imp.cache_from_source(path, False), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000369
370 def test_cache_from_source_cwd(self):
Brett Cannon410e88d2012-04-22 13:29:47 -0400371 path = 'foo.py'
372 expect = os.path.join('__pycache__', 'foo.{}.pyc'.format(self.tag))
373 self.assertEqual(imp.cache_from_source(path, True), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000374
375 def test_cache_from_source_override(self):
376 # When debug_override is not None, it can be any true-ish or false-ish
377 # value.
Brett Cannon410e88d2012-04-22 13:29:47 -0400378 path = os.path.join('foo', 'bar', 'baz.py')
379 partial_expect = os.path.join('foo', 'bar', '__pycache__',
380 'baz.{}.py'.format(self.tag))
381 self.assertEqual(imp.cache_from_source(path, []), partial_expect + 'o')
382 self.assertEqual(imp.cache_from_source(path, [17]),
383 partial_expect + 'c')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000384 # However if the bool-ishness can't be determined, the exception
385 # propagates.
386 class Bearish:
387 def __bool__(self): raise RuntimeError
Brett Cannon410e88d2012-04-22 13:29:47 -0400388 with self.assertRaises(RuntimeError):
389 imp.cache_from_source('/foo/bar/baz.py', Bearish())
Barry Warsaw28a691b2010-04-17 00:19:56 +0000390
Brett Cannon410e88d2012-04-22 13:29:47 -0400391 @unittest.skipUnless(os.sep == '\\' and os.altsep == '/',
Barry Warsaw28a691b2010-04-17 00:19:56 +0000392 'test meaningful only where os.altsep is defined')
393 def test_sep_altsep_and_sep_cache_from_source(self):
394 # Windows path and PEP 3147 where sep is right of altsep.
395 self.assertEqual(
396 imp.cache_from_source('\\foo\\bar\\baz/qux.py', True),
Brett Cannon410e88d2012-04-22 13:29:47 -0400397 '\\foo\\bar\\baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000398
Brett Cannon19a2f592012-07-09 13:58:07 -0400399 @unittest.skipUnless(sys.implementation.cache_tag is not None,
400 'requires sys.implementation.cache_tag to not be '
401 'None')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000402 def test_source_from_cache(self):
403 # Given the path to a PEP 3147 defined .pyc file, return the path to
404 # its source. This tests the good path.
Brett Cannon410e88d2012-04-22 13:29:47 -0400405 path = os.path.join('foo', 'bar', 'baz', '__pycache__',
406 'qux.{}.pyc'.format(self.tag))
407 expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
408 self.assertEqual(imp.source_from_cache(path), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000409
Brett Cannon19a2f592012-07-09 13:58:07 -0400410 def test_source_from_cache_no_cache_tag(self):
411 # If sys.implementation.cache_tag is None, raise NotImplementedError.
412 path = os.path.join('blah', '__pycache__', 'whatever.pyc')
413 with support.swap_attr(sys.implementation, 'cache_tag', None):
414 with self.assertRaises(NotImplementedError):
415 imp.source_from_cache(path)
416
Barry Warsaw28a691b2010-04-17 00:19:56 +0000417 def test_source_from_cache_bad_path(self):
418 # When the path to a pyc file is not in PEP 3147 format, a ValueError
419 # is raised.
420 self.assertRaises(
421 ValueError, imp.source_from_cache, '/foo/bar/bazqux.pyc')
422
423 def test_source_from_cache_no_slash(self):
424 # No slashes at all in path -> ValueError
425 self.assertRaises(
426 ValueError, imp.source_from_cache, 'foo.cpython-32.pyc')
427
428 def test_source_from_cache_too_few_dots(self):
429 # Too few dots in final path component -> ValueError
430 self.assertRaises(
431 ValueError, imp.source_from_cache, '__pycache__/foo.pyc')
432
433 def test_source_from_cache_too_many_dots(self):
434 # Too many dots in final path component -> ValueError
435 self.assertRaises(
436 ValueError, imp.source_from_cache,
437 '__pycache__/foo.cpython-32.foo.pyc')
438
439 def test_source_from_cache_no__pycache__(self):
440 # Another problem with the path -> ValueError
441 self.assertRaises(
442 ValueError, imp.source_from_cache,
443 '/foo/bar/foo.cpython-32.foo.pyc')
444
445 def test_package___file__(self):
Antoine Pitrou06e37582012-06-23 17:27:56 +0200446 try:
447 m = __import__('pep3147')
448 except ImportError:
449 pass
450 else:
451 self.fail("pep3147 module already exists: %r" % (m,))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000452 # Test that a package's __file__ points to the right source directory.
453 os.mkdir('pep3147')
454 sys.path.insert(0, os.curdir)
455 def cleanup():
456 if sys.path[0] == os.curdir:
457 del sys.path[0]
458 shutil.rmtree('pep3147')
459 self.addCleanup(cleanup)
460 # Touch the __init__.py file.
Victor Stinnerbf816222011-06-30 23:25:47 +0200461 support.create_empty_file('pep3147/__init__.py')
Antoine Pitrou4f92a682012-02-26 18:09:50 +0100462 importlib.invalidate_caches()
Antoine Pitrouabe72d72012-02-22 01:11:31 +0100463 expected___file__ = os.sep.join(('.', 'pep3147', '__init__.py'))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000464 m = __import__('pep3147')
Antoine Pitrou9a4d7dd2012-02-27 22:01:25 +0100465 self.assertEqual(m.__file__, expected___file__, (m.__file__, m.__path__, sys.path, sys.path_importer_cache))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000466 # Ensure we load the pyc file.
Antoine Pitrou037615e2012-02-22 02:30:09 +0100467 support.unload('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000468 m = __import__('pep3147')
Antoine Pitrou037615e2012-02-22 02:30:09 +0100469 support.unload('pep3147')
Antoine Pitrou9a4d7dd2012-02-27 22:01:25 +0100470 self.assertEqual(m.__file__, expected___file__, (m.__file__, m.__path__, sys.path, sys.path_importer_cache))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000471
472
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000473class NullImporterTests(unittest.TestCase):
Victor Stinner09c449c2010-08-13 22:23:24 +0000474 @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000475 "Need an undecodeable filename")
476 def test_unencodeable(self):
Victor Stinner09c449c2010-08-13 22:23:24 +0000477 name = support.TESTFN_UNENCODABLE
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000478 os.mkdir(name)
479 try:
480 self.assertRaises(ImportError, imp.NullImporter, name)
481 finally:
482 os.rmdir(name)
483
484
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000485if __name__ == "__main__":
Brett Cannon95ea11f2013-05-03 10:57:08 -0400486 unittest.main()