# Demonstrates problem with gzip.GzipFile.flush() # # flush() is expected to output all pending data stored # in internal buffers. # gzip.GzipFile.flush() does perform a flush on its # fileobj, but does not flush the state of its compressobj # prior to the IO flush. # # 26 Jan 2005 - david.schnepper@verity.com import cStringIO import gzip import sys print "Python %s\n"%sys.version uncompressed_data = "abc" * 1000 restored_data = "" stringbuffer = cStringIO.StringIO() gzip_file = gzip.GzipFile(mode="wb", fileobj = stringbuffer) initial_output = stringbuffer.getvalue()[:] gzip_file.write( uncompressed_data ) gzip_file.flush() after_flush = stringbuffer.getvalue()[:] if len(initial_output) >= len(after_flush): print "FAIL: Data has been written to GzipFile, and flush() has been invoked." print " But no additional bytes are in the output stream." print " This indicates that flush() did not flush the state of all internal buffers" print " len(original) = %d"%len(initial_output) print " len(after) = %d"%len(after_flush) gzip_file.close() # It is OK for close() to write additional data # Ensure the data can be restored. after_close = stringbuffer.getvalue()[:] in_file = cStringIO.StringIO(after_close) restored_data = gzip.GzipFile(mode="rb", fileobj = in_file).read() if restored_data != uncompressed_data: print "FAIL: uncompressed data does not match restored data"