blob: bf9722a229611de7d4e2bf4a97941ac56ce12911 [file] [log] [blame]
Hai Shi96a6a6d2020-07-09 21:25:10 +08001from test.support import run_unittest
2from test.support.import_helper import unload, CleanImport
3from test.support.warnings_helper import check_warnings
Christian Heimesdae2a892008-04-19 00:55:37 +00004import unittest
5import sys
Nick Coghlanc4e0d982013-04-14 22:30:42 +10006import importlib
Eric Snow37148b22014-01-04 15:09:53 -07007from importlib.util import spec_from_file_location
Christian Heimesdae2a892008-04-19 00:55:37 +00008import pkgutil
9import os
10import os.path
11import tempfile
12import shutil
13import zipfile
14
Nick Coghlan8ecf5042012-07-15 21:19:18 +100015# Note: pkgutil.walk_packages is currently tested in test_runpy. This is
16# a hack to get a major issue resolved for 3.3b2. Longer term, it should
17# be moved back here, perhaps by factoring out the helper code for
18# creating interesting package layouts to a separate module.
19# Issue #15348 declares this is indeed a dodgy hack ;)
Christian Heimesdae2a892008-04-19 00:55:37 +000020
21class PkgutilTests(unittest.TestCase):
22
23 def setUp(self):
24 self.dirname = tempfile.mkdtemp()
Ned Deily7010a072011-10-07 12:01:40 -070025 self.addCleanup(shutil.rmtree, self.dirname)
Christian Heimesdae2a892008-04-19 00:55:37 +000026 sys.path.insert(0, self.dirname)
27
28 def tearDown(self):
29 del sys.path[0]
Christian Heimesdae2a892008-04-19 00:55:37 +000030
31 def test_getdata_filesys(self):
32 pkg = 'test_getdata_filesys'
33
34 # Include a LF and a CRLF, to test that binary data is read back
35 RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line'
36
37 # Make a package with some resources
38 package_dir = os.path.join(self.dirname, pkg)
39 os.mkdir(package_dir)
40 # Empty init.py
41 f = open(os.path.join(package_dir, '__init__.py'), "wb")
42 f.close()
43 # Resource files, res.txt, sub/res.txt
44 f = open(os.path.join(package_dir, 'res.txt'), "wb")
45 f.write(RESOURCE_DATA)
46 f.close()
47 os.mkdir(os.path.join(package_dir, 'sub'))
48 f = open(os.path.join(package_dir, 'sub', 'res.txt'), "wb")
49 f.write(RESOURCE_DATA)
50 f.close()
51
52 # Check we can read the resources
53 res1 = pkgutil.get_data(pkg, 'res.txt')
54 self.assertEqual(res1, RESOURCE_DATA)
55 res2 = pkgutil.get_data(pkg, 'sub/res.txt')
56 self.assertEqual(res2, RESOURCE_DATA)
57
58 del sys.modules[pkg]
59
60 def test_getdata_zipfile(self):
61 zip = 'test_getdata_zipfile.zip'
62 pkg = 'test_getdata_zipfile'
63
64 # Include a LF and a CRLF, to test that binary data is read back
65 RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line'
66
67 # Make a package with some resources
68 zip_file = os.path.join(self.dirname, zip)
69 z = zipfile.ZipFile(zip_file, 'w')
70
71 # Empty init.py
72 z.writestr(pkg + '/__init__.py', "")
73 # Resource files, res.txt, sub/res.txt
74 z.writestr(pkg + '/res.txt', RESOURCE_DATA)
75 z.writestr(pkg + '/sub/res.txt', RESOURCE_DATA)
76 z.close()
77
78 # Check we can read the resources
79 sys.path.insert(0, zip_file)
80 res1 = pkgutil.get_data(pkg, 'res.txt')
81 self.assertEqual(res1, RESOURCE_DATA)
82 res2 = pkgutil.get_data(pkg, 'sub/res.txt')
83 self.assertEqual(res2, RESOURCE_DATA)
Alexandre Vassalotti515a74f2009-07-05 06:42:44 +000084
85 names = []
Eric Snowd5f92232016-09-07 18:37:17 -070086 for moduleinfo in pkgutil.iter_modules([zip_file]):
87 self.assertIsInstance(moduleinfo, pkgutil.ModuleInfo)
88 names.append(moduleinfo.name)
Alexandre Vassalotti515a74f2009-07-05 06:42:44 +000089 self.assertEqual(names, ['test_getdata_zipfile'])
90
Christian Heimesdae2a892008-04-19 00:55:37 +000091 del sys.path[0]
92
93 del sys.modules[pkg]
94
Ned Deilycaf5a222011-10-06 14:19:06 -070095 def test_unreadable_dir_on_syspath(self):
96 # issue7367 - walk_packages failed if unreadable dir on sys.path
97 package_name = "unreadable_package"
98 d = os.path.join(self.dirname, package_name)
99 # this does not appear to create an unreadable dir on Windows
100 # but the test should not fail anyway
101 os.mkdir(d, 0)
Ned Deily7010a072011-10-07 12:01:40 -0700102 self.addCleanup(os.rmdir, d)
Ned Deilycaf5a222011-10-06 14:19:06 -0700103 for t in pkgutil.walk_packages(path=[self.dirname]):
104 self.fail("unexpected package found")
Ned Deilycaf5a222011-10-06 14:19:06 -0700105
Łukasz Langa0d18c152016-06-11 18:02:46 -0700106 def test_walkpackages_filesys(self):
107 pkg1 = 'test_walkpackages_filesys'
108 pkg1_dir = os.path.join(self.dirname, pkg1)
109 os.mkdir(pkg1_dir)
110 f = open(os.path.join(pkg1_dir, '__init__.py'), "wb")
111 f.close()
112 os.mkdir(os.path.join(pkg1_dir, 'sub'))
113 f = open(os.path.join(pkg1_dir, 'sub', '__init__.py'), "wb")
114 f.close()
115 f = open(os.path.join(pkg1_dir, 'sub', 'mod.py'), "wb")
116 f.close()
117
118 # Now, to juice it up, let's add the opposite packages, too.
119 pkg2 = 'sub'
120 pkg2_dir = os.path.join(self.dirname, pkg2)
121 os.mkdir(pkg2_dir)
122 f = open(os.path.join(pkg2_dir, '__init__.py'), "wb")
123 f.close()
124 os.mkdir(os.path.join(pkg2_dir, 'test_walkpackages_filesys'))
125 f = open(os.path.join(pkg2_dir, 'test_walkpackages_filesys', '__init__.py'), "wb")
126 f.close()
127 f = open(os.path.join(pkg2_dir, 'test_walkpackages_filesys', 'mod.py'), "wb")
128 f.close()
129
130 expected = [
131 'sub',
132 'sub.test_walkpackages_filesys',
133 'sub.test_walkpackages_filesys.mod',
134 'test_walkpackages_filesys',
135 'test_walkpackages_filesys.sub',
136 'test_walkpackages_filesys.sub.mod',
137 ]
138 actual= [e[1] for e in pkgutil.walk_packages([self.dirname])]
139 self.assertEqual(actual, expected)
140
141 for pkg in expected:
142 if pkg.endswith('mod'):
143 continue
144 del sys.modules[pkg]
145
146 def test_walkpackages_zipfile(self):
147 """Tests the same as test_walkpackages_filesys, only with a zip file."""
148
149 zip = 'test_walkpackages_zipfile.zip'
150 pkg1 = 'test_walkpackages_zipfile'
151 pkg2 = 'sub'
152
153 zip_file = os.path.join(self.dirname, zip)
154 z = zipfile.ZipFile(zip_file, 'w')
155 z.writestr(pkg2 + '/__init__.py', "")
156 z.writestr(pkg2 + '/' + pkg1 + '/__init__.py', "")
157 z.writestr(pkg2 + '/' + pkg1 + '/mod.py', "")
158 z.writestr(pkg1 + '/__init__.py', "")
159 z.writestr(pkg1 + '/' + pkg2 + '/__init__.py', "")
160 z.writestr(pkg1 + '/' + pkg2 + '/mod.py', "")
161 z.close()
162
163 sys.path.insert(0, zip_file)
164 expected = [
165 'sub',
166 'sub.test_walkpackages_zipfile',
167 'sub.test_walkpackages_zipfile.mod',
168 'test_walkpackages_zipfile',
169 'test_walkpackages_zipfile.sub',
170 'test_walkpackages_zipfile.sub.mod',
171 ]
172 actual= [e[1] for e in pkgutil.walk_packages([zip_file])]
173 self.assertEqual(actual, expected)
174 del sys.path[0]
175
176 for pkg in expected:
177 if pkg.endswith('mod'):
178 continue
179 del sys.modules[pkg]
180
Sanyam Khuranab9c3da52017-06-13 22:41:14 +0530181 def test_walk_packages_raises_on_string_or_bytes_input(self):
182
183 str_input = 'test_dir'
184 with self.assertRaises((TypeError, ValueError)):
185 list(pkgutil.walk_packages(str_input))
186
187 bytes_input = b'test_dir'
188 with self.assertRaises((TypeError, ValueError)):
189 list(pkgutil.walk_packages(bytes_input))
Łukasz Langa0d18c152016-06-11 18:02:46 -0700190
Vinay Sajip1ed61612020-02-14 22:02:13 +0000191 def test_name_resolution(self):
192 import logging
193 import logging.handlers
194
195 success_cases = (
196 ('os', os),
197 ('os.path', os.path),
198 ('os.path:pathsep', os.path.pathsep),
199 ('logging', logging),
200 ('logging:', logging),
201 ('logging.handlers', logging.handlers),
202 ('logging.handlers:', logging.handlers),
203 ('logging.handlers:SysLogHandler', logging.handlers.SysLogHandler),
204 ('logging.handlers.SysLogHandler', logging.handlers.SysLogHandler),
205 ('logging.handlers:SysLogHandler.LOG_ALERT',
206 logging.handlers.SysLogHandler.LOG_ALERT),
207 ('logging.handlers.SysLogHandler.LOG_ALERT',
208 logging.handlers.SysLogHandler.LOG_ALERT),
209 ('builtins.int', int),
210 ('builtins:int', int),
211 ('builtins.int.from_bytes', int.from_bytes),
212 ('builtins:int.from_bytes', int.from_bytes),
213 ('builtins.ZeroDivisionError', ZeroDivisionError),
214 ('builtins:ZeroDivisionError', ZeroDivisionError),
215 ('os:path', os.path),
216 )
217
218 failure_cases = (
219 (None, TypeError),
220 (1, TypeError),
221 (2.0, TypeError),
222 (True, TypeError),
223 ('', ValueError),
224 ('?abc', ValueError),
225 ('abc/foo', ValueError),
226 ('foo', ImportError),
227 ('os.foo', AttributeError),
228 ('os.foo:', ImportError),
229 ('os.pth:pathsep', ImportError),
230 ('logging.handlers:NoSuchHandler', AttributeError),
231 ('logging.handlers:SysLogHandler.NO_SUCH_VALUE', AttributeError),
232 ('logging.handlers.SysLogHandler.NO_SUCH_VALUE', AttributeError),
233 ('ZeroDivisionError', ImportError),
Vinay Sajip4f17c5c2020-02-28 14:26:27 +0000234 ('os.path.9abc', ValueError),
235 ('9abc', ValueError),
Vinay Sajip1ed61612020-02-14 22:02:13 +0000236 )
237
Vinay Sajip4f17c5c2020-02-28 14:26:27 +0000238 # add some Unicode package names to the mix.
239
240 unicode_words = ('\u0935\u092e\u0938',
241 '\xe9', '\xc8',
242 '\uc548\ub155\ud558\uc138\uc694',
243 '\u3055\u3088\u306a\u3089',
244 '\u3042\u308a\u304c\u3068\u3046',
245 '\u0425\u043e\u0440\u043e\u0448\u043e',
246 '\u0441\u043f\u0430\u0441\u0438\u0431\u043e',
247 '\u73b0\u4ee3\u6c49\u8bed\u5e38\u7528\u5b57\u8868')
248
249 for uw in unicode_words:
250 d = os.path.join(self.dirname, uw)
Michael Felte0acec12020-03-03 11:11:11 +0100251 try:
252 os.makedirs(d, exist_ok=True)
253 except UnicodeEncodeError:
254 # When filesystem encoding cannot encode uw: skip this test
255 continue
Vinay Sajip4f17c5c2020-02-28 14:26:27 +0000256 # make an empty __init__.py file
257 f = os.path.join(d, '__init__.py')
258 with open(f, 'w') as f:
259 f.write('')
260 f.flush()
261 # now import the package we just created; clearing the caches is
262 # needed, otherwise the newly created package isn't found
263 importlib.invalidate_caches()
264 mod = importlib.import_module(uw)
265 success_cases += (uw, mod),
266 if len(uw) > 1:
267 failure_cases += (uw[:-1], ImportError),
268
269 # add an example with a Unicode digit at the start
270 failure_cases += ('\u0966\u0935\u092e\u0938', ValueError),
271
Vinay Sajip1ed61612020-02-14 22:02:13 +0000272 for s, expected in success_cases:
273 with self.subTest(s=s):
274 o = pkgutil.resolve_name(s)
275 self.assertEqual(o, expected)
276
277 for s, exc in failure_cases:
278 with self.subTest(s=s):
279 with self.assertRaises(exc):
280 pkgutil.resolve_name(s)
281
Łukasz Langa0d18c152016-06-11 18:02:46 -0700282
Christian Heimesdae2a892008-04-19 00:55:37 +0000283class PkgutilPEP302Tests(unittest.TestCase):
284
285 class MyTestLoader(object):
Brett Cannon02d84542015-01-09 11:39:21 -0500286 def create_module(self, spec):
287 return None
288
Eric Snow37148b22014-01-04 15:09:53 -0700289 def exec_module(self, mod):
Christian Heimesdae2a892008-04-19 00:55:37 +0000290 # Count how many times the module is reloaded
Eric Snow37148b22014-01-04 15:09:53 -0700291 mod.__dict__['loads'] = mod.__dict__.get('loads', 0) + 1
Christian Heimesdae2a892008-04-19 00:55:37 +0000292
293 def get_data(self, path):
294 return "Hello, world!"
295
296 class MyTestImporter(object):
Eric Snow37148b22014-01-04 15:09:53 -0700297 def find_spec(self, fullname, path=None, target=None):
298 loader = PkgutilPEP302Tests.MyTestLoader()
299 return spec_from_file_location(fullname,
300 '<%s>' % loader.__class__.__name__,
301 loader=loader,
302 submodule_search_locations=[])
Christian Heimesdae2a892008-04-19 00:55:37 +0000303
304 def setUp(self):
305 sys.meta_path.insert(0, self.MyTestImporter())
306
307 def tearDown(self):
308 del sys.meta_path[0]
309
310 def test_getdata_pep302(self):
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700311 # Use a dummy finder/loader
Christian Heimesdae2a892008-04-19 00:55:37 +0000312 self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!")
313 del sys.modules['foo']
314
315 def test_alreadyloaded(self):
316 # Ensure that get_data works without reloading - the "loads" module
317 # variable in the example loader should count how many times a reload
318 # occurs.
319 import foo
320 self.assertEqual(foo.loads, 1)
321 self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!")
322 self.assertEqual(foo.loads, 1)
323 del sys.modules['foo']
324
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400325
Eric V. Smith984b11f2012-05-24 20:21:04 -0400326# These tests, especially the setup and cleanup, are hideous. They
327# need to be cleaned up once issue 14715 is addressed.
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400328class ExtendPathTests(unittest.TestCase):
329 def create_init(self, pkgname):
330 dirname = tempfile.mkdtemp()
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400331 sys.path.insert(0, dirname)
332
333 pkgdir = os.path.join(dirname, pkgname)
334 os.mkdir(pkgdir)
335 with open(os.path.join(pkgdir, '__init__.py'), 'w') as fl:
336 fl.write('from pkgutil import extend_path\n__path__ = extend_path(__path__, __name__)\n')
337
338 return dirname
339
340 def create_submodule(self, dirname, pkgname, submodule_name, value):
341 module_name = os.path.join(dirname, pkgname, submodule_name + '.py')
342 with open(module_name, 'w') as fl:
343 print('value={}'.format(value), file=fl)
344
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400345 def test_simple(self):
Eric V. Smith984b11f2012-05-24 20:21:04 -0400346 pkgname = 'foo'
347 dirname_0 = self.create_init(pkgname)
348 dirname_1 = self.create_init(pkgname)
349 self.create_submodule(dirname_0, pkgname, 'bar', 0)
350 self.create_submodule(dirname_1, pkgname, 'baz', 1)
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400351 import foo.bar
352 import foo.baz
353 # Ensure we read the expected values
354 self.assertEqual(foo.bar.value, 0)
355 self.assertEqual(foo.baz.value, 1)
356
357 # Ensure the path is set up correctly
358 self.assertEqual(sorted(foo.__path__),
Eric V. Smith984b11f2012-05-24 20:21:04 -0400359 sorted([os.path.join(dirname_0, pkgname),
360 os.path.join(dirname_1, pkgname)]))
361
362 # Cleanup
363 shutil.rmtree(dirname_0)
364 shutil.rmtree(dirname_1)
365 del sys.path[0]
366 del sys.path[0]
367 del sys.modules['foo']
368 del sys.modules['foo.bar']
369 del sys.modules['foo.baz']
370
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000371
372 # Another awful testing hack to be cleaned up once the test_runpy
373 # helpers are factored out to a common location
374 def test_iter_importers(self):
375 iter_importers = pkgutil.iter_importers
376 get_importer = pkgutil.get_importer
377
378 pkgname = 'spam'
379 modname = 'eggs'
380 dirname = self.create_init(pkgname)
381 pathitem = os.path.join(dirname, pkgname)
382 fullname = '{}.{}'.format(pkgname, modname)
Eric Snow2ba66eb2013-11-22 13:55:23 -0700383 sys.modules.pop(fullname, None)
384 sys.modules.pop(pkgname, None)
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000385 try:
386 self.create_submodule(dirname, pkgname, modname, 0)
387
388 importlib.import_module(fullname)
389
390 importers = list(iter_importers(fullname))
391 expected_importer = get_importer(pathitem)
392 for finder in importers:
Eric Snow37148b22014-01-04 15:09:53 -0700393 spec = pkgutil._get_spec(finder, fullname)
394 loader = spec.loader
Eric Snowb523f842013-11-22 09:05:39 -0700395 try:
396 loader = loader.loader
397 except AttributeError:
398 # For now we still allow raw loaders from
399 # find_module().
400 pass
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000401 self.assertIsInstance(finder, importlib.machinery.FileFinder)
402 self.assertEqual(finder, expected_importer)
Eric Snowb523f842013-11-22 09:05:39 -0700403 self.assertIsInstance(loader,
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000404 importlib.machinery.SourceFileLoader)
Eric Snow37148b22014-01-04 15:09:53 -0700405 self.assertIsNone(pkgutil._get_spec(finder, pkgname))
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000406
407 with self.assertRaises(ImportError):
408 list(iter_importers('invalid.module'))
409
410 with self.assertRaises(ImportError):
411 list(iter_importers('.spam'))
412 finally:
413 shutil.rmtree(dirname)
414 del sys.path[0]
Eric Snowb523f842013-11-22 09:05:39 -0700415 try:
416 del sys.modules['spam']
417 del sys.modules['spam.eggs']
418 except KeyError:
419 pass
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000420
421
Eric V. Smith984b11f2012-05-24 20:21:04 -0400422 def test_mixed_namespace(self):
423 pkgname = 'foo'
424 dirname_0 = self.create_init(pkgname)
425 dirname_1 = self.create_init(pkgname)
426 self.create_submodule(dirname_0, pkgname, 'bar', 0)
427 # Turn this into a PEP 420 namespace package
428 os.unlink(os.path.join(dirname_0, pkgname, '__init__.py'))
429 self.create_submodule(dirname_1, pkgname, 'baz', 1)
430 import foo.bar
431 import foo.baz
432 # Ensure we read the expected values
433 self.assertEqual(foo.bar.value, 0)
434 self.assertEqual(foo.baz.value, 1)
435
436 # Ensure the path is set up correctly
437 self.assertEqual(sorted(foo.__path__),
438 sorted([os.path.join(dirname_0, pkgname),
439 os.path.join(dirname_1, pkgname)]))
440
441 # Cleanup
442 shutil.rmtree(dirname_0)
443 shutil.rmtree(dirname_1)
444 del sys.path[0]
445 del sys.path[0]
446 del sys.modules['foo']
447 del sys.modules['foo.bar']
448 del sys.modules['foo.baz']
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400449
450 # XXX: test .pkg files
451
452
Antoine Pitroub2dd8802012-07-09 21:23:58 +0200453class NestedNamespacePackageTest(unittest.TestCase):
454
455 def setUp(self):
456 self.basedir = tempfile.mkdtemp()
457 self.old_path = sys.path[:]
458
459 def tearDown(self):
460 sys.path[:] = self.old_path
461 shutil.rmtree(self.basedir)
462
463 def create_module(self, name, contents):
464 base, final = name.rsplit('.', 1)
465 base_path = os.path.join(self.basedir, base.replace('.', os.path.sep))
466 os.makedirs(base_path, exist_ok=True)
467 with open(os.path.join(base_path, final + ".py"), 'w') as f:
468 f.write(contents)
469
470 def test_nested(self):
471 pkgutil_boilerplate = (
472 'import pkgutil; '
473 '__path__ = pkgutil.extend_path(__path__, __name__)')
474 self.create_module('a.pkg.__init__', pkgutil_boilerplate)
475 self.create_module('b.pkg.__init__', pkgutil_boilerplate)
476 self.create_module('a.pkg.subpkg.__init__', pkgutil_boilerplate)
477 self.create_module('b.pkg.subpkg.__init__', pkgutil_boilerplate)
478 self.create_module('a.pkg.subpkg.c', 'c = 1')
479 self.create_module('b.pkg.subpkg.d', 'd = 2')
480 sys.path.insert(0, os.path.join(self.basedir, 'a'))
481 sys.path.insert(0, os.path.join(self.basedir, 'b'))
482 import pkg
483 self.addCleanup(unload, 'pkg')
484 self.assertEqual(len(pkg.__path__), 2)
485 import pkg.subpkg
486 self.addCleanup(unload, 'pkg.subpkg')
487 self.assertEqual(len(pkg.subpkg.__path__), 2)
488 from pkg.subpkg.c import c
489 from pkg.subpkg.d import d
490 self.assertEqual(c, 1)
491 self.assertEqual(d, 2)
492
493
Nick Coghlan85e729e2012-07-15 18:09:52 +1000494class ImportlibMigrationTests(unittest.TestCase):
495 # With full PEP 302 support in the standard import machinery, the
496 # PEP 302 emulation in this module is in the process of being
497 # deprecated in favour of importlib proper
498
499 def check_deprecated(self):
500 return check_warnings(
501 ("This emulation is deprecated, use 'importlib' instead",
502 DeprecationWarning))
503
504 def test_importer_deprecated(self):
505 with self.check_deprecated():
Łukasz Langa0d18c152016-06-11 18:02:46 -0700506 pkgutil.ImpImporter("")
Nick Coghlan85e729e2012-07-15 18:09:52 +1000507
508 def test_loader_deprecated(self):
509 with self.check_deprecated():
Łukasz Langa0d18c152016-06-11 18:02:46 -0700510 pkgutil.ImpLoader("", "", "", "")
Nick Coghlan85e729e2012-07-15 18:09:52 +1000511
512 def test_get_loader_avoids_emulation(self):
513 with check_warnings() as w:
514 self.assertIsNotNone(pkgutil.get_loader("sys"))
515 self.assertIsNotNone(pkgutil.get_loader("os"))
516 self.assertIsNotNone(pkgutil.get_loader("test.support"))
517 self.assertEqual(len(w.warnings), 0)
518
Brett Cannon4a2360d2016-08-12 10:53:53 -0700519 @unittest.skipIf(__name__ == '__main__', 'not compatible with __main__')
Nick Coghlandc855b72014-03-04 20:39:42 +1000520 def test_get_loader_handles_missing_loader_attribute(self):
521 global __loader__
522 this_loader = __loader__
523 del __loader__
524 try:
525 with check_warnings() as w:
526 self.assertIsNotNone(pkgutil.get_loader(__name__))
527 self.assertEqual(len(w.warnings), 0)
528 finally:
529 __loader__ = this_loader
530
Eric Snow658af312014-04-19 00:13:23 -0600531 def test_get_loader_handles_missing_spec_attribute(self):
532 name = 'spam'
533 mod = type(sys)(name)
534 del mod.__spec__
535 with CleanImport(name):
536 sys.modules[name] = mod
537 loader = pkgutil.get_loader(name)
538 self.assertIsNone(loader)
539
540 def test_get_loader_handles_spec_attribute_none(self):
541 name = 'spam'
542 mod = type(sys)(name)
543 mod.__spec__ = None
544 with CleanImport(name):
545 sys.modules[name] = mod
546 loader = pkgutil.get_loader(name)
547 self.assertIsNone(loader)
Nick Coghlandc855b72014-03-04 20:39:42 +1000548
Brett Cannon8447c702014-05-23 12:30:37 -0400549 def test_get_loader_None_in_sys_modules(self):
550 name = 'totally bogus'
551 sys.modules[name] = None
552 try:
553 loader = pkgutil.get_loader(name)
554 finally:
555 del sys.modules[name]
556 self.assertIsNone(loader)
557
558 def test_find_loader_missing_module(self):
559 name = 'totally bogus'
560 loader = pkgutil.find_loader(name)
561 self.assertIsNone(loader)
562
Nick Coghlandc855b72014-03-04 20:39:42 +1000563 def test_find_loader_avoids_emulation(self):
564 with check_warnings() as w:
565 self.assertIsNotNone(pkgutil.find_loader("sys"))
566 self.assertIsNotNone(pkgutil.find_loader("os"))
567 self.assertIsNotNone(pkgutil.find_loader("test.support"))
568 self.assertEqual(len(w.warnings), 0)
569
Nick Coghlan85e729e2012-07-15 18:09:52 +1000570 def test_get_importer_avoids_emulation(self):
Nick Coghlan94554922012-07-17 21:37:58 +1000571 # We use an illegal path so *none* of the path hooks should fire
Nick Coghlan85e729e2012-07-15 18:09:52 +1000572 with check_warnings() as w:
Nick Coghlan94554922012-07-17 21:37:58 +1000573 self.assertIsNone(pkgutil.get_importer("*??"))
Nick Coghlan85e729e2012-07-15 18:09:52 +1000574 self.assertEqual(len(w.warnings), 0)
575
576 def test_iter_importers_avoids_emulation(self):
577 with check_warnings() as w:
578 for importer in pkgutil.iter_importers(): pass
579 self.assertEqual(len(w.warnings), 0)
580
581
Christian Heimesdae2a892008-04-19 00:55:37 +0000582def test_main():
Antoine Pitroub2dd8802012-07-09 21:23:58 +0200583 run_unittest(PkgutilTests, PkgutilPEP302Tests, ExtendPathTests,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000584 NestedNamespacePackageTest, ImportlibMigrationTests)
Benjamin Petersoncf626032014-02-16 14:52:01 -0500585 # this is necessary if test is run repeated (like when finding leaks)
586 import zipimport
587 import importlib
588 zipimport._zip_directory_cache.clear()
589 importlib.invalidate_caches()
Nick Coghlan85e729e2012-07-15 18:09:52 +1000590
Christian Heimesdae2a892008-04-19 00:55:37 +0000591
592if __name__ == '__main__':
593 test_main()