#! /usr/bin/env python"""Test script for the gzip module."""importunittestfromtestimporttest_supportimportosimportioimportstructgzip=test_support.import_module('gzip')data1=""" int length=DEFAULTALLOC, err = Z_OK; PyObject *RetVal; int flushmode = Z_FINISH; unsigned long start_total_out;"""data2="""/* zlibmodule.c -- gzip-compatible data compression *//* See http://www.gzip.org/zlib//* See http://www.winimage.com/zLibDll for Windows */"""classTestGzip(unittest.TestCase):filename=test_support.TESTFNdefsetUp(self):test_support.unlink(self.filename)deftearDown(self):test_support.unlink(self.filename)deftest_write(self):withgzip.GzipFile(self.filename,'wb')asf:f.write(data1*50)# Try flush and fileno.f.flush()f.fileno()ifhasattr(os,'fsync'):os.fsync(f.fileno())f.close()# Test multiple close() calls.f.close()deftest_read(self):self.test_write()# Try reading.withgzip.GzipFile(self.filename,'r')asf:d=f.read()self.assertEqual(d,data1*50)deftest_io_on_closed_object(self):# Test that I/O operations on closed GzipFile objects raise a# ValueError, just like the corresponding functions on file objects.# Write to a file, open it for reading, then close it.self.test_write()f=gzip.GzipFile(self.filename,'r')f.close()withself.assertRaises(ValueError):f.read(1)withself.assertRaises(ValueError):f.seek(0)withself.assertRaises(ValueError):f.tell()# Open the file for writing, then close it.f=gzip.GzipFile(self.filename,'w')f.close()withself.assertRaises(ValueError):f.write('')withself.assertRaises(ValueError):f.flush()deftest_append(self):self.test_write()# Append to the previous filewithgzip.GzipFile(self.filename,'ab')asf:f.write(data2*15)withgzip.GzipFile(self.filename,'rb')asf:d=f.read()self.assertEqual(d,(data1*50)+(data2*15))deftest_many_append(self):# Bug #1074261 was triggered when reading a file that contained# many, many members. Create such a file and verify that reading it# works.withgzip.open(self.filename,'wb',9)asf:f.write('a')foriinrange(0,200):withgzip.open(self.filename,"ab",9)asf:# appendf.write('a')# Try reading the filewithgzip.open(self.filename,"rb")aszgfile:contents=""while1:ztxt=zgfile.read(8192)contents+=ztxtifnotztxt:breakself.assertEqual(contents,'a'*201)deftest_buffered_reader(self):# Issue #7471: a GzipFile can be wrapped in a BufferedReader for# performance.self.test_write()withgzip.GzipFile(self.filename,'rb')asf:withio.BufferedReader(f)asr:lines=[lineforlineinr]self.assertEqual(lines,50*data1.splitlines(True))deftest_readline(self):self.test_write()# Try .readline() with varying line lengthswithgzip.GzipFile(self.filename,'rb')asf:line_length=0while1:L=f.readline(line_length)ifnotLandline_length!=0:breakself.assertTrue(len(L)<=line_length)line_length=(line_length+1)%50deftest_readlines(self):self.test_write()# Try .readlines()withgzip.GzipFile(self.filename,'rb')asf:L=f.readlines()withgzip.GzipFile(self.filename,'rb')asf:while1:L=f.readlines(150)ifL==[]:breakdeftest_seek_read(self):self.test_write()# Try seek, read testwithgzip.GzipFile(self.filename)asf:while1:oldpos=f.tell()line1=f.readline()ifnotline1:breaknewpos=f.tell()f.seek(oldpos)# negative seekiflen(line1)>10:amount=10else:amount=len(line1)line2=f.read(amount)self.assertEqual(line1[:amount],line2)f.seek(newpos)# positive seekdeftest_seek_whence(self):self.test_write()# Try seek(whence=1), read testwithgzip.GzipFile(self.filename)asf:f.read(10)f.seek(10,whence=1)y=f.read(10)self.assertEqual(y,data1[20:30])deftest_seek_write(self):# Try seek, write testwithgzip.GzipFile(self.filename,'w')asf:forposinrange(0,256,16):f.seek(pos)f.write('GZ\n')deftest_mode(self):self.test_write()withgzip.GzipFile(self.filename,'r')asf:self.assertEqual(f.myfileobj.mode,'rb')deftest_1647484(self):formodein('wb','rb'):withgzip.GzipFile(self.filename,mode)asf:self.assertTrue(hasattr(f,"name"))self.assertEqual(f.name,self.filename)deftest_mtime(self):mtime=123456789withgzip.GzipFile(self.filename,'w',mtime=mtime)asfWrite:fWrite.write(data1)withgzip.GzipFile(self.filename)asfRead:dataRead=fRead.read()self.assertEqual(dataRead,data1)self.assertTrue(hasattr(fRead,'mtime'))self.assertEqual(fRead.mtime,mtime)deftest_metadata(self):mtime=123456789withgzip.GzipFile(self.filename,'w',mtime=mtime)asfWrite:fWrite.write(data1)withopen(self.filename,'rb')asfRead:# see RFC 1952: http://www.faqs.org/rfcs/rfc1952.htmlidBytes=fRead.read(2)self.assertEqual(idBytes,'\x1f\x8b')# gzip IDcmByte=fRead.read(1)self.assertEqual(cmByte,'\x08')# deflateflagsByte=fRead.read(1)self.assertEqual(flagsByte,'\x08')# only the FNAME flag is setmtimeBytes=fRead.read(4)self.assertEqual(mtimeBytes,struct.pack('<i',mtime))# little-endianxflByte=fRead.read(1)self.assertEqual(xflByte,'\x02')# maximum compressionosByte=fRead.read(1)self.assertEqual(osByte,'\xff')# OS "unknown" (OS-independent)# Since the FNAME flag is set, the zero-terminated filename follows.# RFC 1952 specifies that this is the name of the input file, if any.# However, the gzip module defaults to storing the name of the output# file in this field.expected=self.filename.encode('Latin-1')+'\x00'nameBytes=fRead.read(len(expected))self.assertEqual(nameBytes,expected)# Since no other flags were set, the header ends here.# Rather than process the compressed data, let's seek to the trailer.fRead.seek(os.stat(self.filename).st_size-8)crc32Bytes=fRead.read(4)# CRC32 of uncompressed data [data1]self.assertEqual(crc32Bytes,'\xaf\xd7d\x83')isizeBytes=fRead.read(4)self.assertEqual(isizeBytes,struct.pack('<i',len(data1)))deftest_with_open(self):# GzipFile supports the context management protocolwithgzip.GzipFile(self.filename,"wb")asf:f.write(b"xxx")f=gzip.GzipFile(self.filename,"rb")f.close()try:withf:passexceptValueError:passelse:self.fail("__enter__ on a closed file didn't raise an exception")try:withgzip.GzipFile(self.filename,"wb")asf:1//0exceptZeroDivisionError:passelse:self.fail("1 // 0 didn't raise an exception")deftest_zero_padded_file(self):withgzip.GzipFile(self.filename,"wb")asf:f.write(data1*50)# Pad the file with zeroeswithopen(self.filename,"ab")asf:f.write("\x00"*50)withgzip.GzipFile(self.filename,"rb")asf:d=f.read()self.assertEqual(d,data1*50,"Incorrect data in file")deftest_fileobj_from_fdopen(self):# Issue #13781: Creating a GzipFile using a fileobj from os.fdopen()# should not embed the fake filename "<fdopen>" in the output file.fd=os.open(self.filename,os.O_WRONLY|os.O_CREAT)withos.fdopen(fd,"wb")asf:withgzip.GzipFile(fileobj=f,mode="w")asg:self.assertEqual(g.name,"")deftest_main(verbose=None):test_support.run_unittest(TestGzip)if__name__=="__main__":test_main(verbose=True)