blob: 838e1b561f543e2a130e21b5b0eefdb8828e5614 [file] [log] [blame]
Just van Rossum52e14d62002-12-30 22:08:05 +00001import sys
2import os
3import marshal
4import imp
5import struct
6import time
Neal Norwitzb155b622006-01-23 07:52:13 +00007import unittest
Just van Rossum52e14d62002-12-30 22:08:05 +00008
Benjamin Petersonee8712c2008-05-20 21:35:26 +00009from test import support
Just van Rossum52e14d62002-12-30 22:08:05 +000010from test.test_importhooks import ImportHooksBaseTestCase, test_src, test_co
11
Ezio Melotti78ea2022009-09-12 18:41:20 +000012# some tests can be ran even without zlib
13try:
14 import zlib
15except ImportError:
16 zlib = None
17
18from zipfile import ZipFile, ZipInfo, ZIP_STORED, ZIP_DEFLATED
19
Just van Rossum52e14d62002-12-30 22:08:05 +000020import zipimport
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021import linecache
22import doctest
23import inspect
Guido van Rossum34d19282007-08-09 01:03:29 +000024import io
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000025from traceback import extract_tb, extract_stack, print_tb
26raise_src = 'def do_raise(): raise TypeError\n'
Just van Rossum52e14d62002-12-30 22:08:05 +000027
Neal Norwitzb155b622006-01-23 07:52:13 +000028# so we only run testAFakeZlib once if this test is run repeatedly
29# which happens when we look for ref leaks
30test_imported = False
31
32
Just van Rossum52e14d62002-12-30 22:08:05 +000033def make_pyc(co, mtime):
34 data = marshal.dumps(co)
Jack Jansen472e7db2003-01-08 16:37:03 +000035 if type(mtime) is type(0.0):
Tim Petersf2715e02003-02-19 02:35:07 +000036 # Mac mtimes need a bit of special casing
37 if mtime < 0x7fffffff:
38 mtime = int(mtime)
39 else:
Guido van Rossume2a383d2007-01-15 16:59:06 +000040 mtime = int(-0x100000000 + int(mtime))
Jack Jansen472e7db2003-01-08 16:37:03 +000041 pyc = imp.get_magic() + struct.pack("<i", int(mtime)) + data
Just van Rossum52e14d62002-12-30 22:08:05 +000042 return pyc
43
Tim Peters68f2d002006-01-23 22:19:24 +000044def module_path_to_dotted_name(path):
45 return path.replace(os.sep, '.')
46
Just van Rossum52e14d62002-12-30 22:08:05 +000047NOW = time.time()
48test_pyc = make_pyc(test_co, NOW)
49
50
Just van Rossum52e14d62002-12-30 22:08:05 +000051TESTMOD = "ziptestmodule"
52TESTPACK = "ziptestpackage"
Just van Rossumd35c6db2003-01-02 12:55:48 +000053TESTPACK2 = "ziptestpackage2"
Skip Montanaro7a98be22007-08-16 14:35:24 +000054TEMP_ZIP = os.path.abspath("junk95142.zip")
Just van Rossum52e14d62002-12-30 22:08:05 +000055
Barry Warsaw28a691b2010-04-17 00:19:56 +000056pyc_file = imp.cache_from_source(TESTMOD + '.py')
57pyc_ext = ('.pyc' if __debug__ else '.pyo')
58
Ezio Melotti78ea2022009-09-12 18:41:20 +000059
Just van Rossum52e14d62002-12-30 22:08:05 +000060class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
61
62 compression = ZIP_STORED
63
64 def setUp(self):
65 # We're reusing the zip archive path, so we must clear the
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000066 # cached directory info and linecache
67 linecache.clearcache()
Just van Rossum52e14d62002-12-30 22:08:05 +000068 zipimport._zip_directory_cache.clear()
69 ImportHooksBaseTestCase.setUp(self)
70
Thomas Heller354e3d92003-07-22 18:10:15 +000071 def doTest(self, expected_ext, files, *modules, **kw):
Just van Rossum52e14d62002-12-30 22:08:05 +000072 z = ZipFile(TEMP_ZIP, "w")
73 try:
74 for name, (mtime, data) in files.items():
75 zinfo = ZipInfo(name, time.localtime(mtime))
76 zinfo.compress_type = self.compression
77 z.writestr(zinfo, data)
78 z.close()
Thomas Heller354e3d92003-07-22 18:10:15 +000079
80 stuff = kw.get("stuff", None)
81 if stuff is not None:
82 # Prepend 'stuff' to the start of the zipfile
Barry Warsaw28a691b2010-04-17 00:19:56 +000083 with open(TEMP_ZIP, "rb") as f:
84 data = f.read()
85 with open(TEMP_ZIP, "wb") as f:
86 f.write(stuff)
87 f.write(data)
Thomas Heller354e3d92003-07-22 18:10:15 +000088
Just van Rossum52e14d62002-12-30 22:08:05 +000089 sys.path.insert(0, TEMP_ZIP)
90
91 mod = __import__(".".join(modules), globals(), locals(),
92 ["__dummy__"])
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000093
94 call = kw.get('call')
95 if call is not None:
96 call(mod)
97
Just van Rossum9a3129c2003-01-03 11:18:56 +000098 if expected_ext:
99 file = mod.get_file()
100 self.assertEquals(file, os.path.join(TEMP_ZIP,
Just van Rossum6706c4d2003-01-09 22:27:10 +0000101 *modules) + expected_ext)
Just van Rossum52e14d62002-12-30 22:08:05 +0000102 finally:
103 z.close()
104 os.remove(TEMP_ZIP)
105
106 def testAFakeZlib(self):
107 #
108 # This could cause a stack overflow before: importing zlib.py
109 # from a compressed archive would cause zlib to be imported
110 # which would find zlib.py in the archive, which would... etc.
111 #
112 # This test *must* be executed first: it must be the first one
113 # to trigger zipimport to import zlib (zipimport caches the
114 # zlib.decompress function object, after which the problem being
115 # tested here wouldn't be a problem anymore...
116 # (Hence the 'A' in the test method name: to make it the first
117 # item in a list sorted by name, like unittest.makeSuite() does.)
118 #
Just van Rossum59498542003-11-18 23:00:55 +0000119 # This test fails on platforms on which the zlib module is
120 # statically linked, but the problem it tests for can't
121 # occur in that case (builtin modules are always found first),
122 # so we'll simply skip it then. Bug #765456.
123 #
124 if "zlib" in sys.builtin_module_names:
125 return
Just van Rossum52e14d62002-12-30 22:08:05 +0000126 if "zlib" in sys.modules:
127 del sys.modules["zlib"]
128 files = {"zlib.py": (NOW, test_src)}
129 try:
130 self.doTest(".py", files, "zlib")
131 except ImportError:
132 if self.compression != ZIP_DEFLATED:
133 self.fail("expected test to not raise ImportError")
134 else:
135 if self.compression != ZIP_STORED:
136 self.fail("expected test to raise ImportError")
137
138 def testPy(self):
139 files = {TESTMOD + ".py": (NOW, test_src)}
140 self.doTest(".py", files, TESTMOD)
141
142 def testPyc(self):
143 files = {TESTMOD + pyc_ext: (NOW, test_pyc)}
144 self.doTest(pyc_ext, files, TESTMOD)
145
146 def testBoth(self):
147 files = {TESTMOD + ".py": (NOW, test_src),
148 TESTMOD + pyc_ext: (NOW, test_pyc)}
149 self.doTest(pyc_ext, files, TESTMOD)
150
Just van Rossum9a3129c2003-01-03 11:18:56 +0000151 def testEmptyPy(self):
152 files = {TESTMOD + ".py": (NOW, "")}
153 self.doTest(None, files, TESTMOD)
154
Just van Rossum52e14d62002-12-30 22:08:05 +0000155 def testBadMagic(self):
156 # make pyc magic word invalid, forcing loading from .py
Guido van Rossum254348e2007-11-21 19:29:53 +0000157 badmagic_pyc = bytearray(test_pyc)
Guido van Rossumad8d3002007-08-03 18:40:49 +0000158 badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
Just van Rossum52e14d62002-12-30 22:08:05 +0000159 files = {TESTMOD + ".py": (NOW, test_src),
160 TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
161 self.doTest(".py", files, TESTMOD)
162
163 def testBadMagic2(self):
164 # make pyc magic word invalid, causing an ImportError
Guido van Rossum254348e2007-11-21 19:29:53 +0000165 badmagic_pyc = bytearray(test_pyc)
Guido van Rossumad8d3002007-08-03 18:40:49 +0000166 badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
Just van Rossum52e14d62002-12-30 22:08:05 +0000167 files = {TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
168 try:
169 self.doTest(".py", files, TESTMOD)
170 except ImportError:
171 pass
172 else:
173 self.fail("expected ImportError; import from bad pyc")
174
175 def testBadMTime(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000176 badtime_pyc = bytearray(test_pyc)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000177 # flip the second bit -- not the first as that one isn't stored in the
178 # .py's mtime in the zip archive.
179 badtime_pyc[7] ^= 0x02
Just van Rossum52e14d62002-12-30 22:08:05 +0000180 files = {TESTMOD + ".py": (NOW, test_src),
181 TESTMOD + pyc_ext: (NOW, badtime_pyc)}
182 self.doTest(".py", files, TESTMOD)
183
184 def testPackage(self):
185 packdir = TESTPACK + os.sep
186 files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
187 packdir + TESTMOD + pyc_ext: (NOW, test_pyc)}
188 self.doTest(pyc_ext, files, TESTPACK, TESTMOD)
189
190 def testDeepPackage(self):
191 packdir = TESTPACK + os.sep
Just van Rossumd35c6db2003-01-02 12:55:48 +0000192 packdir2 = packdir + TESTPACK2 + os.sep
Just van Rossum52e14d62002-12-30 22:08:05 +0000193 files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
194 packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
195 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
Just van Rossumd35c6db2003-01-02 12:55:48 +0000196 self.doTest(pyc_ext, files, TESTPACK, TESTPACK2, TESTMOD)
Just van Rossum52e14d62002-12-30 22:08:05 +0000197
Neal Norwitzb155b622006-01-23 07:52:13 +0000198 def testZipImporterMethods(self):
199 packdir = TESTPACK + os.sep
200 packdir2 = packdir + TESTPACK2 + os.sep
201 files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
202 packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
203 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
204
205 z = ZipFile(TEMP_ZIP, "w")
206 try:
207 for name, (mtime, data) in files.items():
208 zinfo = ZipInfo(name, time.localtime(mtime))
209 zinfo.compress_type = self.compression
210 z.writestr(zinfo, data)
211 z.close()
212
213 zi = zipimport.zipimporter(TEMP_ZIP)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000214 self.assertEquals(zi.archive, TEMP_ZIP)
Neal Norwitzb155b622006-01-23 07:52:13 +0000215 self.assertEquals(zi.is_package(TESTPACK), True)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000216 mod = zi.load_module(TESTPACK)
Nick Coghlan9a1d6e32009-02-08 03:37:27 +0000217 self.assertEquals(zi.get_filename(TESTPACK), mod.__file__)
Tim Petersbc29c1a2006-01-23 21:28:42 +0000218
Neal Norwitzb155b622006-01-23 07:52:13 +0000219 self.assertEquals(zi.is_package(packdir + '__init__'), False)
220 self.assertEquals(zi.is_package(packdir + TESTPACK2), True)
221 self.assertEquals(zi.is_package(packdir2 + TESTMOD), False)
222
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000223 mod_path = packdir2 + TESTMOD
224 mod_name = module_path_to_dotted_name(mod_path)
Georg Brandl89fad142010-03-14 10:23:39 +0000225 __import__(mod_name)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000226 mod = sys.modules[mod_name]
Neal Norwitzb155b622006-01-23 07:52:13 +0000227 self.assertEquals(zi.get_source(TESTPACK), None)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000228 self.assertEquals(zi.get_source(mod_path), None)
Nick Coghlan9a1d6e32009-02-08 03:37:27 +0000229 self.assertEquals(zi.get_filename(mod_path), mod.__file__)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000230 # To pass in the module name instead of the path, we must use the
231 # right importer
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000232 loader = mod.__loader__
233 self.assertEquals(loader.get_source(mod_name), None)
Nick Coghlan9a1d6e32009-02-08 03:37:27 +0000234 self.assertEquals(loader.get_filename(mod_name), mod.__file__)
Christian Heimes7f044312008-01-06 17:05:40 +0000235
236 # test prefix and archivepath members
237 zi2 = zipimport.zipimporter(TEMP_ZIP + os.sep + TESTPACK)
238 self.assertEquals(zi2.archive, TEMP_ZIP)
239 self.assertEquals(zi2.prefix, TESTPACK + os.sep)
Neal Norwitzb155b622006-01-23 07:52:13 +0000240 finally:
241 z.close()
242 os.remove(TEMP_ZIP)
243
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000244 def testZipImporterMethodsInSubDirectory(self):
245 packdir = TESTPACK + os.sep
246 packdir2 = packdir + TESTPACK2 + os.sep
247 files = {packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
248 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
249
250 z = ZipFile(TEMP_ZIP, "w")
251 try:
252 for name, (mtime, data) in files.items():
253 zinfo = ZipInfo(name, time.localtime(mtime))
254 zinfo.compress_type = self.compression
255 z.writestr(zinfo, data)
256 z.close()
257
258 zi = zipimport.zipimporter(TEMP_ZIP + os.sep + packdir)
259 self.assertEquals(zi.archive, TEMP_ZIP)
260 self.assertEquals(zi.prefix, packdir)
261 self.assertEquals(zi.is_package(TESTPACK2), True)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000262 mod = zi.load_module(TESTPACK2)
Nick Coghlan9a1d6e32009-02-08 03:37:27 +0000263 self.assertEquals(zi.get_filename(TESTPACK2), mod.__file__)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000264
Barry Warsaw28a691b2010-04-17 00:19:56 +0000265 self.assertEquals(
266 zi.is_package(TESTPACK2 + os.sep + '__init__'), False)
267 self.assertEquals(
268 zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000269
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000270 mod_path = TESTPACK2 + os.sep + TESTMOD
271 mod_name = module_path_to_dotted_name(mod_path)
Georg Brandl89fad142010-03-14 10:23:39 +0000272 __import__(mod_name)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000273 mod = sys.modules[mod_name]
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000274 self.assertEquals(zi.get_source(TESTPACK2), None)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000275 self.assertEquals(zi.get_source(mod_path), None)
Nick Coghlan9a1d6e32009-02-08 03:37:27 +0000276 self.assertEquals(zi.get_filename(mod_path), mod.__file__)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000277 # To pass in the module name instead of the path, we must use the
278 # right importer
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000279 loader = mod.__loader__
280 self.assertEquals(loader.get_source(mod_name), None)
Nick Coghlan9a1d6e32009-02-08 03:37:27 +0000281 self.assertEquals(loader.get_filename(mod_name), mod.__file__)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000282 finally:
283 z.close()
284 os.remove(TEMP_ZIP)
285
Just van Rossum52e14d62002-12-30 22:08:05 +0000286 def testGetData(self):
287 z = ZipFile(TEMP_ZIP, "w")
288 z.compression = self.compression
289 try:
290 name = "testdata.dat"
Guido van Rossumad8d3002007-08-03 18:40:49 +0000291 data = bytes(x for x in range(256))
Just van Rossum52e14d62002-12-30 22:08:05 +0000292 z.writestr(name, data)
293 z.close()
294 zi = zipimport.zipimporter(TEMP_ZIP)
295 self.assertEquals(data, zi.get_data(name))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000296 self.assertIn('zipimporter object', repr(zi))
Just van Rossum52e14d62002-12-30 22:08:05 +0000297 finally:
298 z.close()
299 os.remove(TEMP_ZIP)
300
301 def testImporterAttr(self):
302 src = """if 1: # indent hack
303 def get_file():
304 return __file__
Guido van Rossumad8d3002007-08-03 18:40:49 +0000305 if __loader__.get_data("some.data") != b"some data":
Collin Winter828f04a2007-08-31 00:04:24 +0000306 raise AssertionError("bad data")\n"""
Just van Rossum52e14d62002-12-30 22:08:05 +0000307 pyc = make_pyc(compile(src, "<???>", "exec"), NOW)
308 files = {TESTMOD + pyc_ext: (NOW, pyc),
309 "some.data": (NOW, "some data")}
310 self.doTest(pyc_ext, files, TESTMOD)
311
Thomas Heller354e3d92003-07-22 18:10:15 +0000312 def testImport_WithStuff(self):
313 # try importing from a zipfile which contains additional
314 # stuff at the beginning of the file
315 files = {TESTMOD + ".py": (NOW, test_src)}
316 self.doTest(".py", files, TESTMOD,
Guido van Rossum85825dc2007-08-27 17:03:28 +0000317 stuff=b"Some Stuff"*31)
Just van Rossum52e14d62002-12-30 22:08:05 +0000318
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000319 def assertModuleSource(self, module):
320 self.assertEqual(inspect.getsource(module), test_src)
321
322 def testGetSource(self):
323 files = {TESTMOD + ".py": (NOW, test_src)}
324 self.doTest(".py", files, TESTMOD, call=self.assertModuleSource)
325
326 def testGetCompiledSource(self):
327 pyc = make_pyc(compile(test_src, "<???>", "exec"), NOW)
328 files = {TESTMOD + ".py": (NOW, test_src),
329 TESTMOD + pyc_ext: (NOW, pyc)}
330 self.doTest(pyc_ext, files, TESTMOD, call=self.assertModuleSource)
331
332 def runDoctest(self, callback):
333 files = {TESTMOD + ".py": (NOW, test_src),
334 "xyz.txt": (NOW, ">>> log.append(True)\n")}
335 self.doTest(".py", files, TESTMOD, call=callback)
336
337 def doDoctestFile(self, module):
338 log = []
339 old_master, doctest.master = doctest.master, None
340 try:
341 doctest.testfile(
342 'xyz.txt', package=module, module_relative=True,
343 globs=locals()
344 )
345 finally:
346 doctest.master = old_master
347 self.assertEqual(log,[True])
348
349 def testDoctestFile(self):
350 self.runDoctest(self.doDoctestFile)
351
352 def doDoctestSuite(self, module):
353 log = []
354 doctest.DocFileTest(
355 'xyz.txt', package=module, module_relative=True,
356 globs=locals()
357 ).run()
358 self.assertEqual(log,[True])
359
360 def testDoctestSuite(self):
361 self.runDoctest(self.doDoctestSuite)
362
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000363 def doTraceback(self, module):
364 try:
365 module.do_raise()
366 except:
367 tb = sys.exc_info()[2].tb_next
368
369 f,lno,n,line = extract_tb(tb, 1)[0]
370 self.assertEqual(line, raise_src.strip())
371
372 f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
373 self.assertEqual(line, raise_src.strip())
374
Guido van Rossum34d19282007-08-09 01:03:29 +0000375 s = io.StringIO()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000376 print_tb(tb, 1, s)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000377 self.assertTrue(s.getvalue().endswith(raise_src))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000378 else:
379 raise AssertionError("This ought to be impossible")
380
381 def testTraceback(self):
382 files = {TESTMOD + ".py": (NOW, raise_src)}
383 self.doTest(None, files, TESTMOD, call=self.doTraceback)
384
Victor Stinner2460a432010-08-16 17:54:28 +0000385 @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
386 "need an unencodable filename")
Victor Stinner36e79112010-08-17 00:44:11 +0000387 def testUnencodable(self):
Victor Stinner2460a432010-08-16 17:54:28 +0000388 filename = support.TESTFN_UNENCODABLE + ".zip"
389 z = ZipFile(filename, "w")
390 zinfo = ZipInfo(TESTMOD + ".py", time.localtime(NOW))
391 zinfo.compress_type = self.compression
392 z.writestr(zinfo, test_src)
393 z.close()
394 try:
395 zipimport.zipimporter(filename)
396 finally:
397 os.remove(filename)
398
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000399
Ezio Melotti78ea2022009-09-12 18:41:20 +0000400@unittest.skipUnless(zlib, "requires zlib")
Just van Rossum52e14d62002-12-30 22:08:05 +0000401class CompressedZipImportTestCase(UncompressedZipImportTestCase):
402 compression = ZIP_DEFLATED
403
404
Neal Norwitzb155b622006-01-23 07:52:13 +0000405class BadFileZipImportTestCase(unittest.TestCase):
406 def assertZipFailure(self, filename):
407 self.assertRaises(zipimport.ZipImportError,
408 zipimport.zipimporter, filename)
409
410 def testNoFile(self):
411 self.assertZipFailure('AdfjdkFJKDFJjdklfjs')
412
413 def testEmptyFilename(self):
414 self.assertZipFailure('')
415
416 def testBadArgs(self):
417 self.assertRaises(TypeError, zipimport.zipimporter, None)
418 self.assertRaises(TypeError, zipimport.zipimporter, TESTMOD, kwd=None)
419
420 def testFilenameTooLong(self):
421 self.assertZipFailure('A' * 33000)
422
423 def testEmptyFile(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000424 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000425 open(TESTMOD, 'w+').close()
426 self.assertZipFailure(TESTMOD)
427
428 def testFileUnreadable(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000429 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000430 fd = os.open(TESTMOD, os.O_CREAT, 000)
Tim Peters68f2d002006-01-23 22:19:24 +0000431 try:
432 os.close(fd)
433 self.assertZipFailure(TESTMOD)
434 finally:
435 # If we leave "the read-only bit" set on Windows, nothing can
436 # delete TESTMOD, and later tests suffer bogus failures.
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000437 os.chmod(TESTMOD, 0o666)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000438 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000439
440 def testNotZipFile(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000441 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000442 fp = open(TESTMOD, 'w+')
443 fp.write('a' * 22)
444 fp.close()
445 self.assertZipFailure(TESTMOD)
446
Neal Norwitzdbc95f42006-01-23 08:48:03 +0000447 # XXX: disabled until this works on Big-endian machines
448 def _testBogusZipFile(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000449 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000450 fp = open(TESTMOD, 'w+')
451 fp.write(struct.pack('=I', 0x06054B50))
452 fp.write('a' * 18)
453 fp.close()
454 z = zipimport.zipimporter(TESTMOD)
455
456 try:
457 self.assertRaises(TypeError, z.find_module, None)
458 self.assertRaises(TypeError, z.load_module, None)
459 self.assertRaises(TypeError, z.is_package, None)
460 self.assertRaises(TypeError, z.get_code, None)
461 self.assertRaises(TypeError, z.get_data, None)
462 self.assertRaises(TypeError, z.get_source, None)
463
464 error = zipimport.ZipImportError
465 self.assertEqual(z.find_module('abc'), None)
466
467 self.assertRaises(error, z.load_module, 'abc')
468 self.assertRaises(error, z.get_code, 'abc')
469 self.assertRaises(IOError, z.get_data, 'abc')
470 self.assertRaises(error, z.get_source, 'abc')
471 self.assertRaises(error, z.is_package, 'abc')
472 finally:
473 zipimport._zip_directory_cache.clear()
474
475
476def cleanup():
477 # this is necessary if test is run repeated (like when finding leaks)
478 global test_imported
479 if test_imported:
480 zipimport._zip_directory_cache.clear()
481 if hasattr(UncompressedZipImportTestCase, 'testAFakeZlib'):
482 delattr(UncompressedZipImportTestCase, 'testAFakeZlib')
483 if hasattr(CompressedZipImportTestCase, 'testAFakeZlib'):
484 delattr(CompressedZipImportTestCase, 'testAFakeZlib')
485 test_imported = True
486
Neal Norwitz5c1ba532003-02-17 18:05:20 +0000487def test_main():
Neal Norwitzb155b622006-01-23 07:52:13 +0000488 cleanup()
489 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000490 support.run_unittest(
Neal Norwitzb155b622006-01-23 07:52:13 +0000491 UncompressedZipImportTestCase,
492 CompressedZipImportTestCase,
493 BadFileZipImportTestCase,
494 )
495 finally:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000496 support.unlink(TESTMOD)
Neal Norwitz5c1ba532003-02-17 18:05:20 +0000497
498if __name__ == "__main__":
499 test_main()