blob: 906150b10495bfbdc43749cfa68c6fb846a0565f [file] [log] [blame]
Eric Snow658af312014-04-19 00:13:23 -06001from test.support import run_unittest, unload, check_warnings, CleanImport
Christian Heimesdae2a892008-04-19 00:55:37 +00002import unittest
3import sys
Nick Coghlanc4e0d982013-04-14 22:30:42 +10004import importlib
Eric Snow37148b22014-01-04 15:09:53 -07005from importlib.util import spec_from_file_location
Christian Heimesdae2a892008-04-19 00:55:37 +00006import pkgutil
7import os
8import os.path
9import tempfile
10import shutil
11import zipfile
12
Nick Coghlan8ecf5042012-07-15 21:19:18 +100013# Note: pkgutil.walk_packages is currently tested in test_runpy. This is
14# a hack to get a major issue resolved for 3.3b2. Longer term, it should
15# be moved back here, perhaps by factoring out the helper code for
16# creating interesting package layouts to a separate module.
17# Issue #15348 declares this is indeed a dodgy hack ;)
Christian Heimesdae2a892008-04-19 00:55:37 +000018
19class PkgutilTests(unittest.TestCase):
20
21 def setUp(self):
22 self.dirname = tempfile.mkdtemp()
Ned Deily7010a072011-10-07 12:01:40 -070023 self.addCleanup(shutil.rmtree, self.dirname)
Christian Heimesdae2a892008-04-19 00:55:37 +000024 sys.path.insert(0, self.dirname)
25
26 def tearDown(self):
27 del sys.path[0]
Christian Heimesdae2a892008-04-19 00:55:37 +000028
29 def test_getdata_filesys(self):
30 pkg = 'test_getdata_filesys'
31
32 # Include a LF and a CRLF, to test that binary data is read back
33 RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line'
34
35 # Make a package with some resources
36 package_dir = os.path.join(self.dirname, pkg)
37 os.mkdir(package_dir)
38 # Empty init.py
39 f = open(os.path.join(package_dir, '__init__.py'), "wb")
40 f.close()
41 # Resource files, res.txt, sub/res.txt
42 f = open(os.path.join(package_dir, 'res.txt'), "wb")
43 f.write(RESOURCE_DATA)
44 f.close()
45 os.mkdir(os.path.join(package_dir, 'sub'))
46 f = open(os.path.join(package_dir, 'sub', 'res.txt'), "wb")
47 f.write(RESOURCE_DATA)
48 f.close()
49
50 # Check we can read the resources
51 res1 = pkgutil.get_data(pkg, 'res.txt')
52 self.assertEqual(res1, RESOURCE_DATA)
53 res2 = pkgutil.get_data(pkg, 'sub/res.txt')
54 self.assertEqual(res2, RESOURCE_DATA)
55
56 del sys.modules[pkg]
57
58 def test_getdata_zipfile(self):
59 zip = 'test_getdata_zipfile.zip'
60 pkg = 'test_getdata_zipfile'
61
62 # Include a LF and a CRLF, to test that binary data is read back
63 RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line'
64
65 # Make a package with some resources
66 zip_file = os.path.join(self.dirname, zip)
67 z = zipfile.ZipFile(zip_file, 'w')
68
69 # Empty init.py
70 z.writestr(pkg + '/__init__.py', "")
71 # Resource files, res.txt, sub/res.txt
72 z.writestr(pkg + '/res.txt', RESOURCE_DATA)
73 z.writestr(pkg + '/sub/res.txt', RESOURCE_DATA)
74 z.close()
75
76 # Check we can read the resources
77 sys.path.insert(0, zip_file)
78 res1 = pkgutil.get_data(pkg, 'res.txt')
79 self.assertEqual(res1, RESOURCE_DATA)
80 res2 = pkgutil.get_data(pkg, 'sub/res.txt')
81 self.assertEqual(res2, RESOURCE_DATA)
Alexandre Vassalotti515a74f2009-07-05 06:42:44 +000082
83 names = []
Eric Snowd5f92232016-09-07 18:37:17 -070084 for moduleinfo in pkgutil.iter_modules([zip_file]):
85 self.assertIsInstance(moduleinfo, pkgutil.ModuleInfo)
86 names.append(moduleinfo.name)
Alexandre Vassalotti515a74f2009-07-05 06:42:44 +000087 self.assertEqual(names, ['test_getdata_zipfile'])
88
Christian Heimesdae2a892008-04-19 00:55:37 +000089 del sys.path[0]
90
91 del sys.modules[pkg]
92
Ned Deilycaf5a222011-10-06 14:19:06 -070093 def test_unreadable_dir_on_syspath(self):
94 # issue7367 - walk_packages failed if unreadable dir on sys.path
95 package_name = "unreadable_package"
96 d = os.path.join(self.dirname, package_name)
97 # this does not appear to create an unreadable dir on Windows
98 # but the test should not fail anyway
99 os.mkdir(d, 0)
Ned Deily7010a072011-10-07 12:01:40 -0700100 self.addCleanup(os.rmdir, d)
Ned Deilycaf5a222011-10-06 14:19:06 -0700101 for t in pkgutil.walk_packages(path=[self.dirname]):
102 self.fail("unexpected package found")
Ned Deilycaf5a222011-10-06 14:19:06 -0700103
Łukasz Langa0d18c152016-06-11 18:02:46 -0700104 def test_walkpackages_filesys(self):
105 pkg1 = 'test_walkpackages_filesys'
106 pkg1_dir = os.path.join(self.dirname, pkg1)
107 os.mkdir(pkg1_dir)
108 f = open(os.path.join(pkg1_dir, '__init__.py'), "wb")
109 f.close()
110 os.mkdir(os.path.join(pkg1_dir, 'sub'))
111 f = open(os.path.join(pkg1_dir, 'sub', '__init__.py'), "wb")
112 f.close()
113 f = open(os.path.join(pkg1_dir, 'sub', 'mod.py'), "wb")
114 f.close()
115
116 # Now, to juice it up, let's add the opposite packages, too.
117 pkg2 = 'sub'
118 pkg2_dir = os.path.join(self.dirname, pkg2)
119 os.mkdir(pkg2_dir)
120 f = open(os.path.join(pkg2_dir, '__init__.py'), "wb")
121 f.close()
122 os.mkdir(os.path.join(pkg2_dir, 'test_walkpackages_filesys'))
123 f = open(os.path.join(pkg2_dir, 'test_walkpackages_filesys', '__init__.py'), "wb")
124 f.close()
125 f = open(os.path.join(pkg2_dir, 'test_walkpackages_filesys', 'mod.py'), "wb")
126 f.close()
127
128 expected = [
129 'sub',
130 'sub.test_walkpackages_filesys',
131 'sub.test_walkpackages_filesys.mod',
132 'test_walkpackages_filesys',
133 'test_walkpackages_filesys.sub',
134 'test_walkpackages_filesys.sub.mod',
135 ]
136 actual= [e[1] for e in pkgutil.walk_packages([self.dirname])]
137 self.assertEqual(actual, expected)
138
139 for pkg in expected:
140 if pkg.endswith('mod'):
141 continue
142 del sys.modules[pkg]
143
144 def test_walkpackages_zipfile(self):
145 """Tests the same as test_walkpackages_filesys, only with a zip file."""
146
147 zip = 'test_walkpackages_zipfile.zip'
148 pkg1 = 'test_walkpackages_zipfile'
149 pkg2 = 'sub'
150
151 zip_file = os.path.join(self.dirname, zip)
152 z = zipfile.ZipFile(zip_file, 'w')
153 z.writestr(pkg2 + '/__init__.py', "")
154 z.writestr(pkg2 + '/' + pkg1 + '/__init__.py', "")
155 z.writestr(pkg2 + '/' + pkg1 + '/mod.py', "")
156 z.writestr(pkg1 + '/__init__.py', "")
157 z.writestr(pkg1 + '/' + pkg2 + '/__init__.py', "")
158 z.writestr(pkg1 + '/' + pkg2 + '/mod.py', "")
159 z.close()
160
161 sys.path.insert(0, zip_file)
162 expected = [
163 'sub',
164 'sub.test_walkpackages_zipfile',
165 'sub.test_walkpackages_zipfile.mod',
166 'test_walkpackages_zipfile',
167 'test_walkpackages_zipfile.sub',
168 'test_walkpackages_zipfile.sub.mod',
169 ]
170 actual= [e[1] for e in pkgutil.walk_packages([zip_file])]
171 self.assertEqual(actual, expected)
172 del sys.path[0]
173
174 for pkg in expected:
175 if pkg.endswith('mod'):
176 continue
177 del sys.modules[pkg]
178
Sanyam Khuranab9c3da52017-06-13 22:41:14 +0530179 def test_walk_packages_raises_on_string_or_bytes_input(self):
180
181 str_input = 'test_dir'
182 with self.assertRaises((TypeError, ValueError)):
183 list(pkgutil.walk_packages(str_input))
184
185 bytes_input = b'test_dir'
186 with self.assertRaises((TypeError, ValueError)):
187 list(pkgutil.walk_packages(bytes_input))
Łukasz Langa0d18c152016-06-11 18:02:46 -0700188
Vinay Sajip1ed61612020-02-14 22:02:13 +0000189 def test_name_resolution(self):
190 import logging
191 import logging.handlers
192
193 success_cases = (
194 ('os', os),
195 ('os.path', os.path),
196 ('os.path:pathsep', os.path.pathsep),
197 ('logging', logging),
198 ('logging:', logging),
199 ('logging.handlers', logging.handlers),
200 ('logging.handlers:', logging.handlers),
201 ('logging.handlers:SysLogHandler', logging.handlers.SysLogHandler),
202 ('logging.handlers.SysLogHandler', logging.handlers.SysLogHandler),
203 ('logging.handlers:SysLogHandler.LOG_ALERT',
204 logging.handlers.SysLogHandler.LOG_ALERT),
205 ('logging.handlers.SysLogHandler.LOG_ALERT',
206 logging.handlers.SysLogHandler.LOG_ALERT),
207 ('builtins.int', int),
208 ('builtins:int', int),
209 ('builtins.int.from_bytes', int.from_bytes),
210 ('builtins:int.from_bytes', int.from_bytes),
211 ('builtins.ZeroDivisionError', ZeroDivisionError),
212 ('builtins:ZeroDivisionError', ZeroDivisionError),
213 ('os:path', os.path),
214 )
215
216 failure_cases = (
217 (None, TypeError),
218 (1, TypeError),
219 (2.0, TypeError),
220 (True, TypeError),
221 ('', ValueError),
222 ('?abc', ValueError),
223 ('abc/foo', ValueError),
224 ('foo', ImportError),
225 ('os.foo', AttributeError),
226 ('os.foo:', ImportError),
227 ('os.pth:pathsep', ImportError),
228 ('logging.handlers:NoSuchHandler', AttributeError),
229 ('logging.handlers:SysLogHandler.NO_SUCH_VALUE', AttributeError),
230 ('logging.handlers.SysLogHandler.NO_SUCH_VALUE', AttributeError),
231 ('ZeroDivisionError', ImportError),
232 )
233
234 for s, expected in success_cases:
235 with self.subTest(s=s):
236 o = pkgutil.resolve_name(s)
237 self.assertEqual(o, expected)
238
239 for s, exc in failure_cases:
240 with self.subTest(s=s):
241 with self.assertRaises(exc):
242 pkgutil.resolve_name(s)
243
Łukasz Langa0d18c152016-06-11 18:02:46 -0700244
Christian Heimesdae2a892008-04-19 00:55:37 +0000245class PkgutilPEP302Tests(unittest.TestCase):
246
247 class MyTestLoader(object):
Brett Cannon02d84542015-01-09 11:39:21 -0500248 def create_module(self, spec):
249 return None
250
Eric Snow37148b22014-01-04 15:09:53 -0700251 def exec_module(self, mod):
Christian Heimesdae2a892008-04-19 00:55:37 +0000252 # Count how many times the module is reloaded
Eric Snow37148b22014-01-04 15:09:53 -0700253 mod.__dict__['loads'] = mod.__dict__.get('loads', 0) + 1
Christian Heimesdae2a892008-04-19 00:55:37 +0000254
255 def get_data(self, path):
256 return "Hello, world!"
257
258 class MyTestImporter(object):
Eric Snow37148b22014-01-04 15:09:53 -0700259 def find_spec(self, fullname, path=None, target=None):
260 loader = PkgutilPEP302Tests.MyTestLoader()
261 return spec_from_file_location(fullname,
262 '<%s>' % loader.__class__.__name__,
263 loader=loader,
264 submodule_search_locations=[])
Christian Heimesdae2a892008-04-19 00:55:37 +0000265
266 def setUp(self):
267 sys.meta_path.insert(0, self.MyTestImporter())
268
269 def tearDown(self):
270 del sys.meta_path[0]
271
272 def test_getdata_pep302(self):
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700273 # Use a dummy finder/loader
Christian Heimesdae2a892008-04-19 00:55:37 +0000274 self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!")
275 del sys.modules['foo']
276
277 def test_alreadyloaded(self):
278 # Ensure that get_data works without reloading - the "loads" module
279 # variable in the example loader should count how many times a reload
280 # occurs.
281 import foo
282 self.assertEqual(foo.loads, 1)
283 self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!")
284 self.assertEqual(foo.loads, 1)
285 del sys.modules['foo']
286
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400287
Eric V. Smith984b11f2012-05-24 20:21:04 -0400288# These tests, especially the setup and cleanup, are hideous. They
289# need to be cleaned up once issue 14715 is addressed.
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400290class ExtendPathTests(unittest.TestCase):
291 def create_init(self, pkgname):
292 dirname = tempfile.mkdtemp()
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400293 sys.path.insert(0, dirname)
294
295 pkgdir = os.path.join(dirname, pkgname)
296 os.mkdir(pkgdir)
297 with open(os.path.join(pkgdir, '__init__.py'), 'w') as fl:
298 fl.write('from pkgutil import extend_path\n__path__ = extend_path(__path__, __name__)\n')
299
300 return dirname
301
302 def create_submodule(self, dirname, pkgname, submodule_name, value):
303 module_name = os.path.join(dirname, pkgname, submodule_name + '.py')
304 with open(module_name, 'w') as fl:
305 print('value={}'.format(value), file=fl)
306
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400307 def test_simple(self):
Eric V. Smith984b11f2012-05-24 20:21:04 -0400308 pkgname = 'foo'
309 dirname_0 = self.create_init(pkgname)
310 dirname_1 = self.create_init(pkgname)
311 self.create_submodule(dirname_0, pkgname, 'bar', 0)
312 self.create_submodule(dirname_1, pkgname, 'baz', 1)
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400313 import foo.bar
314 import foo.baz
315 # Ensure we read the expected values
316 self.assertEqual(foo.bar.value, 0)
317 self.assertEqual(foo.baz.value, 1)
318
319 # Ensure the path is set up correctly
320 self.assertEqual(sorted(foo.__path__),
Eric V. Smith984b11f2012-05-24 20:21:04 -0400321 sorted([os.path.join(dirname_0, pkgname),
322 os.path.join(dirname_1, pkgname)]))
323
324 # Cleanup
325 shutil.rmtree(dirname_0)
326 shutil.rmtree(dirname_1)
327 del sys.path[0]
328 del sys.path[0]
329 del sys.modules['foo']
330 del sys.modules['foo.bar']
331 del sys.modules['foo.baz']
332
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000333
334 # Another awful testing hack to be cleaned up once the test_runpy
335 # helpers are factored out to a common location
336 def test_iter_importers(self):
337 iter_importers = pkgutil.iter_importers
338 get_importer = pkgutil.get_importer
339
340 pkgname = 'spam'
341 modname = 'eggs'
342 dirname = self.create_init(pkgname)
343 pathitem = os.path.join(dirname, pkgname)
344 fullname = '{}.{}'.format(pkgname, modname)
Eric Snow2ba66eb2013-11-22 13:55:23 -0700345 sys.modules.pop(fullname, None)
346 sys.modules.pop(pkgname, None)
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000347 try:
348 self.create_submodule(dirname, pkgname, modname, 0)
349
350 importlib.import_module(fullname)
351
352 importers = list(iter_importers(fullname))
353 expected_importer = get_importer(pathitem)
354 for finder in importers:
Eric Snow37148b22014-01-04 15:09:53 -0700355 spec = pkgutil._get_spec(finder, fullname)
356 loader = spec.loader
Eric Snowb523f842013-11-22 09:05:39 -0700357 try:
358 loader = loader.loader
359 except AttributeError:
360 # For now we still allow raw loaders from
361 # find_module().
362 pass
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000363 self.assertIsInstance(finder, importlib.machinery.FileFinder)
364 self.assertEqual(finder, expected_importer)
Eric Snowb523f842013-11-22 09:05:39 -0700365 self.assertIsInstance(loader,
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000366 importlib.machinery.SourceFileLoader)
Eric Snow37148b22014-01-04 15:09:53 -0700367 self.assertIsNone(pkgutil._get_spec(finder, pkgname))
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000368
369 with self.assertRaises(ImportError):
370 list(iter_importers('invalid.module'))
371
372 with self.assertRaises(ImportError):
373 list(iter_importers('.spam'))
374 finally:
375 shutil.rmtree(dirname)
376 del sys.path[0]
Eric Snowb523f842013-11-22 09:05:39 -0700377 try:
378 del sys.modules['spam']
379 del sys.modules['spam.eggs']
380 except KeyError:
381 pass
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000382
383
Eric V. Smith984b11f2012-05-24 20:21:04 -0400384 def test_mixed_namespace(self):
385 pkgname = 'foo'
386 dirname_0 = self.create_init(pkgname)
387 dirname_1 = self.create_init(pkgname)
388 self.create_submodule(dirname_0, pkgname, 'bar', 0)
389 # Turn this into a PEP 420 namespace package
390 os.unlink(os.path.join(dirname_0, pkgname, '__init__.py'))
391 self.create_submodule(dirname_1, pkgname, 'baz', 1)
392 import foo.bar
393 import foo.baz
394 # Ensure we read the expected values
395 self.assertEqual(foo.bar.value, 0)
396 self.assertEqual(foo.baz.value, 1)
397
398 # Ensure the path is set up correctly
399 self.assertEqual(sorted(foo.__path__),
400 sorted([os.path.join(dirname_0, pkgname),
401 os.path.join(dirname_1, pkgname)]))
402
403 # Cleanup
404 shutil.rmtree(dirname_0)
405 shutil.rmtree(dirname_1)
406 del sys.path[0]
407 del sys.path[0]
408 del sys.modules['foo']
409 del sys.modules['foo.bar']
410 del sys.modules['foo.baz']
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400411
412 # XXX: test .pkg files
413
414
Antoine Pitroub2dd8802012-07-09 21:23:58 +0200415class NestedNamespacePackageTest(unittest.TestCase):
416
417 def setUp(self):
418 self.basedir = tempfile.mkdtemp()
419 self.old_path = sys.path[:]
420
421 def tearDown(self):
422 sys.path[:] = self.old_path
423 shutil.rmtree(self.basedir)
424
425 def create_module(self, name, contents):
426 base, final = name.rsplit('.', 1)
427 base_path = os.path.join(self.basedir, base.replace('.', os.path.sep))
428 os.makedirs(base_path, exist_ok=True)
429 with open(os.path.join(base_path, final + ".py"), 'w') as f:
430 f.write(contents)
431
432 def test_nested(self):
433 pkgutil_boilerplate = (
434 'import pkgutil; '
435 '__path__ = pkgutil.extend_path(__path__, __name__)')
436 self.create_module('a.pkg.__init__', pkgutil_boilerplate)
437 self.create_module('b.pkg.__init__', pkgutil_boilerplate)
438 self.create_module('a.pkg.subpkg.__init__', pkgutil_boilerplate)
439 self.create_module('b.pkg.subpkg.__init__', pkgutil_boilerplate)
440 self.create_module('a.pkg.subpkg.c', 'c = 1')
441 self.create_module('b.pkg.subpkg.d', 'd = 2')
442 sys.path.insert(0, os.path.join(self.basedir, 'a'))
443 sys.path.insert(0, os.path.join(self.basedir, 'b'))
444 import pkg
445 self.addCleanup(unload, 'pkg')
446 self.assertEqual(len(pkg.__path__), 2)
447 import pkg.subpkg
448 self.addCleanup(unload, 'pkg.subpkg')
449 self.assertEqual(len(pkg.subpkg.__path__), 2)
450 from pkg.subpkg.c import c
451 from pkg.subpkg.d import d
452 self.assertEqual(c, 1)
453 self.assertEqual(d, 2)
454
455
Nick Coghlan85e729e2012-07-15 18:09:52 +1000456class ImportlibMigrationTests(unittest.TestCase):
457 # With full PEP 302 support in the standard import machinery, the
458 # PEP 302 emulation in this module is in the process of being
459 # deprecated in favour of importlib proper
460
461 def check_deprecated(self):
462 return check_warnings(
463 ("This emulation is deprecated, use 'importlib' instead",
464 DeprecationWarning))
465
466 def test_importer_deprecated(self):
467 with self.check_deprecated():
Łukasz Langa0d18c152016-06-11 18:02:46 -0700468 pkgutil.ImpImporter("")
Nick Coghlan85e729e2012-07-15 18:09:52 +1000469
470 def test_loader_deprecated(self):
471 with self.check_deprecated():
Łukasz Langa0d18c152016-06-11 18:02:46 -0700472 pkgutil.ImpLoader("", "", "", "")
Nick Coghlan85e729e2012-07-15 18:09:52 +1000473
474 def test_get_loader_avoids_emulation(self):
475 with check_warnings() as w:
476 self.assertIsNotNone(pkgutil.get_loader("sys"))
477 self.assertIsNotNone(pkgutil.get_loader("os"))
478 self.assertIsNotNone(pkgutil.get_loader("test.support"))
479 self.assertEqual(len(w.warnings), 0)
480
Brett Cannon4a2360d2016-08-12 10:53:53 -0700481 @unittest.skipIf(__name__ == '__main__', 'not compatible with __main__')
Nick Coghlandc855b72014-03-04 20:39:42 +1000482 def test_get_loader_handles_missing_loader_attribute(self):
483 global __loader__
484 this_loader = __loader__
485 del __loader__
486 try:
487 with check_warnings() as w:
488 self.assertIsNotNone(pkgutil.get_loader(__name__))
489 self.assertEqual(len(w.warnings), 0)
490 finally:
491 __loader__ = this_loader
492
Eric Snow658af312014-04-19 00:13:23 -0600493 def test_get_loader_handles_missing_spec_attribute(self):
494 name = 'spam'
495 mod = type(sys)(name)
496 del mod.__spec__
497 with CleanImport(name):
498 sys.modules[name] = mod
499 loader = pkgutil.get_loader(name)
500 self.assertIsNone(loader)
501
502 def test_get_loader_handles_spec_attribute_none(self):
503 name = 'spam'
504 mod = type(sys)(name)
505 mod.__spec__ = None
506 with CleanImport(name):
507 sys.modules[name] = mod
508 loader = pkgutil.get_loader(name)
509 self.assertIsNone(loader)
Nick Coghlandc855b72014-03-04 20:39:42 +1000510
Brett Cannon8447c702014-05-23 12:30:37 -0400511 def test_get_loader_None_in_sys_modules(self):
512 name = 'totally bogus'
513 sys.modules[name] = None
514 try:
515 loader = pkgutil.get_loader(name)
516 finally:
517 del sys.modules[name]
518 self.assertIsNone(loader)
519
520 def test_find_loader_missing_module(self):
521 name = 'totally bogus'
522 loader = pkgutil.find_loader(name)
523 self.assertIsNone(loader)
524
Nick Coghlandc855b72014-03-04 20:39:42 +1000525 def test_find_loader_avoids_emulation(self):
526 with check_warnings() as w:
527 self.assertIsNotNone(pkgutil.find_loader("sys"))
528 self.assertIsNotNone(pkgutil.find_loader("os"))
529 self.assertIsNotNone(pkgutil.find_loader("test.support"))
530 self.assertEqual(len(w.warnings), 0)
531
Nick Coghlan85e729e2012-07-15 18:09:52 +1000532 def test_get_importer_avoids_emulation(self):
Nick Coghlan94554922012-07-17 21:37:58 +1000533 # We use an illegal path so *none* of the path hooks should fire
Nick Coghlan85e729e2012-07-15 18:09:52 +1000534 with check_warnings() as w:
Nick Coghlan94554922012-07-17 21:37:58 +1000535 self.assertIsNone(pkgutil.get_importer("*??"))
Nick Coghlan85e729e2012-07-15 18:09:52 +1000536 self.assertEqual(len(w.warnings), 0)
537
538 def test_iter_importers_avoids_emulation(self):
539 with check_warnings() as w:
540 for importer in pkgutil.iter_importers(): pass
541 self.assertEqual(len(w.warnings), 0)
542
543
Christian Heimesdae2a892008-04-19 00:55:37 +0000544def test_main():
Antoine Pitroub2dd8802012-07-09 21:23:58 +0200545 run_unittest(PkgutilTests, PkgutilPEP302Tests, ExtendPathTests,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000546 NestedNamespacePackageTest, ImportlibMigrationTests)
Benjamin Petersoncf626032014-02-16 14:52:01 -0500547 # this is necessary if test is run repeated (like when finding leaks)
548 import zipimport
549 import importlib
550 zipimport._zip_directory_cache.clear()
551 importlib.invalidate_caches()
Nick Coghlan85e729e2012-07-15 18:09:52 +1000552
Christian Heimesdae2a892008-04-19 00:55:37 +0000553
554if __name__ == '__main__':
555 test_main()