Skip to content

Commit afe5f63

Browse files
bbaylesserhiy-storchaka
authored andcommitted
bpo-33038: Fix gzip.GzipFile for file objects with a non-string name attribute. (GH-6095)
1 parent d7e783b commit afe5f63

File tree

4 files changed

+20
-3
lines changed

4 files changed

+20
-3
lines changed

Lib/gzip.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,9 +95,8 @@ def __init__(self, filename=None, mode=None,
9595
if filename is None:
9696
# Issue #13781: os.fdopen() creates a fileobj with a bogus name
9797
# attribute. Avoid saving this in the gzip header's filename field.
98-
if hasattr(fileobj, 'name') and fileobj.name != '<fdopen>':
99-
filename = fileobj.name
100-
else:
98+
filename = getattr(fileobj, 'name', '')
99+
if not isinstance(filename, basestring) or filename == '<fdopen>':
101100
filename = ''
102101
if mode is None:
103102
if hasattr(fileobj, 'mode'): mode = fileobj.mode

Lib/test/test_gzip.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import os
77
import io
88
import struct
9+
import tempfile
910
gzip = test_support.import_module('gzip')
1011

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

335+
def test_fileobj_from_io_open(self):
336+
fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT)
337+
with io.open(fd, "wb") as f:
338+
with gzip.GzipFile(fileobj=f, mode="w") as g:
339+
self.assertEqual(g.name, "")
340+
334341
def test_fileobj_mode(self):
335342
gzip.GzipFile(self.filename, "wb").close()
336343
with open(self.filename, "r+b") as f:
@@ -359,6 +366,14 @@ def test_read_with_extra(self):
359366
with gzip.GzipFile(fileobj=io.BytesIO(gzdata)) as f:
360367
self.assertEqual(f.read(), b'Test')
361368

369+
def test_fileobj_without_name(self):
370+
# Issue #33038: GzipFile should not assume that file objects that have
371+
# a .name attribute use a non-None value.
372+
with tempfile.SpooledTemporaryFile() as f:
373+
with gzip.GzipFile(fileobj=f, mode='wb') as archive:
374+
archive.write(b'data')
375+
self.assertEqual(archive.name, '')
376+
362377
def test_main(verbose=None):
363378
test_support.run_unittest(TestGzip)
364379

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ Michael R Bax
9494
Anthony Baxter
9595
Mike Bayer
9696
Samuel L. Bayer
97+
Bo Bayles
9798
Donald Beaudry
9899
David Beazley
99100
Carlo Beccarini
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
gzip.GzipFile no longer produces an AttributeError exception when used with
2+
a file object with a non-string name attribute. Patch by Bo Bayles.

0 commit comments

Comments
 (0)