| 1 |
from pathlib import Path |
| 2 |
from test.support.import_helper import unload |
| 3 |
from test.support.warnings_helper import check_warnings |
| 4 |
import unittest |
| 5 |
import sys |
| 6 |
import importlib |
| 7 |
from importlib.util import spec_from_file_location |
| 8 |
import pkgutil |
| 9 |
import os |
| 10 |
import os.path |
| 11 |
import tempfile |
| 12 |
import shutil |
| 13 |
import zipfile |
| 14 |
|
| 15 |
from test.support.import_helper import DirsOnSysPath |
| 16 |
from test.support.os_helper import FakePath |
| 17 |
from test.test_importlib.util import uncache |
| 18 |
|
| 19 |
# Note: pkgutil.walk_packages is currently tested in test_runpy. This is |
| 20 |
# a hack to get a major issue resolved for 3.3b2. Longer term, it should |
| 21 |
# be moved back here, perhaps by factoring out the helper code for |
| 22 |
# creating interesting package layouts to a separate module. |
| 23 |
# Issue #15348 declares this is indeed a dodgy hack ;) |
| 24 |
|
| 25 |
class PkgutilTests(unittest.TestCase): |
| 26 |
|
| 27 |
def setUp(self): |
| 28 |
self.dirname = tempfile.mkdtemp() |
| 29 |
self.addCleanup(shutil.rmtree, self.dirname) |
| 30 |
sys.path.insert(0, self.dirname) |
| 31 |
|
| 32 |
def tearDown(self): |
| 33 |
del sys.path[0] |
| 34 |
|
| 35 |
def test_getdata_filesys(self): |
| 36 |
pkg = 'test_getdata_filesys' |
| 37 |
|
| 38 |
# Include a LF and a CRLF, to test that binary data is read back |
| 39 |
RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line' |
| 40 |
|
| 41 |
# Make a package with some resources |
| 42 |
package_dir = os.path.join(self.dirname, pkg) |
| 43 |
os.mkdir(package_dir) |
| 44 |
# Empty init.py |
| 45 |
f = open(os.path.join(package_dir, '__init__.py'), "wb") |
| 46 |
f.close() |
| 47 |
# Resource files, res.txt, sub/res.txt |
| 48 |
f = open(os.path.join(package_dir, 'res.txt'), "wb") |
| 49 |
f.write(RESOURCE_DATA) |
| 50 |
f.close() |
| 51 |
os.mkdir(os.path.join(package_dir, 'sub')) |
| 52 |
f = open(os.path.join(package_dir, 'sub', 'res.txt'), "wb") |
| 53 |
f.write(RESOURCE_DATA) |
| 54 |
f.close() |
| 55 |
|
| 56 |
# Check we can read the resources |
| 57 |
res1 = pkgutil.get_data(pkg, 'res.txt') |
| 58 |
self.assertEqual(res1, RESOURCE_DATA) |
| 59 |
res2 = pkgutil.get_data(pkg, 'sub/res.txt') |
| 60 |
self.assertEqual(res2, RESOURCE_DATA) |
| 61 |
|
| 62 |
del sys.modules[pkg] |
| 63 |
|
| 64 |
def test_getdata_zipfile(self): |
| 65 |
zip = 'test_getdata_zipfile.zip' |
| 66 |
pkg = 'test_getdata_zipfile' |
| 67 |
|
| 68 |
# Include a LF and a CRLF, to test that binary data is read back |
| 69 |
RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line' |
| 70 |
|
| 71 |
# Make a package with some resources |
| 72 |
zip_file = os.path.join(self.dirname, zip) |
| 73 |
z = zipfile.ZipFile(zip_file, 'w') |
| 74 |
|
| 75 |
# Empty init.py |
| 76 |
z.writestr(pkg + '/__init__.py', "") |
| 77 |
# Resource files, res.txt, sub/res.txt |
| 78 |
z.writestr(pkg + '/res.txt', RESOURCE_DATA) |
| 79 |
z.writestr(pkg + '/sub/res.txt', RESOURCE_DATA) |
| 80 |
z.close() |
| 81 |
|
| 82 |
# Check we can read the resources |
| 83 |
sys.path.insert(0, zip_file) |
| 84 |
res1 = pkgutil.get_data(pkg, 'res.txt') |
| 85 |
self.assertEqual(res1, RESOURCE_DATA) |
| 86 |
res2 = pkgutil.get_data(pkg, 'sub/res.txt') |
| 87 |
self.assertEqual(res2, RESOURCE_DATA) |
| 88 |
|
| 89 |
names = [] |
| 90 |
for moduleinfo in pkgutil.iter_modules([zip_file]): |
| 91 |
self.assertIsInstance(moduleinfo, pkgutil.ModuleInfo) |
| 92 |
names.append(moduleinfo.name) |
| 93 |
self.assertEqual(names, ['test_getdata_zipfile']) |
| 94 |
|
| 95 |
del sys.path[0] |
| 96 |
|
| 97 |
del sys.modules[pkg] |
| 98 |
|
| 99 |
def test_issue44061_iter_modules(self): |
| 100 |
#see: issue44061 |
| 101 |
zip = 'test_getdata_zipfile.zip' |
| 102 |
pkg = 'test_getdata_zipfile' |
| 103 |
|
| 104 |
# Include a LF and a CRLF, to test that binary data is read back |
| 105 |
RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line' |
| 106 |
|
| 107 |
# Make a package with some resources |
| 108 |
zip_file = os.path.join(self.dirname, zip) |
| 109 |
z = zipfile.ZipFile(zip_file, 'w') |
| 110 |
|
| 111 |
# Empty init.py |
| 112 |
z.writestr(pkg + '/__init__.py', "") |
| 113 |
# Resource files, res.txt |
| 114 |
z.writestr(pkg + '/res.txt', RESOURCE_DATA) |
| 115 |
z.close() |
| 116 |
|
| 117 |
# Check we can read the resources |
| 118 |
sys.path.insert(0, zip_file) |
| 119 |
try: |
| 120 |
res = pkgutil.get_data(pkg, 'res.txt') |
| 121 |
self.assertEqual(res, RESOURCE_DATA) |
| 122 |
|
| 123 |
# make sure iter_modules accepts Path objects |
| 124 |
names = [] |
| 125 |
for moduleinfo in pkgutil.iter_modules([FakePath(zip_file)]): |
| 126 |
self.assertIsInstance(moduleinfo, pkgutil.ModuleInfo) |
| 127 |
names.append(moduleinfo.name) |
| 128 |
self.assertEqual(names, [pkg]) |
| 129 |
finally: |
| 130 |
del sys.path[0] |
| 131 |
sys.modules.pop(pkg, None) |
| 132 |
|
| 133 |
# assert path must be None or list of paths |
| 134 |
expected_msg = "path must be None or list of paths to look for modules in" |
| 135 |
with self.assertRaisesRegex(ValueError, expected_msg): |
| 136 |
list(pkgutil.iter_modules("invalid_path")) |
| 137 |
|
| 138 |
def test_unreadable_dir_on_syspath(self): |
| 139 |
# issue7367 - walk_packages failed if unreadable dir on sys.path |
| 140 |
package_name = "unreadable_package" |
| 141 |
d = os.path.join(self.dirname, package_name) |
| 142 |
# this does not appear to create an unreadable dir on Windows |
| 143 |
# but the test should not fail anyway |
| 144 |
os.mkdir(d, 0) |
| 145 |
self.addCleanup(os.rmdir, d) |
| 146 |
for t in pkgutil.walk_packages(path=[self.dirname]): |
| 147 |
self.fail("unexpected package found") |
| 148 |
|
| 149 |
def test_walkpackages_filesys(self): |
| 150 |
pkg1 = 'test_walkpackages_filesys' |
| 151 |
pkg1_dir = os.path.join(self.dirname, pkg1) |
| 152 |
os.mkdir(pkg1_dir) |
| 153 |
f = open(os.path.join(pkg1_dir, '__init__.py'), "wb") |
| 154 |
f.close() |
| 155 |
os.mkdir(os.path.join(pkg1_dir, 'sub')) |
| 156 |
f = open(os.path.join(pkg1_dir, 'sub', '__init__.py'), "wb") |
| 157 |
f.close() |
| 158 |
f = open(os.path.join(pkg1_dir, 'sub', 'mod.py'), "wb") |
| 159 |
f.close() |
| 160 |
|
| 161 |
# Now, to juice it up, let's add the opposite packages, too. |
| 162 |
pkg2 = 'sub' |
| 163 |
pkg2_dir = os.path.join(self.dirname, pkg2) |
| 164 |
os.mkdir(pkg2_dir) |
| 165 |
f = open(os.path.join(pkg2_dir, '__init__.py'), "wb") |
| 166 |
f.close() |
| 167 |
os.mkdir(os.path.join(pkg2_dir, 'test_walkpackages_filesys')) |
| 168 |
f = open(os.path.join(pkg2_dir, 'test_walkpackages_filesys', '__init__.py'), "wb") |
| 169 |
f.close() |
| 170 |
f = open(os.path.join(pkg2_dir, 'test_walkpackages_filesys', 'mod.py'), "wb") |
| 171 |
f.close() |
| 172 |
|
| 173 |
expected = [ |
| 174 |
'sub', |
| 175 |
'sub.test_walkpackages_filesys', |
| 176 |
'sub.test_walkpackages_filesys.mod', |
| 177 |
'test_walkpackages_filesys', |
| 178 |
'test_walkpackages_filesys.sub', |
| 179 |
'test_walkpackages_filesys.sub.mod', |
| 180 |
] |
| 181 |
actual= [e[1] for e in pkgutil.walk_packages([self.dirname])] |
| 182 |
self.assertEqual(actual, expected) |
| 183 |
|
| 184 |
for pkg in expected: |
| 185 |
if pkg.endswith('mod'): |
| 186 |
continue |
| 187 |
del sys.modules[pkg] |
| 188 |
|
| 189 |
def test_walkpackages_zipfile(self): |
| 190 |
"""Tests the same as test_walkpackages_filesys, only with a zip file.""" |
| 191 |
|
| 192 |
zip = 'test_walkpackages_zipfile.zip' |
| 193 |
pkg1 = 'test_walkpackages_zipfile' |
| 194 |
pkg2 = 'sub' |
| 195 |
|
| 196 |
zip_file = os.path.join(self.dirname, zip) |
| 197 |
z = zipfile.ZipFile(zip_file, 'w') |
| 198 |
z.writestr(pkg2 + '/__init__.py', "") |
| 199 |
z.writestr(pkg2 + '/' + pkg1 + '/__init__.py', "") |
| 200 |
z.writestr(pkg2 + '/' + pkg1 + '/mod.py', "") |
| 201 |
z.writestr(pkg1 + '/__init__.py', "") |
| 202 |
z.writestr(pkg1 + '/' + pkg2 + '/__init__.py', "") |
| 203 |
z.writestr(pkg1 + '/' + pkg2 + '/mod.py', "") |
| 204 |
z.close() |
| 205 |
|
| 206 |
sys.path.insert(0, zip_file) |
| 207 |
expected = [ |
| 208 |
'sub', |
| 209 |
'sub.test_walkpackages_zipfile', |
| 210 |
'sub.test_walkpackages_zipfile.mod', |
| 211 |
'test_walkpackages_zipfile', |
| 212 |
'test_walkpackages_zipfile.sub', |
| 213 |
'test_walkpackages_zipfile.sub.mod', |
| 214 |
] |
| 215 |
actual= [e[1] for e in pkgutil.walk_packages([zip_file])] |
| 216 |
self.assertEqual(actual, expected) |
| 217 |
del sys.path[0] |
| 218 |
|
| 219 |
for pkg in expected: |
| 220 |
if pkg.endswith('mod'): |
| 221 |
continue |
| 222 |
del sys.modules[pkg] |
| 223 |
|
| 224 |
def test_walk_packages_raises_on_string_or_bytes_input(self): |
| 225 |
|
| 226 |
str_input = 'test_dir' |
| 227 |
with self.assertRaises((TypeError, ValueError)): |
| 228 |
list(pkgutil.walk_packages(str_input)) |
| 229 |
|
| 230 |
bytes_input = b'test_dir' |
| 231 |
with self.assertRaises((TypeError, ValueError)): |
| 232 |
list(pkgutil.walk_packages(bytes_input)) |
| 233 |
|
| 234 |
def test_name_resolution(self): |
| 235 |
import logging |
| 236 |
import logging.handlers |
| 237 |
|
| 238 |
success_cases = ( |
| 239 |
('os', os), |
| 240 |
('os.path', os.path), |
| 241 |
('os.path:pathsep', os.path.pathsep), |
| 242 |
('logging', logging), |
| 243 |
('logging:', logging), |
| 244 |
('logging.handlers', logging.handlers), |
| 245 |
('logging.handlers:', logging.handlers), |
| 246 |
('logging.handlers:SysLogHandler', logging.handlers.SysLogHandler), |
| 247 |
('logging.handlers.SysLogHandler', logging.handlers.SysLogHandler), |
| 248 |
('logging.handlers:SysLogHandler.LOG_ALERT', |
| 249 |
logging.handlers.SysLogHandler.LOG_ALERT), |
| 250 |
('logging.handlers.SysLogHandler.LOG_ALERT', |
| 251 |
logging.handlers.SysLogHandler.LOG_ALERT), |
| 252 |
('builtins.int', int), |
| 253 |
('builtins:int', int), |
| 254 |
('builtins.int.from_bytes', int.from_bytes), |
| 255 |
('builtins:int.from_bytes', int.from_bytes), |
| 256 |
('builtins.ZeroDivisionError', ZeroDivisionError), |
| 257 |
('builtins:ZeroDivisionError', ZeroDivisionError), |
| 258 |
('os:path', os.path), |
| 259 |
) |
| 260 |
|
| 261 |
failure_cases = ( |
| 262 |
(None, TypeError), |
| 263 |
(1, TypeError), |
| 264 |
(2.0, TypeError), |
| 265 |
(True, TypeError), |
| 266 |
('', ValueError), |
| 267 |
('?abc', ValueError), |
| 268 |
('abc/foo', ValueError), |
| 269 |
('foo', ImportError), |
| 270 |
('os.foo', AttributeError), |
| 271 |
('os.foo:', ImportError), |
| 272 |
('os.pth:pathsep', ImportError), |
| 273 |
('logging.handlers:NoSuchHandler', AttributeError), |
| 274 |
('logging.handlers:SysLogHandler.NO_SUCH_VALUE', AttributeError), |
| 275 |
('logging.handlers.SysLogHandler.NO_SUCH_VALUE', AttributeError), |
| 276 |
('ZeroDivisionError', ImportError), |
| 277 |
('os.path.9abc', ValueError), |
| 278 |
('9abc', ValueError), |
| 279 |
) |
| 280 |
|
| 281 |
# add some Unicode package names to the mix. |
| 282 |
|
| 283 |
unicode_words = ('\u0935\u092e\u0938', |
| 284 |
'\xe9', '\xc8', |
| 285 |
'\uc548\ub155\ud558\uc138\uc694', |
| 286 |
'\u3055\u3088\u306a\u3089', |
| 287 |
'\u3042\u308a\u304c\u3068\u3046', |
| 288 |
'\u0425\u043e\u0440\u043e\u0448\u043e', |
| 289 |
'\u0441\u043f\u0430\u0441\u0438\u0431\u043e', |
| 290 |
'\u73b0\u4ee3\u6c49\u8bed\u5e38\u7528\u5b57\u8868') |
| 291 |
|
| 292 |
for uw in unicode_words: |
| 293 |
d = os.path.join(self.dirname, uw) |
| 294 |
try: |
| 295 |
os.makedirs(d, exist_ok=True) |
| 296 |
except UnicodeEncodeError: |
| 297 |
# When filesystem encoding cannot encode uw: skip this test |
| 298 |
continue |
| 299 |
# make an empty __init__.py file |
| 300 |
f = os.path.join(d, '__init__.py') |
| 301 |
with open(f, 'w') as f: |
| 302 |
f.write('') |
| 303 |
f.flush() |
| 304 |
# now import the package we just created; clearing the caches is |
| 305 |
# needed, otherwise the newly created package isn't found |
| 306 |
importlib.invalidate_caches() |
| 307 |
mod = importlib.import_module(uw) |
| 308 |
success_cases += (uw, mod), |
| 309 |
if len(uw) > 1: |
| 310 |
failure_cases += (uw[:-1], ImportError), |
| 311 |
|
| 312 |
# add an example with a Unicode digit at the start |
| 313 |
failure_cases += ('\u0966\u0935\u092e\u0938', ValueError), |
| 314 |
|
| 315 |
for s, expected in success_cases: |
| 316 |
with self.subTest(s=s): |
| 317 |
o = pkgutil.resolve_name(s) |
| 318 |
self.assertEqual(o, expected) |
| 319 |
|
| 320 |
for s, exc in failure_cases: |
| 321 |
with self.subTest(s=s): |
| 322 |
with self.assertRaises(exc): |
| 323 |
pkgutil.resolve_name(s) |
| 324 |
|
| 325 |
def test_name_resolution_import_rebinding(self): |
| 326 |
# The same data is also used for testing import in test_import and |
| 327 |
# mock.patch in test_unittest. |
| 328 |
path = os.path.join(os.path.dirname(__file__), 'test_import', 'data') |
| 329 |
with uncache('package3', 'package3.submodule'), DirsOnSysPath(path): |
| 330 |
self.assertEqual(pkgutil.resolve_name('package3.submodule.attr'), 'submodule') |
| 331 |
with uncache('package3', 'package3.submodule'), DirsOnSysPath(path): |
| 332 |
self.assertEqual(pkgutil.resolve_name('package3.submodule:attr'), 'submodule') |
| 333 |
with uncache('package3', 'package3.submodule'), DirsOnSysPath(path): |
| 334 |
self.assertEqual(pkgutil.resolve_name('package3:submodule.attr'), 'rebound') |
| 335 |
self.assertEqual(pkgutil.resolve_name('package3.submodule.attr'), 'submodule') |
| 336 |
self.assertEqual(pkgutil.resolve_name('package3:submodule.attr'), 'rebound') |
| 337 |
with uncache('package3', 'package3.submodule'), DirsOnSysPath(path): |
| 338 |
self.assertEqual(pkgutil.resolve_name('package3:submodule.attr'), 'rebound') |
| 339 |
self.assertEqual(pkgutil.resolve_name('package3.submodule:attr'), 'submodule') |
| 340 |
self.assertEqual(pkgutil.resolve_name('package3:submodule.attr'), 'rebound') |
| 341 |
|
| 342 |
def test_name_resolution_import_rebinding2(self): |
| 343 |
path = os.path.join(os.path.dirname(__file__), 'test_import', 'data') |
| 344 |
with uncache('package4', 'package4.submodule'), DirsOnSysPath(path): |
| 345 |
self.assertEqual(pkgutil.resolve_name('package4.submodule.attr'), 'submodule') |
| 346 |
with uncache('package4', 'package4.submodule'), DirsOnSysPath(path): |
| 347 |
self.assertEqual(pkgutil.resolve_name('package4.submodule:attr'), 'submodule') |
| 348 |
with uncache('package4', 'package4.submodule'), DirsOnSysPath(path): |
| 349 |
self.assertEqual(pkgutil.resolve_name('package4:submodule.attr'), 'origin') |
| 350 |
self.assertEqual(pkgutil.resolve_name('package4.submodule.attr'), 'submodule') |
| 351 |
self.assertEqual(pkgutil.resolve_name('package4:submodule.attr'), 'submodule') |
| 352 |
with uncache('package4', 'package4.submodule'), DirsOnSysPath(path): |
| 353 |
self.assertEqual(pkgutil.resolve_name('package4:submodule.attr'), 'origin') |
| 354 |
self.assertEqual(pkgutil.resolve_name('package4.submodule:attr'), 'submodule') |
| 355 |
self.assertEqual(pkgutil.resolve_name('package4:submodule.attr'), 'submodule') |
| 356 |
|
| 357 |
|
| 358 |
class PkgutilPEP302Tests(unittest.TestCase): |
| 359 |
|
| 360 |
class MyTestLoader(object): |
| 361 |
def create_module(self, spec): |
| 362 |
return None |
| 363 |
|
| 364 |
def exec_module(self, mod): |
| 365 |
# Count how many times the module is reloaded |
| 366 |
mod.__dict__['loads'] = mod.__dict__.get('loads', 0) + 1 |
| 367 |
|
| 368 |
def get_data(self, path): |
| 369 |
return "Hello, world!" |
| 370 |
|
| 371 |
class MyTestImporter(object): |
| 372 |
def find_spec(self, fullname, path=None, target=None): |
| 373 |
loader = PkgutilPEP302Tests.MyTestLoader() |
| 374 |
return spec_from_file_location(fullname, |
| 375 |
'<%s>' % loader.__class__.__name__, |
| 376 |
loader=loader, |
| 377 |
submodule_search_locations=[]) |
| 378 |
|
| 379 |
def setUp(self): |
| 380 |
sys.meta_path.insert(0, self.MyTestImporter()) |
| 381 |
|
| 382 |
def tearDown(self): |
| 383 |
del sys.meta_path[0] |
| 384 |
|
| 385 |
def test_getdata_pep302(self): |
| 386 |
# Use a dummy finder/loader |
| 387 |
self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!") |
| 388 |
del sys.modules['foo'] |
| 389 |
|
| 390 |
def test_alreadyloaded(self): |
| 391 |
# Ensure that get_data works without reloading - the "loads" module |
| 392 |
# variable in the example loader should count how many times a reload |
| 393 |
# occurs. |
| 394 |
import foo |
| 395 |
self.assertEqual(foo.loads, 1) |
| 396 |
self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!") |
| 397 |
self.assertEqual(foo.loads, 1) |
| 398 |
del sys.modules['foo'] |
| 399 |
|
| 400 |
|
| 401 |
# These tests, especially the setup and cleanup, are hideous. They |
| 402 |
# need to be cleaned up once issue 14715 is addressed. |
| 403 |
class ExtendPathTests(unittest.TestCase): |
| 404 |
def create_init(self, pkgname): |
| 405 |
dirname = tempfile.mkdtemp() |
| 406 |
sys.path.insert(0, dirname) |
| 407 |
|
| 408 |
pkgdir = os.path.join(dirname, pkgname) |
| 409 |
os.mkdir(pkgdir) |
| 410 |
with open(os.path.join(pkgdir, '__init__.py'), 'w') as fl: |
| 411 |
fl.write('from pkgutil import extend_path\n__path__ = extend_path(__path__, __name__)\n') |
| 412 |
|
| 413 |
return dirname |
| 414 |
|
| 415 |
def create_submodule(self, dirname, pkgname, submodule_name, value): |
| 416 |
module_name = os.path.join(dirname, pkgname, submodule_name + '.py') |
| 417 |
with open(module_name, 'w') as fl: |
| 418 |
print('value={}'.format(value), file=fl) |
| 419 |
|
| 420 |
def test_simple(self): |
| 421 |
pkgname = 'foo' |
| 422 |
dirname_0 = self.create_init(pkgname) |
| 423 |
dirname_1 = self.create_init(pkgname) |
| 424 |
self.create_submodule(dirname_0, pkgname, 'bar', 0) |
| 425 |
self.create_submodule(dirname_1, pkgname, 'baz', 1) |
| 426 |
import foo.bar |
| 427 |
import foo.baz |
| 428 |
# Ensure we read the expected values |
| 429 |
self.assertEqual(foo.bar.value, 0) |
| 430 |
self.assertEqual(foo.baz.value, 1) |
| 431 |
|
| 432 |
# Ensure the path is set up correctly |
| 433 |
self.assertEqual(sorted(foo.__path__), |
| 434 |
sorted([os.path.join(dirname_0, pkgname), |
| 435 |
os.path.join(dirname_1, pkgname)])) |
| 436 |
|
| 437 |
# Cleanup |
| 438 |
shutil.rmtree(dirname_0) |
| 439 |
shutil.rmtree(dirname_1) |
| 440 |
del sys.path[0] |
| 441 |
del sys.path[0] |
| 442 |
del sys.modules['foo'] |
| 443 |
del sys.modules['foo.bar'] |
| 444 |
del sys.modules['foo.baz'] |
| 445 |
|
| 446 |
|
| 447 |
# Another awful testing hack to be cleaned up once the test_runpy |
| 448 |
# helpers are factored out to a common location |
| 449 |
def test_iter_importers(self): |
| 450 |
iter_importers = pkgutil.iter_importers |
| 451 |
get_importer = pkgutil.get_importer |
| 452 |
|
| 453 |
pkgname = 'spam' |
| 454 |
modname = 'eggs' |
| 455 |
dirname = self.create_init(pkgname) |
| 456 |
pathitem = os.path.join(dirname, pkgname) |
| 457 |
fullname = '{}.{}'.format(pkgname, modname) |
| 458 |
sys.modules.pop(fullname, None) |
| 459 |
sys.modules.pop(pkgname, None) |
| 460 |
try: |
| 461 |
self.create_submodule(dirname, pkgname, modname, 0) |
| 462 |
|
| 463 |
importlib.import_module(fullname) |
| 464 |
|
| 465 |
importers = list(iter_importers(fullname)) |
| 466 |
expected_importer = get_importer(pathitem) |
| 467 |
for finder in importers: |
| 468 |
spec = finder.find_spec(fullname) |
| 469 |
loader = spec.loader |
| 470 |
try: |
| 471 |
loader = loader.loader |
| 472 |
except AttributeError: |
| 473 |
# For now we still allow raw loaders from |
| 474 |
# find_module(). |
| 475 |
pass |
| 476 |
self.assertIsInstance(finder, importlib.machinery.FileFinder) |
| 477 |
self.assertEqual(finder, expected_importer) |
| 478 |
self.assertIsInstance(loader, |
| 479 |
importlib.machinery.SourceFileLoader) |
| 480 |
self.assertIsNone(finder.find_spec(pkgname)) |
| 481 |
|
| 482 |
with self.assertRaises(ImportError): |
| 483 |
list(iter_importers('invalid.module')) |
| 484 |
|
| 485 |
with self.assertRaises(ImportError): |
| 486 |
list(iter_importers('.spam')) |
| 487 |
finally: |
| 488 |
shutil.rmtree(dirname) |
| 489 |
del sys.path[0] |
| 490 |
try: |
| 491 |
del sys.modules['spam'] |
| 492 |
del sys.modules['spam.eggs'] |
| 493 |
except KeyError: |
| 494 |
pass |
| 495 |
|
| 496 |
|
| 497 |
def test_mixed_namespace(self): |
| 498 |
pkgname = 'foo' |
| 499 |
dirname_0 = self.create_init(pkgname) |
| 500 |
dirname_1 = self.create_init(pkgname) |
| 501 |
self.create_submodule(dirname_0, pkgname, 'bar', 0) |
| 502 |
# Turn this into a PEP 420 namespace package |
| 503 |
os.unlink(os.path.join(dirname_0, pkgname, '__init__.py')) |
| 504 |
self.create_submodule(dirname_1, pkgname, 'baz', 1) |
| 505 |
import foo.bar |
| 506 |
import foo.baz |
| 507 |
# Ensure we read the expected values |
| 508 |
self.assertEqual(foo.bar.value, 0) |
| 509 |
self.assertEqual(foo.baz.value, 1) |
| 510 |
|
| 511 |
# Ensure the path is set up correctly |
| 512 |
self.assertEqual(sorted(foo.__path__), |
| 513 |
sorted([os.path.join(dirname_0, pkgname), |
| 514 |
os.path.join(dirname_1, pkgname)])) |
| 515 |
|
| 516 |
# Cleanup |
| 517 |
shutil.rmtree(dirname_0) |
| 518 |
shutil.rmtree(dirname_1) |
| 519 |
del sys.path[0] |
| 520 |
del sys.path[0] |
| 521 |
del sys.modules['foo'] |
| 522 |
del sys.modules['foo.bar'] |
| 523 |
del sys.modules['foo.baz'] |
| 524 |
|
| 525 |
|
| 526 |
def test_extend_path_argument_types(self): |
| 527 |
pkgname = 'foo' |
| 528 |
dirname_0 = self.create_init(pkgname) |
| 529 |
|
| 530 |
# If the input path is not a list it is returned unchanged |
| 531 |
self.assertEqual('notalist', pkgutil.extend_path('notalist', 'foo')) |
| 532 |
self.assertEqual(('not', 'a', 'list'), pkgutil.extend_path(('not', 'a', 'list'), 'foo')) |
| 533 |
self.assertEqual(123, pkgutil.extend_path(123, 'foo')) |
| 534 |
self.assertEqual(None, pkgutil.extend_path(None, 'foo')) |
| 535 |
|
| 536 |
# Cleanup |
| 537 |
shutil.rmtree(dirname_0) |
| 538 |
del sys.path[0] |
| 539 |
|
| 540 |
|
| 541 |
def test_extend_path_pkg_files(self): |
| 542 |
pkgname = 'foo' |
| 543 |
dirname_0 = self.create_init(pkgname) |
| 544 |
|
| 545 |
with open(os.path.join(dirname_0, 'bar.pkg'), 'w') as pkg_file: |
| 546 |
pkg_file.write('\n'.join([ |
| 547 |
'baz', |
| 548 |
'/foo/bar/baz', |
| 549 |
'', |
| 550 |
'#comment' |
| 551 |
])) |
| 552 |
|
| 553 |
extended_paths = pkgutil.extend_path(sys.path, 'bar') |
| 554 |
|
| 555 |
self.assertEqual(extended_paths[:-2], sys.path) |
| 556 |
self.assertEqual(extended_paths[-2], 'baz') |
| 557 |
self.assertEqual(extended_paths[-1], '/foo/bar/baz') |
| 558 |
|
| 559 |
# Cleanup |
| 560 |
shutil.rmtree(dirname_0) |
| 561 |
del sys.path[0] |
| 562 |
|
| 563 |
|
| 564 |
class NestedNamespacePackageTest(unittest.TestCase): |
| 565 |
|
| 566 |
def setUp(self): |
| 567 |
self.basedir = tempfile.mkdtemp() |
| 568 |
self.old_path = sys.path[:] |
| 569 |
|
| 570 |
def tearDown(self): |
| 571 |
sys.path[:] = self.old_path |
| 572 |
shutil.rmtree(self.basedir) |
| 573 |
|
| 574 |
def create_module(self, name, contents): |
| 575 |
base, final = name.rsplit('.', 1) |
| 576 |
base_path = os.path.join(self.basedir, base.replace('.', os.path.sep)) |
| 577 |
os.makedirs(base_path, exist_ok=True) |
| 578 |
with open(os.path.join(base_path, final + ".py"), 'w') as f: |
| 579 |
f.write(contents) |
| 580 |
|
| 581 |
def test_nested(self): |
| 582 |
pkgutil_boilerplate = ( |
| 583 |
'import pkgutil; ' |
| 584 |
'__path__ = pkgutil.extend_path(__path__, __name__)') |
| 585 |
self.create_module('a.pkg.__init__', pkgutil_boilerplate) |
| 586 |
self.create_module('b.pkg.__init__', pkgutil_boilerplate) |
| 587 |
self.create_module('a.pkg.subpkg.__init__', pkgutil_boilerplate) |
| 588 |
self.create_module('b.pkg.subpkg.__init__', pkgutil_boilerplate) |
| 589 |
self.create_module('a.pkg.subpkg.c', 'c = 1') |
| 590 |
self.create_module('b.pkg.subpkg.d', 'd = 2') |
| 591 |
sys.path.insert(0, os.path.join(self.basedir, 'a')) |
| 592 |
sys.path.insert(0, os.path.join(self.basedir, 'b')) |
| 593 |
import pkg |
| 594 |
self.addCleanup(unload, 'pkg') |
| 595 |
self.assertEqual(len(pkg.__path__), 2) |
| 596 |
import pkg.subpkg |
| 597 |
self.addCleanup(unload, 'pkg.subpkg') |
| 598 |
self.assertEqual(len(pkg.subpkg.__path__), 2) |
| 599 |
from pkg.subpkg.c import c |
| 600 |
from pkg.subpkg.d import d |
| 601 |
self.assertEqual(c, 1) |
| 602 |
self.assertEqual(d, 2) |
| 603 |
|
| 604 |
|
| 605 |
class ImportlibMigrationTests(unittest.TestCase): |
| 606 |
# With full PEP 302 support in the standard import machinery, the |
| 607 |
# PEP 302 emulation in this module is in the process of being |
| 608 |
# deprecated in favour of importlib proper |
| 609 |
|
| 610 |
def test_get_importer_avoids_emulation(self): |
| 611 |
# We use an illegal path so *none* of the path hooks should fire |
| 612 |
with check_warnings() as w: |
| 613 |
self.assertIsNone(pkgutil.get_importer("*??")) |
| 614 |
self.assertEqual(len(w.warnings), 0) |
| 615 |
|
| 616 |
def test_issue44061(self): |
| 617 |
try: |
| 618 |
pkgutil.get_importer(Path("/home")) |
| 619 |
except AttributeError: |
| 620 |
self.fail("Unexpected AttributeError when calling get_importer") |
| 621 |
|
| 622 |
def test_iter_importers_avoids_emulation(self): |
| 623 |
with check_warnings() as w: |
| 624 |
for importer in pkgutil.iter_importers(): pass |
| 625 |
self.assertEqual(len(w.warnings), 0) |
| 626 |
|
| 627 |
|
| 628 |
def tearDownModule(): |
| 629 |
# this is necessary if test is run repeated (like when finding leaks) |
| 630 |
import zipimport |
| 631 |
import importlib |
| 632 |
zipimport._zip_directory_cache.clear() |
| 633 |
importlib.invalidate_caches() |
| 634 |
|
| 635 |
|
| 636 |
if __name__ == '__main__': |
| 637 |
unittest.main() |