PageRenderTime 69ms CodeModel.GetById 37ms app.highlight 27ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/test/test_zipimport.py

http://unladen-swallow.googlecode.com/
Python | 482 lines | 433 code | 26 blank | 23 comment | 16 complexity | 7cf6753c6fd404c1c6071e8cf620b231 MD5 | raw file
  1import sys
  2import os
  3import marshal
  4import imp
  5import struct
  6import time
  7import unittest
  8
  9import zlib # implied prerequisite
 10from zipfile import ZipFile, ZipInfo, ZIP_STORED, ZIP_DEFLATED
 11from test import test_support
 12from test.test_importhooks import ImportHooksBaseTestCase, test_src, test_co
 13
 14import zipimport
 15import linecache
 16import doctest
 17import inspect
 18import StringIO
 19from traceback import extract_tb, extract_stack, print_tb
 20raise_src = 'def do_raise(): raise TypeError\n'
 21
 22# so we only run testAFakeZlib once if this test is run repeatedly
 23# which happens when we look for ref leaks
 24test_imported = False
 25
 26
 27def make_pyc(co, mtime):
 28    data = marshal.dumps(co)
 29    if type(mtime) is type(0.0):
 30        # Mac mtimes need a bit of special casing
 31        if mtime < 0x7fffffff:
 32            mtime = int(mtime)
 33        else:
 34            mtime = int(-0x100000000L + long(mtime))
 35    pyc = imp.get_magic() + struct.pack("<i", int(mtime)) + data
 36    return pyc
 37
 38def module_path_to_dotted_name(path):
 39    return path.replace(os.sep, '.')
 40
 41NOW = time.time()
 42test_pyc = make_pyc(test_co, NOW)
 43
 44
 45if __debug__:
 46    pyc_ext = ".pyc"
 47else:
 48    pyc_ext = ".pyo"
 49
 50
 51TESTMOD = "ziptestmodule"
 52TESTPACK = "ziptestpackage"
 53TESTPACK2 = "ziptestpackage2"
 54TEMP_ZIP = os.path.abspath("junk95142" + os.extsep + "zip")
 55
 56class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
 57
 58    compression = ZIP_STORED
 59
 60    def setUp(self):
 61        # We're reusing the zip archive path, so we must clear the
 62        # cached directory info and linecache
 63        linecache.clearcache()
 64        zipimport._zip_directory_cache.clear()
 65        ImportHooksBaseTestCase.setUp(self)
 66
 67    def doTest(self, expected_ext, files, *modules, **kw):
 68        z = ZipFile(TEMP_ZIP, "w")
 69        try:
 70            for name, (mtime, data) in files.items():
 71                zinfo = ZipInfo(name, time.localtime(mtime))
 72                zinfo.compress_type = self.compression
 73                z.writestr(zinfo, data)
 74            z.close()
 75
 76            stuff = kw.get("stuff", None)
 77            if stuff is not None:
 78                # Prepend 'stuff' to the start of the zipfile
 79                f = open(TEMP_ZIP, "rb")
 80                data = f.read()
 81                f.close()
 82
 83                f = open(TEMP_ZIP, "wb")
 84                f.write(stuff)
 85                f.write(data)
 86                f.close()
 87
 88            sys.path.insert(0, TEMP_ZIP)
 89
 90            mod = __import__(".".join(modules), globals(), locals(),
 91                             ["__dummy__"])
 92
 93            call = kw.get('call')
 94            if call is not None:
 95                call(mod)
 96
 97            if expected_ext:
 98                file = mod.get_file()
 99                self.assertEquals(file, os.path.join(TEMP_ZIP,
100                                  *modules) + expected_ext)
101        finally:
102            z.close()
103            os.remove(TEMP_ZIP)
104
105    def testAFakeZlib(self):
106        #
107        # This could cause a stack overflow before: importing zlib.py
108        # from a compressed archive would cause zlib to be imported
109        # which would find zlib.py in the archive, which would... etc.
110        #
111        # This test *must* be executed first: it must be the first one
112        # to trigger zipimport to import zlib (zipimport caches the
113        # zlib.decompress function object, after which the problem being
114        # tested here wouldn't be a problem anymore...
115        # (Hence the 'A' in the test method name: to make it the first
116        # item in a list sorted by name, like unittest.makeSuite() does.)
117        #
118        # This test fails on platforms on which the zlib module is
119        # statically linked, but the problem it tests for can't
120        # occur in that case (builtin modules are always found first),
121        # so we'll simply skip it then. Bug #765456.
122        #
123        if "zlib" in sys.builtin_module_names:
124            return
125        if "zlib" in sys.modules:
126            del sys.modules["zlib"]
127        files = {"zlib.py": (NOW, test_src)}
128        try:
129            self.doTest(".py", files, "zlib")
130        except ImportError:
131            if self.compression != ZIP_DEFLATED:
132                self.fail("expected test to not raise ImportError")
133        else:
134            if self.compression != ZIP_STORED:
135                self.fail("expected test to raise ImportError")
136
137    def testPy(self):
138        files = {TESTMOD + ".py": (NOW, test_src)}
139        self.doTest(".py", files, TESTMOD)
140
141    def testPyc(self):
142        files = {TESTMOD + pyc_ext: (NOW, test_pyc)}
143        self.doTest(pyc_ext, files, TESTMOD)
144
145    def testBoth(self):
146        files = {TESTMOD + ".py": (NOW, test_src),
147                 TESTMOD + pyc_ext: (NOW, test_pyc)}
148        self.doTest(pyc_ext, files, TESTMOD)
149
150    def testEmptyPy(self):
151        files = {TESTMOD + ".py": (NOW, "")}
152        self.doTest(None, files, TESTMOD)
153
154    def testBadMagic(self):
155        # make pyc magic word invalid, forcing loading from .py
156        m0 = ord(test_pyc[0])
157        m0 ^= 0x04  # flip an arbitrary bit
158        badmagic_pyc = chr(m0) + test_pyc[1:]
159        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
165        m0 = ord(test_pyc[0])
166        m0 ^= 0x04  # flip an arbitrary bit
167        badmagic_pyc = chr(m0) + test_pyc[1:]
168        files = {TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
169        try:
170            self.doTest(".py", files, TESTMOD)
171        except ImportError:
172            pass
173        else:
174            self.fail("expected ImportError; import from bad pyc")
175
176    def testBadMTime(self):
177        t3 = ord(test_pyc[7])
178        t3 ^= 0x02  # flip the second bit -- not the first as that one
179                    # isn't stored in the .py's mtime in the zip archive.
180        badtime_pyc = test_pyc[:7] + chr(t3) + test_pyc[8:]
181        files = {TESTMOD + ".py": (NOW, test_src),
182                 TESTMOD + pyc_ext: (NOW, badtime_pyc)}
183        self.doTest(".py", files, TESTMOD)
184
185    def testPackage(self):
186        packdir = TESTPACK + os.sep
187        files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
188                 packdir + TESTMOD + pyc_ext: (NOW, test_pyc)}
189        self.doTest(pyc_ext, files, TESTPACK, TESTMOD)
190
191    def testDeepPackage(self):
192        packdir = TESTPACK + os.sep
193        packdir2 = packdir + TESTPACK2 + os.sep
194        files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
195                 packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
196                 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
197        self.doTest(pyc_ext, files, TESTPACK, TESTPACK2, TESTMOD)
198
199    def testZipImporterMethods(self):
200        packdir = TESTPACK + os.sep
201        packdir2 = packdir + TESTPACK2 + os.sep
202        files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
203                 packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
204                 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
205
206        z = ZipFile(TEMP_ZIP, "w")
207        try:
208            for name, (mtime, data) in files.items():
209                zinfo = ZipInfo(name, time.localtime(mtime))
210                zinfo.compress_type = self.compression
211                z.writestr(zinfo, data)
212            z.close()
213
214            zi = zipimport.zipimporter(TEMP_ZIP)
215            self.assertEquals(zi.archive, TEMP_ZIP)
216            self.assertEquals(zi.is_package(TESTPACK), True)
217            mod = zi.load_module(TESTPACK)
218            self.assertEquals(zi._get_filename(TESTPACK), mod.__file__)
219
220            self.assertEquals(zi.is_package(packdir + '__init__'), False)
221            self.assertEquals(zi.is_package(packdir + TESTPACK2), True)
222            self.assertEquals(zi.is_package(packdir2 + TESTMOD), False)
223
224            mod_path = packdir2 + TESTMOD
225            mod_name = module_path_to_dotted_name(mod_path)
226            pkg = __import__(mod_name)
227            mod = sys.modules[mod_name]
228            self.assertEquals(zi.get_source(TESTPACK), None)
229            self.assertEquals(zi.get_source(mod_path), None)
230            self.assertEquals(zi._get_filename(mod_path), mod.__file__)
231            # To pass in the module name instead of the path, we must use the right importer
232            loader = mod.__loader__
233            self.assertEquals(loader.get_source(mod_name), None)
234            self.assertEquals(loader._get_filename(mod_name), mod.__file__)
235
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)
240        finally:
241            z.close()
242            os.remove(TEMP_ZIP)
243
244    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)
262            mod = zi.load_module(TESTPACK2)
263            self.assertEquals(zi._get_filename(TESTPACK2), mod.__file__)
264
265            self.assertEquals(zi.is_package(TESTPACK2 + os.sep + '__init__'), False)
266            self.assertEquals(zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)
267
268            mod_path = TESTPACK2 + os.sep + TESTMOD
269            mod_name = module_path_to_dotted_name(mod_path)
270            pkg = __import__(mod_name)
271            mod = sys.modules[mod_name]
272            self.assertEquals(zi.get_source(TESTPACK2), None)
273            self.assertEquals(zi.get_source(mod_path), None)
274            self.assertEquals(zi._get_filename(mod_path), mod.__file__)
275            # To pass in the module name instead of the path, we must use the right importer
276            loader = mod.__loader__
277            self.assertEquals(loader.get_source(mod_name), None)
278            self.assertEquals(loader._get_filename(mod_name), mod.__file__)
279        finally:
280            z.close()
281            os.remove(TEMP_ZIP)
282
283    def testGetData(self):
284        z = ZipFile(TEMP_ZIP, "w")
285        z.compression = self.compression
286        try:
287            name = "testdata.dat"
288            data = "".join([chr(x) for x in range(256)]) * 500
289            z.writestr(name, data)
290            z.close()
291            zi = zipimport.zipimporter(TEMP_ZIP)
292            self.assertEquals(data, zi.get_data(name))
293            self.assert_('zipimporter object' in repr(zi))
294        finally:
295            z.close()
296            os.remove(TEMP_ZIP)
297
298    def testImporterAttr(self):
299        src = """if 1:  # indent hack
300        def get_file():
301            return __file__
302        if __loader__.get_data("some.data") != "some data":
303            raise AssertionError, "bad data"\n"""
304        pyc = make_pyc(compile(src, "<???>", "exec"), NOW)
305        files = {TESTMOD + pyc_ext: (NOW, pyc),
306                 "some.data": (NOW, "some data")}
307        self.doTest(pyc_ext, files, TESTMOD)
308
309    def testImport_WithStuff(self):
310        # try importing from a zipfile which contains additional
311        # stuff at the beginning of the file
312        files = {TESTMOD + ".py": (NOW, test_src)}
313        self.doTest(".py", files, TESTMOD,
314                    stuff="Some Stuff"*31)
315
316    def assertModuleSource(self, module):
317        self.assertEqual(inspect.getsource(module), test_src)
318
319    def testGetSource(self):
320        files = {TESTMOD + ".py": (NOW, test_src)}
321        self.doTest(".py", files, TESTMOD, call=self.assertModuleSource)
322
323    def testGetCompiledSource(self):
324        pyc = make_pyc(compile(test_src, "<???>", "exec"), NOW)
325        files = {TESTMOD + ".py": (NOW, test_src),
326                 TESTMOD + pyc_ext: (NOW, pyc)}
327        self.doTest(pyc_ext, files, TESTMOD, call=self.assertModuleSource)
328
329    def runDoctest(self, callback):
330        files = {TESTMOD + ".py": (NOW, test_src),
331                 "xyz.txt": (NOW, ">>> log.append(True)\n")}
332        self.doTest(".py", files, TESTMOD, call=callback)
333
334    def doDoctestFile(self, module):
335        log = []
336        old_master, doctest.master = doctest.master, None
337        try:
338            doctest.testfile(
339                'xyz.txt', package=module, module_relative=True,
340                globs=locals()
341            )
342        finally:
343            doctest.master = old_master
344        self.assertEqual(log,[True])
345
346    def testDoctestFile(self):
347        self.runDoctest(self.doDoctestFile)
348
349    def doDoctestSuite(self, module):
350        log = []
351        doctest.DocFileTest(
352            'xyz.txt', package=module, module_relative=True,
353            globs=locals()
354        ).run()
355        self.assertEqual(log,[True])
356
357    def testDoctestSuite(self):
358        self.runDoctest(self.doDoctestSuite)
359
360
361    def doTraceback(self, module):
362        try:
363            module.do_raise()
364        except:
365            tb = sys.exc_info()[2].tb_next
366
367            f,lno,n,line = extract_tb(tb, 1)[0]
368            self.assertEqual(line, raise_src.strip())
369
370            f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
371            self.assertEqual(line, raise_src.strip())
372
373            s = StringIO.StringIO()
374            print_tb(tb, 1, s)
375            self.failUnless(s.getvalue().endswith(raise_src))
376        else:
377            raise AssertionError("This ought to be impossible")
378
379    def testTraceback(self):
380        files = {TESTMOD + ".py": (NOW, raise_src)}
381        self.doTest(None, files, TESTMOD, call=self.doTraceback)
382
383
384class CompressedZipImportTestCase(UncompressedZipImportTestCase):
385    compression = ZIP_DEFLATED
386
387
388class BadFileZipImportTestCase(unittest.TestCase):
389    def assertZipFailure(self, filename):
390        self.assertRaises(zipimport.ZipImportError,
391                          zipimport.zipimporter, filename)
392
393    def testNoFile(self):
394        self.assertZipFailure('AdfjdkFJKDFJjdklfjs')
395
396    def testEmptyFilename(self):
397        self.assertZipFailure('')
398
399    def testBadArgs(self):
400        self.assertRaises(TypeError, zipimport.zipimporter, None)
401        self.assertRaises(TypeError, zipimport.zipimporter, TESTMOD, kwd=None)
402
403    def testFilenameTooLong(self):
404        self.assertZipFailure('A' * 33000)
405
406    def testEmptyFile(self):
407        test_support.unlink(TESTMOD)
408        open(TESTMOD, 'w+').close()
409        self.assertZipFailure(TESTMOD)
410
411    def testFileUnreadable(self):
412        test_support.unlink(TESTMOD)
413        fd = os.open(TESTMOD, os.O_CREAT, 000)
414        try:
415            os.close(fd)
416            self.assertZipFailure(TESTMOD)
417        finally:
418            # If we leave "the read-only bit" set on Windows, nothing can
419            # delete TESTMOD, and later tests suffer bogus failures.
420            os.chmod(TESTMOD, 0666)
421            test_support.unlink(TESTMOD)
422
423    def testNotZipFile(self):
424        test_support.unlink(TESTMOD)
425        fp = open(TESTMOD, 'w+')
426        fp.write('a' * 22)
427        fp.close()
428        self.assertZipFailure(TESTMOD)
429
430    # XXX: disabled until this works on Big-endian machines
431    def _testBogusZipFile(self):
432        test_support.unlink(TESTMOD)
433        fp = open(TESTMOD, 'w+')
434        fp.write(struct.pack('=I', 0x06054B50))
435        fp.write('a' * 18)
436        fp.close()
437        z = zipimport.zipimporter(TESTMOD)
438
439        try:
440            self.assertRaises(TypeError, z.find_module, None)
441            self.assertRaises(TypeError, z.load_module, None)
442            self.assertRaises(TypeError, z.is_package, None)
443            self.assertRaises(TypeError, z.get_code, None)
444            self.assertRaises(TypeError, z.get_data, None)
445            self.assertRaises(TypeError, z.get_source, None)
446
447            error = zipimport.ZipImportError
448            self.assertEqual(z.find_module('abc'), None)
449
450            self.assertRaises(error, z.load_module, 'abc')
451            self.assertRaises(error, z.get_code, 'abc')
452            self.assertRaises(IOError, z.get_data, 'abc')
453            self.assertRaises(error, z.get_source, 'abc')
454            self.assertRaises(error, z.is_package, 'abc')
455        finally:
456            zipimport._zip_directory_cache.clear()
457
458
459def cleanup():
460    # this is necessary if test is run repeated (like when finding leaks)
461    global test_imported
462    if test_imported:
463        zipimport._zip_directory_cache.clear()
464        if hasattr(UncompressedZipImportTestCase, 'testAFakeZlib'):
465            delattr(UncompressedZipImportTestCase, 'testAFakeZlib')
466        if hasattr(CompressedZipImportTestCase, 'testAFakeZlib'):
467            delattr(CompressedZipImportTestCase, 'testAFakeZlib')
468    test_imported = True
469
470def test_main():
471    cleanup()
472    try:
473        test_support.run_unittest(
474              UncompressedZipImportTestCase,
475              CompressedZipImportTestCase,
476              BadFileZipImportTestCase,
477            )
478    finally:
479        test_support.unlink(TESTMOD)
480
481if __name__ == "__main__":
482    test_main()