bpo-33038: Fix gzip.GzipFile for file objects with a non-string name attribute. (GH-6095)
diff --git a/Lib/gzip.py b/Lib/gzip.py
index 07c6db4..76ace39 100644
--- a/Lib/gzip.py
+++ b/Lib/gzip.py
@@ -95,9 +95,8 @@
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
diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py
index 902d93f..cdb1af5 100644
--- a/Lib/test/test_gzip.py
+++ b/Lib/test/test_gzip.py
@@ -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;
@@ -331,6 +332,12 @@
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:
@@ -359,6 +366,14 @@
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)