This commit was manufactured by cvs2svn to create tag 'r211c1'.
[python/dscho.git] / Lib / test / test_zipfile.py
blob87e99ec0719a59c05e8a1fc0d12897cbeb0f3e95
1 import zlib # implied prerequisite
2 import zipfile, os, StringIO, tempfile
3 from test_support import TestFailed
5 srcname = "junk9630.tmp"
6 zipname = "junk9708.tmp"
9 def zipTest(f, compression, srccontents):
10 zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive
11 zip.write(srcname, "another.name")
12 zip.write(srcname, srcname)
13 zip.close()
15 zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive
16 readData2 = zip.read(srcname)
17 readData1 = zip.read("another.name")
18 zip.close()
20 if readData1 != srccontents or readData2 != srccontents:
21 raise TestFailed, "Written data doesn't equal read data."
24 try:
25 fp = open(srcname, "wb") # Make a source file with some lines
26 for i in range(0, 1000):
27 fp.write("Test of zipfile line %d.\n" % i)
28 fp.close()
30 fp = open(srcname, "rb")
31 writtenData = fp.read()
32 fp.close()
34 for file in (zipname, tempfile.TemporaryFile(), StringIO.StringIO()):
35 zipTest(file, zipfile.ZIP_STORED, writtenData)
37 for file in (zipname, tempfile.TemporaryFile(), StringIO.StringIO()):
38 zipTest(file, zipfile.ZIP_DEFLATED, writtenData)
40 finally:
41 if os.path.isfile(srcname): # Remove temporary files
42 os.unlink(srcname)
43 if os.path.isfile(zipname):
44 os.unlink(zipname)
47 # This test checks that the ZipFile constructor closes the file object
48 # it opens if there's an error in the file. If it doesn't, the traceback
49 # holds a reference to the ZipFile object and, indirectly, the file object.
50 # On Windows, this causes the os.unlink() call to fail because the
51 # underlying file is still open. This is SF bug #412214.
53 fp = open(srcname, "w")
54 fp.write("this is not a legal zip file\n")
55 fp.close()
56 try:
57 zf = zipfile.ZipFile(srcname)
58 except zipfile.BadZipfile:
59 os.unlink(srcname)
62 # make sure we don't raise an AttributeError when a partially-constructed
63 # ZipFile instance is finalized; this tests for regression on SF tracker
64 # bug #403871.
65 try:
66 zipfile.ZipFile(srcname)
67 except IOError:
68 # The bug we're testing for caused an AttributeError to be raised
69 # when a ZipFile instance was created for a file that did not
70 # exist; the .fp member was not initialized but was needed by the
71 # __del__() method. Since the AttributeError is in the __del__(),
72 # it is ignored, but the user should be sufficiently annoyed by
73 # the message on the output that regression will be noticed
74 # quickly.
75 pass
76 else:
77 raise TestFailed("expected creation of readable ZipFile without\n"
78 " a file to raise an IOError.")