Skip to content

Commit

Permalink
bpo-33038: Fix gzip.GzipFile for file objects with a non-string name …
Browse files Browse the repository at this point in the history
…attribute. (pythonGH-6095)
  • Loading branch information
bbayles authored and serhiy-storchaka committed May 9, 2018
1 parent d7e783b commit afe5f63
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 3 deletions.
5 changes: 2 additions & 3 deletions Lib/gzip.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,8 @@ def __init__(self, filename=None, mode=None,
if filename is None:
# Issue #13781: os.fdopen() creates a fileobj with a bogus name
# attribute. Avoid saving this in the gzip header's filename field.
if hasattr(fileobj, 'name') and fileobj.name != '<fdopen>':
filename = fileobj.name
else:
filename = getattr(fileobj, 'name', '')
if not isinstance(filename, basestring) or filename == '<fdopen>':
filename = ''
if mode is None:
if hasattr(fileobj, 'mode'): mode = fileobj.mode
Expand Down
15 changes: 15 additions & 0 deletions Lib/test/test_gzip.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import os
import io
import struct
import tempfile
gzip = test_support.import_module('gzip')

data1 = """ int length=DEFAULTALLOC, err = Z_OK;
Expand Down Expand Up @@ -331,6 +332,12 @@ def test_fileobj_from_fdopen(self):
with gzip.GzipFile(fileobj=f, mode="w") as g:
self.assertEqual(g.name, "")

def test_fileobj_from_io_open(self):
fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT)
with io.open(fd, "wb") as f:
with gzip.GzipFile(fileobj=f, mode="w") as g:
self.assertEqual(g.name, "")

def test_fileobj_mode(self):
gzip.GzipFile(self.filename, "wb").close()
with open(self.filename, "r+b") as f:
Expand Down Expand Up @@ -359,6 +366,14 @@ def test_read_with_extra(self):
with gzip.GzipFile(fileobj=io.BytesIO(gzdata)) as f:
self.assertEqual(f.read(), b'Test')

def test_fileobj_without_name(self):
# Issue #33038: GzipFile should not assume that file objects that have
# a .name attribute use a non-None value.
with tempfile.SpooledTemporaryFile() as f:
with gzip.GzipFile(fileobj=f, mode='wb') as archive:
archive.write(b'data')
self.assertEqual(archive.name, '')

def test_main(verbose=None):
test_support.run_unittest(TestGzip)

Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ Michael R Bax
Anthony Baxter
Mike Bayer
Samuel L. Bayer
Bo Bayles
Donald Beaudry
David Beazley
Carlo Beccarini
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
gzip.GzipFile no longer produces an AttributeError exception when used with
a file object with a non-string name attribute. Patch by Bo Bayles.

0 comments on commit afe5f63

Please sign in to comment.