blob: e0c8635de1675a99ba58c5530d42b5469b784952 [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
Brett Cannon9529fbf2013-06-15 17:11:25 -040010import types
Christian Heimesdae2a892008-04-19 00:55:37 +000011import shutil
12import zipfile
13
Nick Coghlan8ecf5042012-07-15 21:19:18 +100014# Note: pkgutil.walk_packages is currently tested in test_runpy. This is
15# a hack to get a major issue resolved for 3.3b2. Longer term, it should
16# be moved back here, perhaps by factoring out the helper code for
17# creating interesting package layouts to a separate module.
18# Issue #15348 declares this is indeed a dodgy hack ;)
Christian Heimesdae2a892008-04-19 00:55:37 +000019
20class PkgutilTests(unittest.TestCase):
21
22 def setUp(self):
23 self.dirname = tempfile.mkdtemp()
Ned Deily7010a072011-10-07 12:01:40 -070024 self.addCleanup(shutil.rmtree, self.dirname)
Christian Heimesdae2a892008-04-19 00:55:37 +000025 sys.path.insert(0, self.dirname)
26
27 def tearDown(self):
28 del sys.path[0]
Christian Heimesdae2a892008-04-19 00:55:37 +000029
30 def test_getdata_filesys(self):
31 pkg = 'test_getdata_filesys'
32
33 # Include a LF and a CRLF, to test that binary data is read back
34 RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line'
35
36 # Make a package with some resources
37 package_dir = os.path.join(self.dirname, pkg)
38 os.mkdir(package_dir)
39 # Empty init.py
40 f = open(os.path.join(package_dir, '__init__.py'), "wb")
41 f.close()
42 # Resource files, res.txt, sub/res.txt
43 f = open(os.path.join(package_dir, 'res.txt'), "wb")
44 f.write(RESOURCE_DATA)
45 f.close()
46 os.mkdir(os.path.join(package_dir, 'sub'))
47 f = open(os.path.join(package_dir, 'sub', 'res.txt'), "wb")
48 f.write(RESOURCE_DATA)
49 f.close()
50
51 # Check we can read the resources
52 res1 = pkgutil.get_data(pkg, 'res.txt')
53 self.assertEqual(res1, RESOURCE_DATA)
54 res2 = pkgutil.get_data(pkg, 'sub/res.txt')
55 self.assertEqual(res2, RESOURCE_DATA)
56
57 del sys.modules[pkg]
58
59 def test_getdata_zipfile(self):
60 zip = 'test_getdata_zipfile.zip'
61 pkg = 'test_getdata_zipfile'
62
63 # Include a LF and a CRLF, to test that binary data is read back
64 RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line'
65
66 # Make a package with some resources
67 zip_file = os.path.join(self.dirname, zip)
68 z = zipfile.ZipFile(zip_file, 'w')
69
70 # Empty init.py
71 z.writestr(pkg + '/__init__.py', "")
72 # Resource files, res.txt, sub/res.txt
73 z.writestr(pkg + '/res.txt', RESOURCE_DATA)
74 z.writestr(pkg + '/sub/res.txt', RESOURCE_DATA)
75 z.close()
76
77 # Check we can read the resources
78 sys.path.insert(0, zip_file)
79 res1 = pkgutil.get_data(pkg, 'res.txt')
80 self.assertEqual(res1, RESOURCE_DATA)
81 res2 = pkgutil.get_data(pkg, 'sub/res.txt')
82 self.assertEqual(res2, RESOURCE_DATA)
Alexandre Vassalotti515a74f2009-07-05 06:42:44 +000083
84 names = []
85 for loader, name, ispkg in pkgutil.iter_modules([zip_file]):
86 names.append(name)
87 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
Christian Heimesdae2a892008-04-19 00:55:37 +0000104class PkgutilPEP302Tests(unittest.TestCase):
105
106 class MyTestLoader(object):
Eric Snow37148b22014-01-04 15:09:53 -0700107 def exec_module(self, mod):
Christian Heimesdae2a892008-04-19 00:55:37 +0000108 # Count how many times the module is reloaded
Eric Snow37148b22014-01-04 15:09:53 -0700109 mod.__dict__['loads'] = mod.__dict__.get('loads', 0) + 1
Christian Heimesdae2a892008-04-19 00:55:37 +0000110
111 def get_data(self, path):
112 return "Hello, world!"
113
114 class MyTestImporter(object):
Eric Snow37148b22014-01-04 15:09:53 -0700115 def find_spec(self, fullname, path=None, target=None):
116 loader = PkgutilPEP302Tests.MyTestLoader()
117 return spec_from_file_location(fullname,
118 '<%s>' % loader.__class__.__name__,
119 loader=loader,
120 submodule_search_locations=[])
Christian Heimesdae2a892008-04-19 00:55:37 +0000121
122 def setUp(self):
123 sys.meta_path.insert(0, self.MyTestImporter())
124
125 def tearDown(self):
126 del sys.meta_path[0]
127
128 def test_getdata_pep302(self):
129 # Use a dummy importer/loader
130 self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!")
131 del sys.modules['foo']
132
133 def test_alreadyloaded(self):
134 # Ensure that get_data works without reloading - the "loads" module
135 # variable in the example loader should count how many times a reload
136 # occurs.
137 import foo
138 self.assertEqual(foo.loads, 1)
139 self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!")
140 self.assertEqual(foo.loads, 1)
141 del sys.modules['foo']
142
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400143
Eric V. Smith984b11f2012-05-24 20:21:04 -0400144# These tests, especially the setup and cleanup, are hideous. They
145# need to be cleaned up once issue 14715 is addressed.
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400146class ExtendPathTests(unittest.TestCase):
147 def create_init(self, pkgname):
148 dirname = tempfile.mkdtemp()
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400149 sys.path.insert(0, dirname)
150
151 pkgdir = os.path.join(dirname, pkgname)
152 os.mkdir(pkgdir)
153 with open(os.path.join(pkgdir, '__init__.py'), 'w') as fl:
154 fl.write('from pkgutil import extend_path\n__path__ = extend_path(__path__, __name__)\n')
155
156 return dirname
157
158 def create_submodule(self, dirname, pkgname, submodule_name, value):
159 module_name = os.path.join(dirname, pkgname, submodule_name + '.py')
160 with open(module_name, 'w') as fl:
161 print('value={}'.format(value), file=fl)
162
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400163 def test_simple(self):
Eric V. Smith984b11f2012-05-24 20:21:04 -0400164 pkgname = 'foo'
165 dirname_0 = self.create_init(pkgname)
166 dirname_1 = self.create_init(pkgname)
167 self.create_submodule(dirname_0, pkgname, 'bar', 0)
168 self.create_submodule(dirname_1, pkgname, 'baz', 1)
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400169 import foo.bar
170 import foo.baz
171 # Ensure we read the expected values
172 self.assertEqual(foo.bar.value, 0)
173 self.assertEqual(foo.baz.value, 1)
174
175 # Ensure the path is set up correctly
176 self.assertEqual(sorted(foo.__path__),
Eric V. Smith984b11f2012-05-24 20:21:04 -0400177 sorted([os.path.join(dirname_0, pkgname),
178 os.path.join(dirname_1, pkgname)]))
179
180 # Cleanup
181 shutil.rmtree(dirname_0)
182 shutil.rmtree(dirname_1)
183 del sys.path[0]
184 del sys.path[0]
185 del sys.modules['foo']
186 del sys.modules['foo.bar']
187 del sys.modules['foo.baz']
188
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000189
190 # Another awful testing hack to be cleaned up once the test_runpy
191 # helpers are factored out to a common location
192 def test_iter_importers(self):
193 iter_importers = pkgutil.iter_importers
194 get_importer = pkgutil.get_importer
195
196 pkgname = 'spam'
197 modname = 'eggs'
198 dirname = self.create_init(pkgname)
199 pathitem = os.path.join(dirname, pkgname)
200 fullname = '{}.{}'.format(pkgname, modname)
Eric Snow2ba66eb2013-11-22 13:55:23 -0700201 sys.modules.pop(fullname, None)
202 sys.modules.pop(pkgname, None)
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000203 try:
204 self.create_submodule(dirname, pkgname, modname, 0)
205
206 importlib.import_module(fullname)
207
208 importers = list(iter_importers(fullname))
209 expected_importer = get_importer(pathitem)
210 for finder in importers:
Eric Snow37148b22014-01-04 15:09:53 -0700211 spec = pkgutil._get_spec(finder, fullname)
212 loader = spec.loader
Eric Snowb523f842013-11-22 09:05:39 -0700213 try:
214 loader = loader.loader
215 except AttributeError:
216 # For now we still allow raw loaders from
217 # find_module().
218 pass
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000219 self.assertIsInstance(finder, importlib.machinery.FileFinder)
220 self.assertEqual(finder, expected_importer)
Eric Snowb523f842013-11-22 09:05:39 -0700221 self.assertIsInstance(loader,
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000222 importlib.machinery.SourceFileLoader)
Eric Snow37148b22014-01-04 15:09:53 -0700223 self.assertIsNone(pkgutil._get_spec(finder, pkgname))
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000224
225 with self.assertRaises(ImportError):
226 list(iter_importers('invalid.module'))
227
228 with self.assertRaises(ImportError):
229 list(iter_importers('.spam'))
230 finally:
231 shutil.rmtree(dirname)
232 del sys.path[0]
Eric Snowb523f842013-11-22 09:05:39 -0700233 try:
234 del sys.modules['spam']
235 del sys.modules['spam.eggs']
236 except KeyError:
237 pass
Nick Coghlanc4e0d982013-04-14 22:30:42 +1000238
239
Eric V. Smith984b11f2012-05-24 20:21:04 -0400240 def test_mixed_namespace(self):
241 pkgname = 'foo'
242 dirname_0 = self.create_init(pkgname)
243 dirname_1 = self.create_init(pkgname)
244 self.create_submodule(dirname_0, pkgname, 'bar', 0)
245 # Turn this into a PEP 420 namespace package
246 os.unlink(os.path.join(dirname_0, pkgname, '__init__.py'))
247 self.create_submodule(dirname_1, pkgname, 'baz', 1)
248 import foo.bar
249 import foo.baz
250 # Ensure we read the expected values
251 self.assertEqual(foo.bar.value, 0)
252 self.assertEqual(foo.baz.value, 1)
253
254 # Ensure the path is set up correctly
255 self.assertEqual(sorted(foo.__path__),
256 sorted([os.path.join(dirname_0, pkgname),
257 os.path.join(dirname_1, pkgname)]))
258
259 # Cleanup
260 shutil.rmtree(dirname_0)
261 shutil.rmtree(dirname_1)
262 del sys.path[0]
263 del sys.path[0]
264 del sys.modules['foo']
265 del sys.modules['foo.bar']
266 del sys.modules['foo.baz']
Eric V. Smitha790c9b2012-05-15 20:44:06 -0400267
268 # XXX: test .pkg files
269
270
Antoine Pitroub2dd8802012-07-09 21:23:58 +0200271class NestedNamespacePackageTest(unittest.TestCase):
272
273 def setUp(self):
274 self.basedir = tempfile.mkdtemp()
275 self.old_path = sys.path[:]
276
277 def tearDown(self):
278 sys.path[:] = self.old_path
279 shutil.rmtree(self.basedir)
280
281 def create_module(self, name, contents):
282 base, final = name.rsplit('.', 1)
283 base_path = os.path.join(self.basedir, base.replace('.', os.path.sep))
284 os.makedirs(base_path, exist_ok=True)
285 with open(os.path.join(base_path, final + ".py"), 'w') as f:
286 f.write(contents)
287
288 def test_nested(self):
289 pkgutil_boilerplate = (
290 'import pkgutil; '
291 '__path__ = pkgutil.extend_path(__path__, __name__)')
292 self.create_module('a.pkg.__init__', pkgutil_boilerplate)
293 self.create_module('b.pkg.__init__', pkgutil_boilerplate)
294 self.create_module('a.pkg.subpkg.__init__', pkgutil_boilerplate)
295 self.create_module('b.pkg.subpkg.__init__', pkgutil_boilerplate)
296 self.create_module('a.pkg.subpkg.c', 'c = 1')
297 self.create_module('b.pkg.subpkg.d', 'd = 2')
298 sys.path.insert(0, os.path.join(self.basedir, 'a'))
299 sys.path.insert(0, os.path.join(self.basedir, 'b'))
300 import pkg
301 self.addCleanup(unload, 'pkg')
302 self.assertEqual(len(pkg.__path__), 2)
303 import pkg.subpkg
304 self.addCleanup(unload, 'pkg.subpkg')
305 self.assertEqual(len(pkg.subpkg.__path__), 2)
306 from pkg.subpkg.c import c
307 from pkg.subpkg.d import d
308 self.assertEqual(c, 1)
309 self.assertEqual(d, 2)
310
311
Nick Coghlan85e729e2012-07-15 18:09:52 +1000312class ImportlibMigrationTests(unittest.TestCase):
313 # With full PEP 302 support in the standard import machinery, the
314 # PEP 302 emulation in this module is in the process of being
315 # deprecated in favour of importlib proper
316
317 def check_deprecated(self):
318 return check_warnings(
319 ("This emulation is deprecated, use 'importlib' instead",
320 DeprecationWarning))
321
322 def test_importer_deprecated(self):
323 with self.check_deprecated():
324 x = pkgutil.ImpImporter("")
325
326 def test_loader_deprecated(self):
327 with self.check_deprecated():
328 x = pkgutil.ImpLoader("", "", "", "")
329
330 def test_get_loader_avoids_emulation(self):
331 with check_warnings() as w:
332 self.assertIsNotNone(pkgutil.get_loader("sys"))
333 self.assertIsNotNone(pkgutil.get_loader("os"))
334 self.assertIsNotNone(pkgutil.get_loader("test.support"))
335 self.assertEqual(len(w.warnings), 0)
336
Nick Coghlandc855b72014-03-04 20:39:42 +1000337 def test_get_loader_handles_missing_loader_attribute(self):
338 global __loader__
339 this_loader = __loader__
340 del __loader__
341 try:
342 with check_warnings() as w:
343 self.assertIsNotNone(pkgutil.get_loader(__name__))
344 self.assertEqual(len(w.warnings), 0)
345 finally:
346 __loader__ = this_loader
347
Eric Snow658af312014-04-19 00:13:23 -0600348 def test_get_loader_handles_missing_spec_attribute(self):
349 name = 'spam'
350 mod = type(sys)(name)
351 del mod.__spec__
352 with CleanImport(name):
353 sys.modules[name] = mod
354 loader = pkgutil.get_loader(name)
355 self.assertIsNone(loader)
356
357 def test_get_loader_handles_spec_attribute_none(self):
358 name = 'spam'
359 mod = type(sys)(name)
360 mod.__spec__ = None
361 with CleanImport(name):
362 sys.modules[name] = mod
363 loader = pkgutil.get_loader(name)
364 self.assertIsNone(loader)
Nick Coghlandc855b72014-03-04 20:39:42 +1000365
Brett Cannon8447c702014-05-23 12:30:37 -0400366 def test_get_loader_None_in_sys_modules(self):
367 name = 'totally bogus'
368 sys.modules[name] = None
369 try:
370 loader = pkgutil.get_loader(name)
371 finally:
372 del sys.modules[name]
373 self.assertIsNone(loader)
374
375 def test_find_loader_missing_module(self):
376 name = 'totally bogus'
377 loader = pkgutil.find_loader(name)
378 self.assertIsNone(loader)
379
Nick Coghlandc855b72014-03-04 20:39:42 +1000380 def test_find_loader_avoids_emulation(self):
381 with check_warnings() as w:
382 self.assertIsNotNone(pkgutil.find_loader("sys"))
383 self.assertIsNotNone(pkgutil.find_loader("os"))
384 self.assertIsNotNone(pkgutil.find_loader("test.support"))
385 self.assertEqual(len(w.warnings), 0)
386
Nick Coghlan85e729e2012-07-15 18:09:52 +1000387 def test_get_importer_avoids_emulation(self):
Nick Coghlan94554922012-07-17 21:37:58 +1000388 # We use an illegal path so *none* of the path hooks should fire
Nick Coghlan85e729e2012-07-15 18:09:52 +1000389 with check_warnings() as w:
Nick Coghlan94554922012-07-17 21:37:58 +1000390 self.assertIsNone(pkgutil.get_importer("*??"))
Nick Coghlan85e729e2012-07-15 18:09:52 +1000391 self.assertEqual(len(w.warnings), 0)
392
393 def test_iter_importers_avoids_emulation(self):
394 with check_warnings() as w:
395 for importer in pkgutil.iter_importers(): pass
396 self.assertEqual(len(w.warnings), 0)
397
398
Christian Heimesdae2a892008-04-19 00:55:37 +0000399def test_main():
Antoine Pitroub2dd8802012-07-09 21:23:58 +0200400 run_unittest(PkgutilTests, PkgutilPEP302Tests, ExtendPathTests,
Nick Coghlan85e729e2012-07-15 18:09:52 +1000401 NestedNamespacePackageTest, ImportlibMigrationTests)
Benjamin Petersoncf626032014-02-16 14:52:01 -0500402 # this is necessary if test is run repeated (like when finding leaks)
403 import zipimport
404 import importlib
405 zipimport._zip_directory_cache.clear()
406 importlib.invalidate_caches()
Nick Coghlan85e729e2012-07-15 18:09:52 +1000407
Christian Heimesdae2a892008-04-19 00:55:37 +0000408
409if __name__ == '__main__':
410 test_main()