blob: a115e60d4e4f088a05adcc12cfe2a2550c74d200 [file] [log] [blame]
Brett Cannonc0499522012-05-11 14:48:41 -04001import importlib
Nick Coghlan9d3c61c2015-09-05 21:05:05 +10002import importlib.util
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003import os
4import os.path
Brett Cannon8a9583e2008-09-04 05:04:25 +00005import sys
Benjamin Petersonee8712c2008-05-20 21:35:26 +00006from test import support
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08007from test.support import script_helper
Brett Cannonc0499522012-05-11 14:48:41 -04008import unittest
9import warnings
Brett Cannone4f41de2013-06-16 13:13:40 -040010with warnings.catch_warnings():
Brett Cannon213b4052015-10-30 14:41:06 -070011 warnings.simplefilter('ignore', DeprecationWarning)
Brett Cannone4f41de2013-06-16 13:13:40 -040012 import imp
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080013import _imp
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
Thomas Wouters89f507f2006-12-13 04:49:30 +000024class LockTests(unittest.TestCase):
Tim Peters579bed72003-04-26 14:31:24 +000025
Thomas Wouters89f507f2006-12-13 04:49:30 +000026 """Very basic test of import lock functions."""
Tim Peters579bed72003-04-26 14:31:24 +000027
Thomas Wouters89f507f2006-12-13 04:49:30 +000028 def verify_lock_state(self, expected):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000029 self.assertEqual(imp.lock_held(), expected,
Thomas Wouters89f507f2006-12-13 04:49:30 +000030 "expected imp.lock_held() to be %r" % expected)
31 def testLock(self):
32 LOOPS = 50
Tim Peters579bed72003-04-26 14:31:24 +000033
Thomas Wouters89f507f2006-12-13 04:49:30 +000034 # The import lock may already be held, e.g. if the test suite is run
35 # via "import test.autotest".
36 lock_held_at_start = imp.lock_held()
37 self.verify_lock_state(lock_held_at_start)
Tim Peters579bed72003-04-26 14:31:24 +000038
Thomas Wouters89f507f2006-12-13 04:49:30 +000039 for i in range(LOOPS):
40 imp.acquire_lock()
41 self.verify_lock_state(True)
Tim Peters579bed72003-04-26 14:31:24 +000042
Thomas Wouters89f507f2006-12-13 04:49:30 +000043 for i in range(LOOPS):
Neal Norwitz2294c0d2003-02-12 23:02:21 +000044 imp.release_lock()
Thomas Wouters89f507f2006-12-13 04:49:30 +000045
46 # The original state should be restored now.
47 self.verify_lock_state(lock_held_at_start)
48
49 if not lock_held_at_start:
50 try:
51 imp.release_lock()
52 except RuntimeError:
53 pass
54 else:
55 self.fail("release_lock() without lock should raise "
56 "RuntimeError")
Neal Norwitz2294c0d2003-02-12 23:02:21 +000057
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058class ImportTests(unittest.TestCase):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000059 def setUp(self):
60 mod = importlib.import_module('test.encoded_modules')
61 self.test_strings = mod.test_strings
62 self.test_path = mod.__path__
63
64 def test_import_encoded_module(self):
65 for modname, encoding, teststr in self.test_strings:
66 mod = importlib.import_module('test.encoded_modules.'
67 'module_' + modname)
68 self.assertEqual(teststr, mod.test)
Guido van Rossumce3a72a2007-10-19 23:16:50 +000069
70 def test_find_module_encoding(self):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000071 for mod, encoding, _ in self.test_strings:
Brett Cannon749afa92010-10-29 23:47:23 +000072 with imp.find_module('module_' + mod, self.test_path)[0] as fd:
73 self.assertEqual(fd.encoding, encoding)
Guido van Rossumce3a72a2007-10-19 23:16:50 +000074
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020075 path = [os.path.dirname(__file__)]
Brett Cannondd9a5692012-04-20 12:59:59 -040076 with self.assertRaises(SyntaxError):
77 imp.find_module('badsyntax_pep3120', path)
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020078
Guido van Rossum40d20bc2007-10-22 00:09:51 +000079 def test_issue1267(self):
Alexander Belopolskye8f58322010-10-15 16:28:20 +000080 for mod, encoding, _ in self.test_strings:
81 fp, filename, info = imp.find_module('module_' + mod,
82 self.test_path)
Brett Cannon749afa92010-10-29 23:47:23 +000083 with fp:
84 self.assertNotEqual(fp, None)
85 self.assertEqual(fp.encoding, encoding)
86 self.assertEqual(fp.tell(), 0)
87 self.assertEqual(fp.readline(), '# test %s encoding\n'
88 % encoding)
Guido van Rossum40d20bc2007-10-22 00:09:51 +000089
90 fp, filename, info = imp.find_module("tokenize")
Brett Cannon749afa92010-10-29 23:47:23 +000091 with fp:
92 self.assertNotEqual(fp, None)
93 self.assertEqual(fp.encoding, "utf-8")
94 self.assertEqual(fp.tell(), 0)
95 self.assertEqual(fp.readline(),
96 '"""Tokenization help for Python programs.\n')
Guido van Rossum40d20bc2007-10-22 00:09:51 +000097
Brett Cannon8a9583e2008-09-04 05:04:25 +000098 def test_issue3594(self):
99 temp_mod_name = 'test_imp_helper'
100 sys.path.insert(0, '.')
101 try:
102 with open(temp_mod_name + '.py', 'w') as file:
103 file.write("# coding: cp1252\nu = 'test.test_imp'\n")
104 file, filename, info = imp.find_module(temp_mod_name)
105 file.close()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000106 self.assertEqual(file.encoding, 'cp1252')
Brett Cannon8a9583e2008-09-04 05:04:25 +0000107 finally:
108 del sys.path[0]
109 support.unlink(temp_mod_name + '.py')
110 support.unlink(temp_mod_name + '.pyc')
Brett Cannon8a9583e2008-09-04 05:04:25 +0000111
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000112 def test_issue5604(self):
113 # Test cannot cover imp.load_compiled function.
114 # Martin von Loewis note what shared library cannot have non-ascii
115 # character because init_xxx function cannot be compiled
116 # and issue never happens for dynamic modules.
luzpaza5293b42017-11-05 07:37:50 -0600117 # But sources modified to follow generic way for processing paths.
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000118
Ezio Melotti435b5312010-03-06 01:20:49 +0000119 # the return encoding could be uppercase or None
120 fs_encoding = sys.getfilesystemencoding()
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000121
122 # covers utf-8 and Windows ANSI code pages
123 # one non-space symbol from every page
124 # (http://en.wikipedia.org/wiki/Code_page)
125 known_locales = {
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000126 'utf-8' : b'\xc3\xa4',
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000127 'cp1250' : b'\x8C',
128 'cp1251' : b'\xc0',
129 'cp1252' : b'\xc0',
130 'cp1253' : b'\xc1',
131 'cp1254' : b'\xc0',
132 'cp1255' : b'\xe0',
133 'cp1256' : b'\xe0',
134 'cp1257' : b'\xc0',
135 'cp1258' : b'\xc0',
136 }
137
Florent Xicluna21164ce2010-03-20 20:30:53 +0000138 if sys.platform == 'darwin':
139 self.assertEqual(fs_encoding, 'utf-8')
140 # Mac OS X uses the Normal Form D decomposition
141 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
142 special_char = b'a\xcc\x88'
143 else:
144 special_char = known_locales.get(fs_encoding)
145
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000146 if not special_char:
Ezio Melotti76e0d1a2010-03-05 15:08:19 +0000147 self.skipTest("can't run this test with %s as filesystem encoding"
148 % fs_encoding)
149 decoded_char = special_char.decode(fs_encoding)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000150 temp_mod_name = 'test_imp_helper_' + decoded_char
151 test_package_name = 'test_imp_helper_package_' + decoded_char
152 init_file_name = os.path.join(test_package_name, '__init__.py')
153 try:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000154 # if the curdir is not in sys.path the test fails when run with
155 # ./python ./Lib/test/regrtest.py test_imp
156 sys.path.insert(0, os.curdir)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000157 with open(temp_mod_name + '.py', 'w') as file:
158 file.write('a = 1\n')
159 file, filename, info = imp.find_module(temp_mod_name)
Brett Cannon749afa92010-10-29 23:47:23 +0000160 with file:
161 self.assertIsNotNone(file)
162 self.assertTrue(filename[:-3].endswith(temp_mod_name))
163 self.assertEqual(info[0], '.py')
Serhiy Storchaka6787a382013-11-23 22:12:06 +0200164 self.assertEqual(info[1], 'r')
Brett Cannon749afa92010-10-29 23:47:23 +0000165 self.assertEqual(info[2], imp.PY_SOURCE)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000166
Brett Cannon749afa92010-10-29 23:47:23 +0000167 mod = imp.load_module(temp_mod_name, file, filename, info)
168 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000169
Brett Cannonc0499522012-05-11 14:48:41 -0400170 with warnings.catch_warnings():
171 warnings.simplefilter('ignore')
172 mod = imp.load_source(temp_mod_name, temp_mod_name + '.py')
Ezio Melotti435b5312010-03-06 01:20:49 +0000173 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000174
Brett Cannonc0499522012-05-11 14:48:41 -0400175 with warnings.catch_warnings():
176 warnings.simplefilter('ignore')
Ezio Melottie5e7a7c2013-03-16 21:49:20 +0200177 if not sys.dont_write_bytecode:
178 mod = imp.load_compiled(
179 temp_mod_name,
180 imp.cache_from_source(temp_mod_name + '.py'))
Ezio Melotti435b5312010-03-06 01:20:49 +0000181 self.assertEqual(mod.a, 1)
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000182
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000183 if not os.path.exists(test_package_name):
184 os.mkdir(test_package_name)
185 with open(init_file_name, 'w') as file:
186 file.write('b = 2\n')
Brett Cannonc0499522012-05-11 14:48:41 -0400187 with warnings.catch_warnings():
188 warnings.simplefilter('ignore')
189 package = imp.load_package(test_package_name, test_package_name)
Ezio Melotti435b5312010-03-06 01:20:49 +0000190 self.assertEqual(package.b, 2)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000191 finally:
Ezio Melotti41a6b042010-03-06 01:50:25 +0000192 del sys.path[0]
Brett Cannonf299abd2015-04-13 14:21:02 -0400193 for ext in ('.py', '.pyc'):
Ezio Melotti435b5312010-03-06 01:20:49 +0000194 support.unlink(temp_mod_name + ext)
195 support.unlink(init_file_name + ext)
Ezio Melotti9a7d5ac2010-03-05 12:43:17 +0000196 support.rmtree(test_package_name)
Victor Stinner047b7ae2014-10-05 17:37:41 +0200197 support.rmtree('__pycache__')
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000198
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200199 def test_issue9319(self):
Antoine Pitrou11846902011-04-25 21:39:49 +0200200 path = os.path.dirname(__file__)
Victor Stinner7fdd0fe2011-04-23 01:24:11 +0200201 self.assertRaises(SyntaxError,
Antoine Pitrou11846902011-04-25 21:39:49 +0200202 imp.find_module, "badsyntax_pep3120", [path])
Victor Stinnerc68b6aa2011-04-23 00:41:19 +0200203
Nick Coghlan91b9f132012-09-01 00:13:45 +1000204 def test_load_from_source(self):
205 # Verify that the imp module can correctly load and find .py files
206 # XXX (ncoghlan): It would be nice to use support.CleanImport
207 # here, but that breaks because the os module registers some
208 # handlers in copy_reg on import. Since CleanImport doesn't
209 # revert that registration, the module is left in a broken
210 # state after reversion. Reinitialising the module contents
211 # and just reverting os.environ to its previous state is an OK
212 # workaround
213 orig_path = os.path
214 orig_getenv = os.getenv
215 with support.EnvironmentVarGuard():
216 x = imp.find_module("os")
217 self.addCleanup(x[0].close)
218 new_os = imp.load_module("os", *x)
219 self.assertIs(os, new_os)
220 self.assertIs(orig_path, new_os.path)
221 self.assertIsNot(orig_getenv, new_os.getenv)
222
Brett Cannon130e4812013-05-03 10:54:23 -0400223 @requires_load_dynamic
Nick Coghlan91b9f132012-09-01 00:13:45 +1000224 def test_issue15828_load_extensions(self):
225 # Issue 15828 picked up that the adapter between the old imp API
226 # and importlib couldn't handle C extensions
227 example = "_heapq"
228 x = imp.find_module(example)
Brett Cannon848cdfd2012-08-31 11:31:20 -0400229 file_ = x[0]
230 if file_ is not None:
231 self.addCleanup(file_.close)
Nick Coghlan91b9f132012-09-01 00:13:45 +1000232 mod = imp.load_module(example, *x)
233 self.assertEqual(mod.__name__, example)
234
Brett Cannon130e4812013-05-03 10:54:23 -0400235 @requires_load_dynamic
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200236 def test_issue16421_multiple_modules_in_one_dll(self):
237 # Issue 16421: loading several modules from the same compiled file fails
238 m = '_testimportmultiple'
239 fileobj, pathname, description = imp.find_module(m)
240 fileobj.close()
241 mod0 = imp.load_dynamic(m, pathname)
Andrew Svetlovef9a43b2012-12-15 17:22:59 +0200242 mod1 = imp.load_dynamic('_testimportmultiple_foo', pathname)
243 mod2 = imp.load_dynamic('_testimportmultiple_bar', pathname)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200244 self.assertEqual(mod0.__name__, m)
Andrew Svetlovef9a43b2012-12-15 17:22:59 +0200245 self.assertEqual(mod1.__name__, '_testimportmultiple_foo')
246 self.assertEqual(mod2.__name__, '_testimportmultiple_bar')
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200247 with self.assertRaises(ImportError):
248 imp.load_dynamic('nonexistent', pathname)
249
Brett Cannon130e4812013-05-03 10:54:23 -0400250 @requires_load_dynamic
Brett Cannonf0434e62012-04-20 15:22:50 -0400251 def test_load_dynamic_ImportError_path(self):
252 # Issue #1559549 added `name` and `path` attributes to ImportError
253 # in order to provide better detail. Issue #10854 implemented those
254 # attributes on import failures of extensions on Windows.
255 path = 'bogus file path'
256 name = 'extension'
257 with self.assertRaises(ImportError) as err:
258 imp.load_dynamic(name, path)
259 self.assertIn(path, err.exception.path)
260 self.assertEqual(name, err.exception.name)
261
Brett Cannon130e4812013-05-03 10:54:23 -0400262 @requires_load_dynamic
Brett Cannon9d0f7722013-05-03 10:37:08 -0400263 def test_load_module_extension_file_is_None(self):
264 # When loading an extension module and the file is None, open one
265 # on the behalf of imp.load_dynamic().
266 # Issue #15902
Brett Cannon8772b182013-05-04 17:54:57 -0400267 name = '_testimportmultiple'
Brett Cannon9d0f7722013-05-03 10:37:08 -0400268 found = imp.find_module(name)
Benjamin Petersonaa6f6882013-05-11 16:29:03 -0500269 if found[0] is not None:
270 found[0].close()
Brett Cannon8772b182013-05-04 17:54:57 -0400271 if found[2][2] != imp.C_EXTENSION:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600272 self.skipTest("found module doesn't appear to be a C extension")
Brett Cannon9d0f7722013-05-03 10:37:08 -0400273 imp.load_module(name, None, *found[1:])
274
Nick Coghlan9d3c61c2015-09-05 21:05:05 +1000275 @requires_load_dynamic
276 def test_issue24748_load_module_skips_sys_modules_check(self):
277 name = 'test.imp_dummy'
278 try:
279 del sys.modules[name]
280 except KeyError:
281 pass
282 try:
283 module = importlib.import_module(name)
284 spec = importlib.util.find_spec('_testmultiphase')
285 module = imp.load_dynamic(name, spec.origin)
286 self.assertEqual(module.__name__, name)
287 self.assertEqual(module.__spec__.name, name)
288 self.assertEqual(module.__spec__.origin, spec.origin)
289 self.assertRaises(AttributeError, getattr, module, 'dummy_name')
290 self.assertEqual(module.int_const, 1969)
291 self.assertIs(sys.modules[name], module)
292 finally:
293 try:
294 del sys.modules[name]
295 except KeyError:
296 pass
297
Brett Cannon997487d2013-06-07 13:26:53 -0400298 @unittest.skipIf(sys.dont_write_bytecode,
299 "test meaningful only when writing bytecode")
300 def test_bug7732(self):
Antoine Pitroubb2c45e2013-08-19 23:31:18 +0200301 with support.temp_cwd():
302 source = support.TESTFN + '.py'
303 os.mkdir(source)
Brett Cannon997487d2013-06-07 13:26:53 -0400304 self.assertRaisesRegex(ImportError, '^No module',
305 imp.find_module, support.TESTFN, ["."])
Brett Cannon330cc522013-08-23 12:10:09 -0400306
Brett Cannona4975a92013-08-23 11:45:57 -0400307 def test_multiple_calls_to_get_data(self):
308 # Issue #18755: make sure multiple calls to get_data() can succeed.
309 loader = imp._LoadSourceCompatibility('imp', imp.__file__,
310 open(imp.__file__))
311 loader.get_data(imp.__file__) # File should be closed
312 loader.get_data(imp.__file__) # Will need to create a newly opened file
Brett Cannon997487d2013-06-07 13:26:53 -0400313
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300314 def test_load_source(self):
Victor Stinnera505ecd2017-10-13 13:47:49 -0700315 # Create a temporary module since load_source(name) modifies
316 # sys.modules[name] attributes like __loader___
317 modname = f"tmp{__name__}"
318 mod = type(sys.modules[__name__])(modname)
319 with support.swap_item(sys.modules, modname, mod):
320 with self.assertRaisesRegex(ValueError, 'embedded null'):
321 imp.load_source(modname, __file__ + "\0")
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300322
Oren Milman9974e1b2017-09-19 14:39:47 +0300323 @support.cpython_only
324 def test_issue31315(self):
325 # There shouldn't be an assertion failure in imp.create_dynamic(),
326 # when spec.name is not a string.
327 create_dynamic = support.get_attribute(imp, 'create_dynamic')
328 class BadSpec:
329 name = None
330 origin = 'foo'
331 with self.assertRaises(TypeError):
332 create_dynamic(BadSpec())
333
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800334 def test_source_hash(self):
335 self.assertEqual(_imp.source_hash(42, b'hi'), b'\xc6\xe7Z\r\x03:}\xab')
336 self.assertEqual(_imp.source_hash(43, b'hi'), b'\x85\x9765\xf8\x9a\x8b9')
337
338 def test_pyc_invalidation_mode_from_cmdline(self):
339 cases = [
340 ([], "default"),
341 (["--check-hash-based-pycs", "default"], "default"),
342 (["--check-hash-based-pycs", "always"], "always"),
343 (["--check-hash-based-pycs", "never"], "never"),
344 ]
345 for interp_args, expected in cases:
346 args = interp_args + [
347 "-c",
348 "import _imp; print(_imp.check_hash_based_pycs)",
349 ]
350 res = script_helper.assert_python_ok(*args)
351 self.assertEqual(res.out.strip().decode('utf-8'), expected)
352
Guido van Rossum0ad59d42009-03-30 22:01:35 +0000353
Nick Coghlan6ead5522009-10-18 13:19:33 +0000354class ReloadTests(unittest.TestCase):
355
356 """Very basic tests to make sure that imp.reload() operates just like
357 reload()."""
358
359 def test_source(self):
Florent Xicluna97133722010-03-20 20:31:34 +0000360 # XXX (ncoghlan): It would be nice to use test.support.CleanImport
Nick Coghlan6ead5522009-10-18 13:19:33 +0000361 # here, but that breaks because the os module registers some
362 # handlers in copy_reg on import. Since CleanImport doesn't
363 # revert that registration, the module is left in a broken
364 # state after reversion. Reinitialising the module contents
365 # and just reverting os.environ to its previous state is an OK
366 # workaround
367 with support.EnvironmentVarGuard():
368 import os
369 imp.reload(os)
370
371 def test_extension(self):
372 with support.CleanImport('time'):
373 import time
374 imp.reload(time)
375
376 def test_builtin(self):
377 with support.CleanImport('marshal'):
378 import marshal
379 imp.reload(marshal)
Christian Heimes13a7a212008-01-07 17:13:09 +0000380
Ezio Melotti056bafe2013-08-10 19:59:36 +0300381 def test_with_deleted_parent(self):
382 # see #18681
383 from html import parser
Serhiy Storchakab2122912013-08-11 20:12:20 +0300384 html = sys.modules.pop('html')
385 def cleanup():
386 sys.modules['html'] = html
Ezio Melotti056bafe2013-08-10 19:59:36 +0300387 self.addCleanup(cleanup)
388 with self.assertRaisesRegex(ImportError, 'html'):
389 imp.reload(parser)
390
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000391
Barry Warsaw28a691b2010-04-17 00:19:56 +0000392class PEP3147Tests(unittest.TestCase):
393 """Tests of PEP 3147."""
394
395 tag = imp.get_tag()
396
Brett Cannon19a2f592012-07-09 13:58:07 -0400397 @unittest.skipUnless(sys.implementation.cache_tag is not None,
398 'requires sys.implementation.cache_tag not be None')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000399 def test_cache_from_source(self):
400 # Given the path to a .py file, return the path to its PEP 3147
401 # defined .pyc file (i.e. under __pycache__).
Brett Cannon410e88d2012-04-22 13:29:47 -0400402 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
403 expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
404 'qux.{}.pyc'.format(self.tag))
405 self.assertEqual(imp.cache_from_source(path, True), expect)
406
Brett Cannon19a2f592012-07-09 13:58:07 -0400407 @unittest.skipUnless(sys.implementation.cache_tag is not None,
408 'requires sys.implementation.cache_tag to not be '
409 'None')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000410 def test_source_from_cache(self):
411 # Given the path to a PEP 3147 defined .pyc file, return the path to
412 # its source. This tests the good path.
Brett Cannon410e88d2012-04-22 13:29:47 -0400413 path = os.path.join('foo', 'bar', 'baz', '__pycache__',
414 'qux.{}.pyc'.format(self.tag))
415 expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
416 self.assertEqual(imp.source_from_cache(path), expect)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000417
Barry Warsaw28a691b2010-04-17 00:19:56 +0000418
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000419class NullImporterTests(unittest.TestCase):
Victor Stinner09c449c2010-08-13 22:23:24 +0000420 @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000421 "Need an undecodeable filename")
422 def test_unencodeable(self):
Victor Stinner09c449c2010-08-13 22:23:24 +0000423 name = support.TESTFN_UNENCODABLE
Victor Stinner1a4d12d2010-08-13 13:07:29 +0000424 os.mkdir(name)
425 try:
426 self.assertRaises(ImportError, imp.NullImporter, name)
427 finally:
428 os.rmdir(name)
429
430
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000431if __name__ == "__main__":
Brett Cannon95ea11f2013-05-03 10:57:08 -0400432 unittest.main()