# HG changeset patch # User Jeffrey Finkelstein # Date 1284569399 14400 # Branch py3k # Node ID 42b46e64900d38ec56bdfa0f45237d322e633206 # Parent 4ea5a13762e53b439a6f86833f6d5b36167acac1 fix for issue #9759: adds a check to GzipFile.read(), GzipFile.write(), and GzipFile.flush() which raises a ValueError if I/O operations are performed on a closed file diff -r 4ea5a13762e5 -r 42b46e64900d Lib/gzip.py --- a/Lib/gzip.py Wed Sep 15 17:13:17 2010 +0200 +++ b/Lib/gzip.py Wed Sep 15 12:49:59 2010 -0400 @@ -150,6 +150,13 @@ s = repr(self.fileobj) return '' + def _check_closed(self): + """Raises a ValueError if the underlying file object has been closed. + + """ + if self.closed: + raise ValueError('I/O operation on closed file.') + def _init_write(self, filename): self.name = filename self.crc = zlib.crc32(b"") & 0xffffffff @@ -220,6 +227,7 @@ self.fileobj.read(2) # Read & discard the 16-bit header CRC def write(self,data): + self._check_closed() if self.mode != WRITE: import errno raise IOError(errno.EBADF, "write() on read-only GzipFile object") @@ -240,6 +248,7 @@ return len(data) def read(self, size=-1): + self._check_closed() if self.mode != READ: import errno raise IOError(errno.EBADF, "read() on write-only GzipFile object") @@ -377,6 +386,7 @@ self.myfileobj = None def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH): + self._check_closed() if self.mode == WRITE: # Ensure the compressor's buffer is flushed self.fileobj.write(self.compress.flush(zlib_mode)) diff -r 4ea5a13762e5 -r 42b46e64900d Lib/test/test_gzip.py --- a/Lib/test/test_gzip.py Wed Sep 15 17:13:17 2010 +0200 +++ b/Lib/test/test_gzip.py Wed Sep 15 12:49:59 2010 -0400 @@ -51,6 +51,29 @@ f = gzip.GzipFile(self.filename, 'r') ; d = f.read() ; f.close() self.assertEqual(d, data1*50) + def test_io_on_closed_object(self): + """Tests 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() + + with self.assertRaises(ValueError): + f.read() + + # Open the file for writing, then close it. + f = gzip.GzipFile(self.filename, 'w') + f.close() + + with self.assertRaises(ValueError): + f.write('') + + with self.assertRaises(ValueError): + f.flush() + def test_append(self): self.test_write() # Append to the previous file