blob: 50b8b36a859e72fb44c3f46f757742c00497f429 [file] [log] [blame]
Fred Drake3d9091e2001-03-26 15:49:24 +00001import zipfile, os, StringIO, tempfile
Fred Drake6e7e4852001-02-28 05:34:16 +00002from test_support import TestFailed
Guido van Rossum368f04a2000-04-10 13:23:04 +00003
4srcname = "junk9630.tmp"
5zipname = "junk9708.tmp"
6
Fred Drake3d9091e2001-03-26 15:49:24 +00007
8def zipTest(f, compression, srccontents):
9 zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive
10 zip.write(srcname, "another.name")
11 zip.write(srcname, srcname)
12 zip.close()
Tim Petersa19a1682001-03-29 04:36:09 +000013
Fred Drake3d9091e2001-03-26 15:49:24 +000014 zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive
15 readData2 = zip.read(srcname)
16 readData1 = zip.read("another.name")
17 zip.close()
Tim Petersa19a1682001-03-29 04:36:09 +000018
Fred Drake3d9091e2001-03-26 15:49:24 +000019 if readData1 != srccontents or readData2 != srccontents:
20 raise TestFailed, "Written data doesn't equal read data."
21
22
Guido van Rossum368f04a2000-04-10 13:23:04 +000023try:
Fred Drake3d9091e2001-03-26 15:49:24 +000024 fp = open(srcname, "wb") # Make a source file with some lines
Fred Drake004d5e62000-10-23 17:22:08 +000025 for i in range(0, 1000):
26 fp.write("Test of zipfile line %d.\n" % i)
27 fp.close()
Tim Petersa19a1682001-03-29 04:36:09 +000028
Fred Drake3d9091e2001-03-26 15:49:24 +000029 fp = open(srcname, "rb")
30 writtenData = fp.read()
31 fp.close()
Tim Petersa19a1682001-03-29 04:36:09 +000032
Fred Drake3d9091e2001-03-26 15:49:24 +000033 for file in (zipname, tempfile.TemporaryFile(), StringIO.StringIO()):
34 zipTest(file, zipfile.ZIP_STORED, writtenData)
Guido van Rossum368f04a2000-04-10 13:23:04 +000035
Fred Drake3d9091e2001-03-26 15:49:24 +000036 for file in (zipname, tempfile.TemporaryFile(), StringIO.StringIO()):
37 zipTest(file, zipfile.ZIP_DEFLATED, writtenData)
Guido van Rossum368f04a2000-04-10 13:23:04 +000038
Guido van Rossum368f04a2000-04-10 13:23:04 +000039finally:
Fred Drake004d5e62000-10-23 17:22:08 +000040 if os.path.isfile(srcname): # Remove temporary files
41 os.unlink(srcname)
42 if os.path.isfile(zipname):
43 os.unlink(zipname)
Fred Drake6e7e4852001-02-28 05:34:16 +000044
45# make sure we don't raise an AttributeError when a partially-constructed
46# ZipFile instance is finalized; this tests for regression on SF tracker
47# bug #403871.
48try:
49 zipfile.ZipFile(srcname)
50except IOError:
51 # The bug we're testing for caused an AttributeError to be raised
52 # when a ZipFile instance was created for a file that did not
53 # exist; the .fp member was not initialized but was needed by the
54 # __del__() method. Since the AttributeError is in the __del__(),
55 # it is ignored, but the user should be sufficiently annoyed by
56 # the message on the output that regression will be noticed
57 # quickly.
58 pass
59else:
60 raise TestFailed("expected creation of readable ZipFile without\n"
61 " a file to raise an IOError.")