Debian Codegraph @

Lib/test/test_zipimport.py

raw
1 import sys
2 import os
3 import marshal
4 import glob
5 import importlib
6 import importlib.util
7 import re
8 import struct
9 import time
10 import unittest
11 import unittest.mock
12 import warnings
13
14 from test import support
15 from test.support import import_helper
16 from test.support import os_helper
17
18 from zipfile import ZipFile, ZipInfo, ZIP_STORED, ZIP_DEFLATED
19
20 import zipimport
21 import linecache
22 import doctest
23 import inspect
24 import io
25 from traceback import extract_tb, extract_stack, print_tb
26 try:
27 import zlib
28 except ImportError:
29 zlib = None
30
31 test_src = """\
32 def get_name():
33 return __name__
34 def get_file():
35 return __file__
36 """
37 test_co = compile(test_src, "<???>", "exec")
38 raise_src = 'def do_raise(): raise TypeError\n'
39
40 def make_pyc(co, mtime, size):
41 data = marshal.dumps(co)
42 pyc = (importlib.util.MAGIC_NUMBER +
43 struct.pack("<iLL", 0,
44 int(mtime) & 0xFFFF_FFFF, size & 0xFFFF_FFFF) + data)
45 return pyc
46
47 def module_path_to_dotted_name(path):
48 return path.replace(os.sep, '.')
49
50 NOW = time.time()
51 test_pyc = make_pyc(test_co, NOW, len(test_src))
52
53
54 TESTMOD = "ziptestmodule"
55 TESTMOD2 = "ziptestmodule2"
56 TESTMOD3 = "ziptestmodule3"
57 TESTPACK = "ziptestpackage"
58 TESTPACK2 = "ziptestpackage2"
59 TESTPACK3 = "ziptestpackage3"
60 TEMP_DIR = os.path.abspath("junk95142")
61 TEMP_ZIP = os.path.abspath("junk95142.zip")
62 TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "zipimport_data")
63
64 pyc_file = importlib.util.cache_from_source(TESTMOD + '.py')
65 pyc_ext = '.pyc'
66
67
68 class ImportHooksBaseTestCase(unittest.TestCase):
69
70 def setUp(self):
71 self.path = sys.path[:]
72 self.meta_path = sys.meta_path[:]
73 self.path_hooks = sys.path_hooks[:]
74 sys.path_importer_cache.clear()
75 self.modules_before = import_helper.modules_setup()
76
77 def tearDown(self):
78 sys.path[:] = self.path
79 sys.meta_path[:] = self.meta_path
80 sys.path_hooks[:] = self.path_hooks
81 sys.path_importer_cache.clear()
82 import_helper.modules_cleanup(*self.modules_before)
83
84
85 class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
86
87 compression = ZIP_STORED
88
89 def setUp(self):
90 # We're reusing the zip archive path, so we must clear the
91 # cached directory info and linecache.
92 linecache.clearcache()
93 zipimport._zip_directory_cache.clear()
94 ImportHooksBaseTestCase.setUp(self)
95
96 def makeTree(self, files, dirName=TEMP_DIR):
97 # Create a filesystem based set of modules/packages
98 # defined by files under the directory dirName.
99 self.addCleanup(os_helper.rmtree, dirName)
100
101 for name, data in files.items():
102 if isinstance(data, tuple):
103 mtime, data = data
104 path = os.path.join(dirName, *name.split('/'))
105 if path[-1] == os.sep:
106 if not os.path.isdir(path):
107 os.makedirs(path)
108 else:
109 dname = os.path.dirname(path)
110 if not os.path.isdir(dname):
111 os.makedirs(dname)
112 with open(path, 'wb') as fp:
113 fp.write(data)
114
115 def makeZip(self, files, zipName=TEMP_ZIP, *,
116 comment=None, file_comment=None, stuff=None, prefix='', **kw):
117 # Create a zip archive based set of modules/packages
118 # defined by files in the zip file zipName.
119 # If stuff is not None, it is prepended to the archive.
120 self.addCleanup(os_helper.unlink, zipName)
121
122 with ZipFile(zipName, "w", compression=self.compression) as z:
123 self.writeZip(z, files, file_comment=file_comment, prefix=prefix)
124 if comment is not None:
125 z.comment = comment
126
127 if stuff is not None:
128 # Prepend 'stuff' to the start of the zipfile
129 with open(zipName, "rb") as f:
130 data = f.read()
131 with open(zipName, "wb") as f:
132 f.write(stuff)
133 f.write(data)
134
135 def writeZip(self, z, files, *, file_comment=None, prefix=''):
136 for name, data in files.items():
137 if isinstance(data, tuple):
138 mtime, data = data
139 else:
140 mtime = NOW
141 name = name.replace(os.sep, '/')
142 zinfo = ZipInfo(prefix + name, time.localtime(mtime))
143 zinfo.compress_type = self.compression
144 if file_comment is not None:
145 zinfo.comment = file_comment
146 if data is None:
147 zinfo.CRC = 0
148 z.mkdir(zinfo)
149 else:
150 assert name[-1] != '/'
151 z.writestr(zinfo, data)
152
153 def getZip64Files(self):
154 # This is the simplest way to make zipfile generate the zip64 EOCD block
155 return {f"f{n}.py": test_src for n in range(65537)}
156
157 def doTest(self, expected_ext, files, *modules, **kw):
158 if 'prefix' not in kw:
159 kw['prefix'] = 'pre/fix/'
160 self.makeZip(files, **kw)
161 self.doTestWithPreBuiltZip(expected_ext, *modules, **kw)
162
163 def doTestWithPreBuiltZip(self, expected_ext, *modules,
164 call=None, prefix='', **kw):
165 zip_path = os.path.join(TEMP_ZIP, *prefix.split('/')[:-1])
166 sys.path.insert(0, zip_path)
167
168 mod = importlib.import_module(".".join(modules))
169
170 if call is not None:
171 call(mod)
172
173 if expected_ext:
174 file = mod.get_file()
175 self.assertEqual(file, os.path.join(zip_path,
176 *modules) + expected_ext)
177
178 def testAFakeZlib(self):
179 #
180 # This could cause a stack overflow before: importing zlib.py
181 # from a compressed archive would cause zlib to be imported
182 # which would find zlib.py in the archive, which would... etc.
183 #
184 # This test *must* be executed first: it must be the first one
185 # to trigger zipimport to import zlib (zipimport caches the
186 # zlib.decompress function object, after which the problem being
187 # tested here wouldn't be a problem anymore...
188 # (Hence the 'A' in the test method name: to make it the first
189 # item in a list sorted by name, like
190 # unittest.TestLoader.getTestCaseNames() does.)
191 #
192 # This test fails on platforms on which the zlib module is
193 # statically linked, but the problem it tests for can't
194 # occur in that case (builtin modules are always found first),
195 # so we'll simply skip it then. Bug #765456.
196 #
197 if "zlib" in sys.builtin_module_names:
198 self.skipTest('zlib is a builtin module')
199 if "zlib" in sys.modules:
200 del sys.modules["zlib"]
201 files = {"zlib.py": test_src}
202 try:
203 self.doTest(".py", files, "zlib")
204 except ImportError:
205 if self.compression != ZIP_DEFLATED:
206 self.fail("expected test to not raise ImportError")
207 else:
208 if self.compression != ZIP_STORED:
209 self.fail("expected test to raise ImportError")
210
211 def testPy(self):
212 files = {TESTMOD + ".py": test_src}
213 self.doTest(".py", files, TESTMOD)
214
215 def testPyc(self):
216 files = {TESTMOD + pyc_ext: test_pyc}
217 self.doTest(pyc_ext, files, TESTMOD)
218
219 def testBoth(self):
220 files = {TESTMOD + ".py": test_src,
221 TESTMOD + pyc_ext: test_pyc}
222 self.doTest(pyc_ext, files, TESTMOD)
223
224 def testUncheckedHashBasedPyc(self):
225 source = b"state = 'old'"
226 source_hash = importlib.util.source_hash(source)
227 bytecode = importlib._bootstrap_external._code_to_hash_pyc(
228 compile(source, "???", "exec"),
229 source_hash,
230 False, # unchecked
231 )
232 files = {TESTMOD + ".py": (NOW, "state = 'new'"),
233 TESTMOD + ".pyc": (NOW - 20, bytecode)}
234 def check(mod):
235 self.assertEqual(mod.state, 'old')
236 self.doTest(None, files, TESTMOD, call=check)
237
238 @unittest.mock.patch('_imp.check_hash_based_pycs', 'always')
239 def test_checked_hash_based_change_pyc(self):
240 source = b"state = 'old'"
241 source_hash = importlib.util.source_hash(source)
242 bytecode = importlib._bootstrap_external._code_to_hash_pyc(
243 compile(source, "???", "exec"),
244 source_hash,
245 False,
246 )
247 files = {TESTMOD + ".py": (NOW, "state = 'new'"),
248 TESTMOD + ".pyc": (NOW - 20, bytecode)}
249 def check(mod):
250 self.assertEqual(mod.state, 'new')
251 self.doTest(None, files, TESTMOD, call=check)
252
253 def testEmptyPy(self):
254 files = {TESTMOD + ".py": ""}
255 self.doTest(None, files, TESTMOD)
256
257 def testBadMagic(self):
258 # make pyc magic word invalid, forcing loading from .py
259 badmagic_pyc = bytearray(test_pyc)
260 badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
261 files = {TESTMOD + ".py": test_src,
262 TESTMOD + pyc_ext: badmagic_pyc}
263 self.doTest(".py", files, TESTMOD)
264
265 def testBadMagic2(self):
266 # make pyc magic word invalid, causing an ImportError
267 badmagic_pyc = bytearray(test_pyc)
268 badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
269 files = {TESTMOD + pyc_ext: badmagic_pyc}
270 try:
271 self.doTest(".py", files, TESTMOD)
272 self.fail("This should not be reached")
273 except zipimport.ZipImportError as exc:
274 self.assertIsInstance(exc.__cause__, ImportError)
275 self.assertIn("magic number", exc.__cause__.msg)
276
277 def testBadMTime(self):
278 badtime_pyc = bytearray(test_pyc)
279 # flip the second bit -- not the first as that one isn't stored in the
280 # .py's mtime in the zip archive.
281 badtime_pyc[11] ^= 0x02
282 files = {TESTMOD + ".py": test_src,
283 TESTMOD + pyc_ext: badtime_pyc}
284 self.doTest(".py", files, TESTMOD)
285
286 def test2038MTime(self):
287 # Make sure we can handle mtimes larger than what a 32-bit signed number
288 # can hold.
289 twenty_thirty_eight_pyc = make_pyc(test_co, 2**32 - 1, len(test_src))
290 files = {TESTMOD + ".py": test_src,
291 TESTMOD + pyc_ext: twenty_thirty_eight_pyc}
292 self.doTest(".py", files, TESTMOD)
293
294 def testPackage(self):
295 packdir = TESTPACK + os.sep
296 files = {packdir + "__init__" + pyc_ext: test_pyc,
297 packdir + TESTMOD + pyc_ext: test_pyc}
298 self.doTest(pyc_ext, files, TESTPACK, TESTMOD)
299
300 def testSubPackage(self):
301 # Test that subpackages function when loaded from zip
302 # archives.
303 packdir = TESTPACK + os.sep
304 packdir2 = packdir + TESTPACK2 + os.sep
305 files = {packdir + "__init__" + pyc_ext: test_pyc,
306 packdir2 + "__init__" + pyc_ext: test_pyc,
307 packdir2 + TESTMOD + pyc_ext: test_pyc}
308 self.doTest(pyc_ext, files, TESTPACK, TESTPACK2, TESTMOD)
309
310 def testSubNamespacePackage(self):
311 # Test that implicit namespace subpackages function
312 # when loaded from zip archives.
313 packdir = TESTPACK + os.sep
314 packdir2 = packdir + TESTPACK2 + os.sep
315 # The first two files are just directory entries (so have no data).
316 files = {packdir: None,
317 packdir2: None,
318 packdir2 + TESTMOD + pyc_ext: test_pyc}
319 self.doTest(pyc_ext, files, TESTPACK, TESTPACK2, TESTMOD)
320
321 def testMixedNamespacePackage(self):
322 # Test implicit namespace packages spread between a
323 # real filesystem and a zip archive.
324 packdir = TESTPACK + os.sep
325 packdir2 = packdir + TESTPACK2 + os.sep
326 packdir3 = packdir2 + TESTPACK3 + os.sep
327 files1 = {packdir: None,
328 packdir + TESTMOD + pyc_ext: test_pyc,
329 packdir2: None,
330 packdir3: None,
331 packdir3 + TESTMOD + pyc_ext: test_pyc,
332 packdir2 + TESTMOD3 + pyc_ext: test_pyc,
333 packdir2 + TESTMOD + pyc_ext: test_pyc}
334 files2 = {packdir: None,
335 packdir + TESTMOD2 + pyc_ext: test_pyc,
336 packdir2: None,
337 packdir2 + TESTMOD2 + pyc_ext: test_pyc,
338 packdir2 + TESTMOD + pyc_ext: test_pyc}
339
340 zip1 = os.path.abspath("path1.zip")
341 self.makeZip(files1, zip1)
342
343 zip2 = TEMP_DIR
344 self.makeTree(files2, zip2)
345
346 # zip2 should override zip1.
347 sys.path.insert(0, zip1)
348 sys.path.insert(0, zip2)
349
350 mod = importlib.import_module(TESTPACK)
351
352 # if TESTPACK is functioning as a namespace pkg then
353 # there should be two entries in the __path__.
354 # First should be path2 and second path1.
355 self.assertEqual(2, len(mod.__path__))
356 p1, p2 = mod.__path__
357 self.assertEqual(os.path.basename(TEMP_DIR), p1.split(os.sep)[-2])
358 self.assertEqual("path1.zip", p2.split(os.sep)[-2])
359
360 # packdir3 should import as a namespace package.
361 # Its __path__ is an iterable of 1 element from zip1.
362 mod = importlib.import_module(packdir3.replace(os.sep, '.')[:-1])
363 self.assertEqual(1, len(mod.__path__))
364 mpath = list(mod.__path__)[0].split('path1.zip' + os.sep)[1]
365 self.assertEqual(packdir3[:-1], mpath)
366
367 # TESTPACK/TESTMOD only exists in path1.
368 mod = importlib.import_module('.'.join((TESTPACK, TESTMOD)))
369 self.assertEqual("path1.zip", mod.__file__.split(os.sep)[-3])
370
371 # And TESTPACK/(TESTMOD2) only exists in path2.
372 mod = importlib.import_module('.'.join((TESTPACK, TESTMOD2)))
373 self.assertEqual(os.path.basename(TEMP_DIR),
374 mod.__file__.split(os.sep)[-3])
375
376 # One level deeper...
377 subpkg = '.'.join((TESTPACK, TESTPACK2))
378 mod = importlib.import_module(subpkg)
379 self.assertEqual(2, len(mod.__path__))
380 p1, p2 = mod.__path__
381 self.assertEqual(os.path.basename(TEMP_DIR), p1.split(os.sep)[-3])
382 self.assertEqual("path1.zip", p2.split(os.sep)[-3])
383
384 # subpkg.TESTMOD exists in both zips should load from zip2.
385 mod = importlib.import_module('.'.join((subpkg, TESTMOD)))
386 self.assertEqual(os.path.basename(TEMP_DIR),
387 mod.__file__.split(os.sep)[-4])
388
389 # subpkg.TESTMOD2 only exists in zip2.
390 mod = importlib.import_module('.'.join((subpkg, TESTMOD2)))
391 self.assertEqual(os.path.basename(TEMP_DIR),
392 mod.__file__.split(os.sep)[-4])
393
394 # Finally subpkg.TESTMOD3 only exists in zip1.
395 mod = importlib.import_module('.'.join((subpkg, TESTMOD3)))
396 self.assertEqual('path1.zip', mod.__file__.split(os.sep)[-4])
397
398 def testNamespacePackage(self):
399 # Test implicit namespace packages spread between multiple zip
400 # archives.
401 packdir = TESTPACK + os.sep
402 packdir2 = packdir + TESTPACK2 + os.sep
403 packdir3 = packdir2 + TESTPACK3 + os.sep
404 files1 = {packdir: None,
405 packdir + TESTMOD + pyc_ext: test_pyc,
406 packdir2: None,
407 packdir3: None,
408 packdir3 + TESTMOD + pyc_ext: test_pyc,
409 packdir2 + TESTMOD3 + pyc_ext: test_pyc,
410 packdir2 + TESTMOD + pyc_ext: test_pyc}
411 zip1 = os.path.abspath("path1.zip")
412 self.makeZip(files1, zip1)
413
414 files2 = {packdir: None,
415 packdir + TESTMOD2 + pyc_ext: test_pyc,
416 packdir2: None,
417 packdir2 + TESTMOD2 + pyc_ext: test_pyc,
418 packdir2 + TESTMOD + pyc_ext: test_pyc}
419 zip2 = os.path.abspath("path2.zip")
420 self.makeZip(files2, zip2)
421
422 # zip2 should override zip1.
423 sys.path.insert(0, zip1)
424 sys.path.insert(0, zip2)
425
426 mod = importlib.import_module(TESTPACK)
427
428 # if TESTPACK is functioning as a namespace pkg then
429 # there should be two entries in the __path__.
430 # First should be path2 and second path1.
431 self.assertEqual(2, len(mod.__path__))
432 p1, p2 = mod.__path__
433 self.assertEqual("path2.zip", p1.split(os.sep)[-2])
434 self.assertEqual("path1.zip", p2.split(os.sep)[-2])
435
436 # packdir3 should import as a namespace package.
437 # Tts __path__ is an iterable of 1 element from zip1.
438 mod = importlib.import_module(packdir3.replace(os.sep, '.')[:-1])
439 self.assertEqual(1, len(mod.__path__))
440 mpath = list(mod.__path__)[0].split('path1.zip' + os.sep)[1]
441 self.assertEqual(packdir3[:-1], mpath)
442
443 # TESTPACK/TESTMOD only exists in path1.
444 mod = importlib.import_module('.'.join((TESTPACK, TESTMOD)))
445 self.assertEqual("path1.zip", mod.__file__.split(os.sep)[-3])
446
447 # And TESTPACK/(TESTMOD2) only exists in path2.
448 mod = importlib.import_module('.'.join((TESTPACK, TESTMOD2)))
449 self.assertEqual("path2.zip", mod.__file__.split(os.sep)[-3])
450
451 # One level deeper...
452 subpkg = '.'.join((TESTPACK, TESTPACK2))
453 mod = importlib.import_module(subpkg)
454 self.assertEqual(2, len(mod.__path__))
455 p1, p2 = mod.__path__
456 self.assertEqual("path2.zip", p1.split(os.sep)[-3])
457 self.assertEqual("path1.zip", p2.split(os.sep)[-3])
458
459 # subpkg.TESTMOD exists in both zips should load from zip2.
460 mod = importlib.import_module('.'.join((subpkg, TESTMOD)))
461 self.assertEqual('path2.zip', mod.__file__.split(os.sep)[-4])
462
463 # subpkg.TESTMOD2 only exists in zip2.
464 mod = importlib.import_module('.'.join((subpkg, TESTMOD2)))
465 self.assertEqual('path2.zip', mod.__file__.split(os.sep)[-4])
466
467 # Finally subpkg.TESTMOD3 only exists in zip1.
468 mod = importlib.import_module('.'.join((subpkg, TESTMOD3)))
469 self.assertEqual('path1.zip', mod.__file__.split(os.sep)[-4])
470
471 def testZipImporterMethods(self):
472 packdir = TESTPACK + os.sep
473 packdir2 = packdir + TESTPACK2 + os.sep
474 files = {packdir + "__init__" + pyc_ext: test_pyc,
475 packdir2 + "__init__" + pyc_ext: test_pyc,
476 packdir2 + TESTMOD + pyc_ext: test_pyc,
477 "spam" + pyc_ext: test_pyc}
478 self.makeZip(files, file_comment=b"spam")
479
480 zi = zipimport.zipimporter(TEMP_ZIP)
481 self.assertEqual(zi.archive, TEMP_ZIP)
482 self.assertTrue(zi.is_package(TESTPACK))
483
484 # PEP 302
485 with warnings.catch_warnings():
486 warnings.simplefilter("ignore", DeprecationWarning)
487
488 mod = zi.load_module(TESTPACK)
489 self.assertEqual(zi.get_filename(TESTPACK), mod.__file__)
490
491 # PEP 451
492 spec = zi.find_spec('spam')
493 self.assertIsNotNone(spec)
494 self.assertIsInstance(spec.loader, zipimport.zipimporter)
495 self.assertFalse(spec.loader.is_package('spam'))
496 exec_mod = importlib.util.module_from_spec(spec)
497 spec.loader.exec_module(exec_mod)
498 self.assertEqual(spec.loader.get_filename('spam'), exec_mod.__file__)
499
500 spec = zi.find_spec(TESTPACK)
501 mod = importlib.util.module_from_spec(spec)
502 spec.loader.exec_module(mod)
503 self.assertEqual(zi.get_filename(TESTPACK), mod.__file__)
504
505 existing_pack_path = importlib.import_module(TESTPACK).__path__[0]
506 expected_path_path = os.path.join(TEMP_ZIP, TESTPACK)
507 self.assertEqual(existing_pack_path, expected_path_path)
508
509 self.assertFalse(zi.is_package(packdir + '__init__'))
510 self.assertTrue(zi.is_package(packdir + TESTPACK2))
511 self.assertFalse(zi.is_package(packdir2 + TESTMOD))
512
513 mod_path = packdir2 + TESTMOD
514 mod_name = module_path_to_dotted_name(mod_path)
515 mod = importlib.import_module(mod_name)
516 self.assertTrue(mod_name in sys.modules)
517 self.assertIsNone(zi.get_source(TESTPACK))
518 self.assertIsNone(zi.get_source(mod_path))
519 self.assertEqual(zi.get_filename(mod_path), mod.__file__)
520 # To pass in the module name instead of the path, we must use the
521 # right importer
522 loader = mod.__spec__.loader
523 self.assertIsNone(loader.get_source(mod_name))
524 self.assertEqual(loader.get_filename(mod_name), mod.__file__)
525
526 # test prefix and archivepath members
527 zi2 = zipimport.zipimporter(TEMP_ZIP + os.sep + TESTPACK)
528 self.assertEqual(zi2.archive, TEMP_ZIP)
529 self.assertEqual(zi2.prefix, TESTPACK + os.sep)
530
531 def testInvalidateCaches(self):
532 packdir = TESTPACK + os.sep
533 packdir2 = packdir + TESTPACK2 + os.sep
534 files = {packdir + "__init__" + pyc_ext: test_pyc,
535 packdir2 + "__init__" + pyc_ext: test_pyc,
536 packdir2 + TESTMOD + pyc_ext: test_pyc,
537 "spam" + pyc_ext: test_pyc}
538 self.makeZip(files, file_comment=b"spam")
539
540 zi = zipimport.zipimporter(TEMP_ZIP)
541 self.assertEqual(zi._get_files().keys(), files.keys())
542 # Check that the file information remains accurate after reloading
543 zi.invalidate_caches()
544 self.assertEqual(zi._get_files().keys(), files.keys())
545 # Add a new file to the ZIP archive
546 newfile = {"spam2" + pyc_ext: test_pyc}
547 files.update(newfile)
548 with ZipFile(TEMP_ZIP, "a", compression=self.compression) as z:
549 self.writeZip(z, newfile, file_comment=b"spam")
550 # Check that we can detect the new file after invalidating the cache
551 zi.invalidate_caches()
552 self.assertEqual(zi._get_files().keys(), files.keys())
553 spec = zi.find_spec('spam2')
554 self.assertIsNotNone(spec)
555 self.assertIsInstance(spec.loader, zipimport.zipimporter)
556 # Check that the cached data is removed if the file is deleted
557 os.remove(TEMP_ZIP)
558 zi.invalidate_caches()
559 self.assertFalse(zi._get_files())
560 self.assertIsNone(zipimport._zip_directory_cache.get(zi.archive))
561 self.assertIsNone(zi.find_spec("name_does_not_matter"))
562
563 def testInvalidateCachesWithMultipleZipimports(self):
564 packdir = TESTPACK + os.sep
565 packdir2 = packdir + TESTPACK2 + os.sep
566 files = {packdir + "__init__" + pyc_ext: test_pyc,
567 packdir2 + "__init__" + pyc_ext: test_pyc,
568 packdir2 + TESTMOD + pyc_ext: test_pyc,
569 "spam" + pyc_ext: test_pyc}
570 self.makeZip(files, file_comment=b"spam")
571
572 zi = zipimport.zipimporter(TEMP_ZIP)
573 self.assertEqual(zi._get_files().keys(), files.keys())
574 # Zipimporter for the same path.
575 zi2 = zipimport.zipimporter(TEMP_ZIP)
576 self.assertEqual(zi2._get_files().keys(), files.keys())
577 # Add a new file to the ZIP archive to make the cache wrong.
578 newfile = {"spam2" + pyc_ext: test_pyc}
579 files.update(newfile)
580 with ZipFile(TEMP_ZIP, "a", compression=self.compression) as z:
581 self.writeZip(z, newfile, file_comment=b"spam")
582 # Invalidate the cache of the first zipimporter.
583 zi.invalidate_caches()
584 # Check that the second zipimporter detects the new file and isn't using a stale cache.
585 self.assertEqual(zi2._get_files().keys(), files.keys())
586 spec = zi2.find_spec('spam2')
587 self.assertIsNotNone(spec)
588 self.assertIsInstance(spec.loader, zipimport.zipimporter)
589
590 def testZipImporterMethodsInSubDirectory(self):
591 packdir = TESTPACK + os.sep
592 packdir2 = packdir + TESTPACK2 + os.sep
593 files = {packdir2 + "__init__" + pyc_ext: test_pyc,
594 packdir2 + TESTMOD + pyc_ext: test_pyc}
595 self.makeZip(files, file_comment=b"eggs")
596
597 zi = zipimport.zipimporter(TEMP_ZIP + os.sep + packdir)
598 self.assertEqual(zi.archive, TEMP_ZIP)
599 self.assertEqual(zi.prefix, packdir)
600 self.assertTrue(zi.is_package(TESTPACK2))
601 # PEP 302
602 with warnings.catch_warnings():
603 warnings.simplefilter("ignore", DeprecationWarning)
604 mod = zi.load_module(TESTPACK2)
605 self.assertEqual(zi.get_filename(TESTPACK2), mod.__file__)
606 # PEP 451
607 spec = zi.find_spec(TESTPACK2)
608 mod = importlib.util.module_from_spec(spec)
609 spec.loader.exec_module(mod)
610 self.assertEqual(spec.loader.get_filename(TESTPACK2), mod.__file__)
611
612 self.assertFalse(zi.is_package(TESTPACK2 + os.sep + '__init__'))
613 self.assertFalse(zi.is_package(TESTPACK2 + os.sep + TESTMOD))
614
615 pkg_path = TEMP_ZIP + os.sep + packdir + TESTPACK2
616 zi2 = zipimport.zipimporter(pkg_path)
617
618 # PEP 451
619 spec = zi2.find_spec(TESTMOD)
620 self.assertIsNotNone(spec)
621 self.assertIsInstance(spec.loader, zipimport.zipimporter)
622 self.assertFalse(spec.loader.is_package(TESTMOD))
623 load_mod = importlib.util.module_from_spec(spec)
624 spec.loader.exec_module(load_mod)
625 self.assertEqual(
626 spec.loader.get_filename(TESTMOD), load_mod.__file__)
627
628 mod_path = TESTPACK2 + os.sep + TESTMOD
629 mod_name = module_path_to_dotted_name(mod_path)
630 mod = importlib.import_module(mod_name)
631 self.assertTrue(mod_name in sys.modules)
632 self.assertIsNone(zi.get_source(TESTPACK2))
633 self.assertIsNone(zi.get_source(mod_path))
634 self.assertEqual(zi.get_filename(mod_path), mod.__file__)
635 # To pass in the module name instead of the path, we must use the
636 # right importer.
637 loader = mod.__loader__
638 self.assertIsNone(loader.get_source(mod_name))
639 self.assertEqual(loader.get_filename(mod_name), mod.__file__)
640
641 def testGetData(self):
642 self.addCleanup(os_helper.unlink, TEMP_ZIP)
643 with ZipFile(TEMP_ZIP, "w") as z:
644 z.compression = self.compression
645 name = "testdata.dat"
646 data = bytes(x for x in range(256))
647 z.writestr(name, data)
648
649 zi = zipimport.zipimporter(TEMP_ZIP)
650 self.assertEqual(data, zi.get_data(name))
651 self.assertIn('zipimporter object', repr(zi))
652
653 def testImporterAttr(self):
654 src = """if 1: # indent hack
655 def get_file():
656 return __file__
657 if __loader__.get_data("some.data") != b"some data":
658 raise AssertionError("bad data")\n"""
659 pyc = make_pyc(compile(src, "<???>", "exec"), NOW, len(src))
660 files = {TESTMOD + pyc_ext: pyc,
661 "some.data": "some data"}
662 self.doTest(pyc_ext, files, TESTMOD, prefix='')
663
664 def testDefaultOptimizationLevel(self):
665 # zipimport should use the default optimization level (#28131)
666 src = """if 1: # indent hack
667 def test(val):
668 assert(val)
669 return val\n"""
670 files = {TESTMOD + '.py': src}
671 self.makeZip(files)
672 sys.path.insert(0, TEMP_ZIP)
673 mod = importlib.import_module(TESTMOD)
674 self.assertEqual(mod.test(1), 1)
675 if __debug__:
676 self.assertRaises(AssertionError, mod.test, False)
677 else:
678 self.assertEqual(mod.test(0), 0)
679
680 def testImport_WithStuff(self):
681 # try importing from a zipfile which contains additional
682 # stuff at the beginning of the file
683 files = {TESTMOD + ".py": test_src}
684 self.doTest(".py", files, TESTMOD,
685 stuff=b"Some Stuff"*31)
686
687 def assertModuleSource(self, module):
688 self.assertEqual(inspect.getsource(module), test_src)
689
690 def testGetSource(self):
691 files = {TESTMOD + ".py": test_src}
692 self.doTest(".py", files, TESTMOD, call=self.assertModuleSource)
693
694 def testGetCompiledSource(self):
695 pyc = make_pyc(compile(test_src, "<???>", "exec"), NOW, len(test_src))
696 files = {TESTMOD + ".py": test_src,
697 TESTMOD + pyc_ext: pyc}
698 self.doTest(pyc_ext, files, TESTMOD, call=self.assertModuleSource)
699
700 def runDoctest(self, callback):
701 files = {TESTMOD + ".py": test_src,
702 "xyz.txt": ">>> log.append(True)\n"}
703 self.doTest(".py", files, TESTMOD, call=callback)
704
705 def doDoctestFile(self, module):
706 log = []
707 old_master, doctest.master = doctest.master, None
708 try:
709 doctest.testfile(
710 'xyz.txt', package=module, module_relative=True,
711 globs=locals()
712 )
713 finally:
714 doctest.master = old_master
715 self.assertEqual(log,[True])
716
717 def testDoctestFile(self):
718 self.runDoctest(self.doDoctestFile)
719
720 def doDoctestSuite(self, module):
721 log = []
722 doctest.DocFileTest(
723 'xyz.txt', package=module, module_relative=True,
724 globs=locals()
725 ).run()
726 self.assertEqual(log,[True])
727
728 def testDoctestSuite(self):
729 self.runDoctest(self.doDoctestSuite)
730
731 def doTraceback(self, module):
732 try:
733 module.do_raise()
734 except Exception as e:
735 tb = e.__traceback__.tb_next
736
737 f,lno,n,line = extract_tb(tb, 1)[0]
738 self.assertEqual(line, raise_src.strip())
739
740 f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
741 self.assertEqual(line, raise_src.strip())
742
743 s = io.StringIO()
744 print_tb(tb, 1, s)
745 self.assertTrue(s.getvalue().endswith(
746 ' def do_raise(): raise TypeError\n'
747 '' if support.has_no_debug_ranges() else
748 ' ^^^^^^^^^^^^^^^\n'
749 ))
750 else:
751 raise AssertionError("This ought to be impossible")
752
753 def testTraceback(self):
754 files = {TESTMOD + ".py": raise_src}
755 self.doTest(None, files, TESTMOD, call=self.doTraceback)
756
757 @unittest.skipIf(os_helper.TESTFN_UNENCODABLE is None,
758 "need an unencodable filename")
759 def testUnencodable(self):
760 filename = os_helper.TESTFN_UNENCODABLE + ".zip"
761 self.makeZip({TESTMOD + ".py": test_src}, filename)
762 spec = zipimport.zipimporter(filename).find_spec(TESTMOD)
763 mod = importlib.util.module_from_spec(spec)
764 spec.loader.exec_module(mod)
765
766 def testBytesPath(self):
767 filename = os_helper.TESTFN + ".zip"
768 self.makeZip({TESTMOD + ".py": test_src}, filename)
769
770 zipimport.zipimporter(filename)
771 with self.assertRaises(TypeError):
772 zipimport.zipimporter(os.fsencode(filename))
773 with self.assertRaises(TypeError):
774 zipimport.zipimporter(bytearray(os.fsencode(filename)))
775 with self.assertRaises(TypeError):
776 zipimport.zipimporter(memoryview(os.fsencode(filename)))
777
778 def testComment(self):
779 files = {TESTMOD + ".py": test_src}
780 self.doTest(".py", files, TESTMOD, comment=b"comment")
781
782 def testBeginningCruftAndComment(self):
783 files = {TESTMOD + ".py": test_src}
784 self.doTest(".py", files, TESTMOD, stuff=b"cruft" * 64, comment=b"hi")
785
786 def testLargestPossibleComment(self):
787 files = {TESTMOD + ".py": test_src}
788 self.doTest(".py", files, TESTMOD, comment=b"c" * ((1 << 16) - 1))
789
790 def testZip64(self):
791 files = self.getZip64Files()
792 self.doTest(".py", files, "f6")
793
794 def testZip64CruftAndComment(self):
795 files = self.getZip64Files()
796 self.doTest(".py", files, "f65536", comment=b"c" * ((1 << 16) - 1))
797
798 def testZip64LargeFile(self):
799 support.requires(
800 "largefile",
801 f"test generates files >{0xFFFFFFFF} bytes and takes a long time "
802 "to run"
803 )
804
805 # N.B.: We do a lot of gymnastics below in the ZIP_STORED case to save
806 # and reconstruct a sparse zip on systems that support sparse files.
807 # Instead of creating a ~8GB zip file mainly consisting of null bytes
808 # for every run of the test, we create the zip once and save off the
809 # non-null portions of the resulting file as data blobs with offsets
810 # that allow re-creating the zip file sparsely. This drops disk space
811 # usage to ~9KB for the ZIP_STORED case and drops that test time by ~2
812 # orders of magnitude. For the ZIP_DEFLATED case, however, we bite the
813 # bullet. The resulting zip file is ~8MB of non-null data; so the sparse
814 # trick doesn't work and would result in that full ~8MB zip data file
815 # being checked in to source control.
816 parts_glob = f"sparse-zip64-c{self.compression:d}-0x*.part"
817 full_parts_glob = os.path.join(TEST_DATA_DIR, parts_glob)
818 pre_built_zip_parts = glob.glob(full_parts_glob)
819
820 self.addCleanup(os_helper.unlink, TEMP_ZIP)
821 if not pre_built_zip_parts:
822 if self.compression != ZIP_STORED:
823 support.requires(
824 "cpu",
825 "test requires a lot of CPU for compression."
826 )
827 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
828 with open(os_helper.TESTFN, "wb") as f:
829 f.write(b"data")
830 f.write(os.linesep.encode())
831 f.seek(0xffff_ffff, os.SEEK_CUR)
832 f.write(os.linesep.encode())
833 os.utime(os_helper.TESTFN, (0.0, 0.0))
834 with ZipFile(
835 TEMP_ZIP,
836 "w",
837 compression=self.compression,
838 strict_timestamps=False
839 ) as z:
840 z.write(os_helper.TESTFN, "data1")
841 z.writestr(
842 ZipInfo("module.py", (1980, 1, 1, 0, 0, 0)), test_src
843 )
844 z.write(os_helper.TESTFN, "data2")
845
846 # This "works" but relies on the zip format having a non-empty
847 # final page due to the trailing central directory to wind up with
848 # the correct length file.
849 def make_sparse_zip_parts(name):
850 empty_page = b"\0" * 4096
851 with open(name, "rb") as f:
852 part = None
853 try:
854 while True:
855 offset = f.tell()
856 data = f.read(len(empty_page))
857 if not data:
858 break
859 if data != empty_page:
860 if not part:
861 part_fullname = os.path.join(
862 TEST_DATA_DIR,
863 f"sparse-zip64-c{self.compression:d}-"
864 f"{offset:#011x}.part",
865 )
866 os.makedirs(
867 os.path.dirname(part_fullname),
868 exist_ok=True
869 )
870 part = open(part_fullname, "wb")
871 print("Created", part_fullname)
872 part.write(data)
873 else:
874 if part:
875 part.close()
876 part = None
877 finally:
878 if part:
879 part.close()
880
881 if self.compression == ZIP_STORED:
882 print(f"Creating sparse parts to check in into {TEST_DATA_DIR}:")
883 make_sparse_zip_parts(TEMP_ZIP)
884
885 else:
886 def extract_offset(name):
887 if m := re.search(r"-(0x[0-9a-f]{9})\.part$", name):
888 return int(m.group(1), base=16)
889 raise ValueError(f"{name=} does not fit expected pattern.")
890 offset_parts = [(extract_offset(n), n) for n in pre_built_zip_parts]
891 with open(TEMP_ZIP, "wb") as f:
892 for offset, part_fn in sorted(offset_parts):
893 with open(part_fn, "rb") as part:
894 f.seek(offset, os.SEEK_SET)
895 f.write(part.read())
896 # Confirm that the reconstructed zip file works and looks right.
897 with ZipFile(TEMP_ZIP, "r") as z:
898 self.assertEqual(
899 z.getinfo("module.py").date_time, (1980, 1, 1, 0, 0, 0)
900 )
901 self.assertEqual(
902 z.read("module.py"), test_src.encode(),
903 msg=f"Recreate {full_parts_glob}, unexpected contents."
904 )
905 def assertDataEntry(name):
906 zinfo = z.getinfo(name)
907 self.assertEqual(zinfo.date_time, (1980, 1, 1, 0, 0, 0))
908 self.assertGreater(zinfo.file_size, 0xffff_ffff)
909 assertDataEntry("data1")
910 assertDataEntry("data2")
911
912 self.doTestWithPreBuiltZip(".py", "module")
913
914
915 @support.requires_zlib()
916 class CompressedZipImportTestCase(UncompressedZipImportTestCase):
917 compression = ZIP_DEFLATED
918
919
920 class BadFileZipImportTestCase(unittest.TestCase):
921 def assertZipFailure(self, filename):
922 self.assertRaises(zipimport.ZipImportError,
923 zipimport.zipimporter, filename)
924
925 def testNoFile(self):
926 self.assertZipFailure('AdfjdkFJKDFJjdklfjs')
927
928 def testEmptyFilename(self):
929 self.assertZipFailure('')
930
931 def testBadArgs(self):
932 self.assertRaises(TypeError, zipimport.zipimporter, None)
933 self.assertRaises(TypeError, zipimport.zipimporter, TESTMOD, kwd=None)
934 self.assertRaises(TypeError, zipimport.zipimporter,
935 list(os.fsencode(TESTMOD)))
936
937 def testFilenameTooLong(self):
938 self.assertZipFailure('A' * 33000)
939
940 def testEmptyFile(self):
941 os_helper.unlink(TESTMOD)
942 os_helper.create_empty_file(TESTMOD)
943 self.assertZipFailure(TESTMOD)
944
945 @unittest.skipIf(support.is_wasi, "mode 000 not supported.")
946 def testFileUnreadable(self):
947 os_helper.unlink(TESTMOD)
948 fd = os.open(TESTMOD, os.O_CREAT, 000)
949 try:
950 os.close(fd)
951
952 with self.assertRaises(zipimport.ZipImportError) as cm:
953 zipimport.zipimporter(TESTMOD)
954 finally:
955 # If we leave "the read-only bit" set on Windows, nothing can
956 # delete TESTMOD, and later tests suffer bogus failures.
957 os.chmod(TESTMOD, 0o666)
958 os_helper.unlink(TESTMOD)
959
960 def testNotZipFile(self):
961 os_helper.unlink(TESTMOD)
962 fp = open(TESTMOD, 'w+')
963 fp.write('a' * 22)
964 fp.close()
965 self.assertZipFailure(TESTMOD)
966
967 # XXX: disabled until this works on Big-endian machines
968 def _testBogusZipFile(self):
969 os_helper.unlink(TESTMOD)
970 fp = open(TESTMOD, 'w+')
971 fp.write(struct.pack('=I', 0x06054B50))
972 fp.write('a' * 18)
973 fp.close()
974 z = zipimport.zipimporter(TESTMOD)
975
976 try:
977 with warnings.catch_warnings():
978 warnings.simplefilter("ignore", DeprecationWarning)
979 self.assertRaises(TypeError, z.load_module, None)
980 self.assertRaises(TypeError, z.find_module, None)
981 self.assertRaises(TypeError, z.find_spec, None)
982 self.assertRaises(TypeError, z.exec_module, None)
983 self.assertRaises(TypeError, z.is_package, None)
984 self.assertRaises(TypeError, z.get_code, None)
985 self.assertRaises(TypeError, z.get_data, None)
986 self.assertRaises(TypeError, z.get_source, None)
987
988 error = zipimport.ZipImportError
989 self.assertIsNone(z.find_spec('abc'))
990
991 with warnings.catch_warnings():
992 warnings.simplefilter("ignore", DeprecationWarning)
993 self.assertRaises(error, z.load_module, 'abc')
994 self.assertRaises(error, z.get_code, 'abc')
995 self.assertRaises(OSError, z.get_data, 'abc')
996 self.assertRaises(error, z.get_source, 'abc')
997 self.assertRaises(error, z.is_package, 'abc')
998 finally:
999 zipimport._zip_directory_cache.clear()
1000
1001
1002 def tearDownModule():
1003 os_helper.unlink(TESTMOD)
1004
1005
1006 if __name__ == "__main__":
1007 unittest.main()