Issue #20243: TarFile no longer raise ReadError when opened in write mode.
This commit is contained in:
parent
9fbec7ad5e
commit
c2d01423e0
|
@ -1628,19 +1628,22 @@ class TarFile(object):
|
|||
except (ImportError, AttributeError):
|
||||
raise CompressionError("gzip module is not available")
|
||||
|
||||
extfileobj = fileobj is not None
|
||||
try:
|
||||
fileobj = gzip.GzipFile(name, mode + "b", compresslevel, fileobj)
|
||||
except OSError:
|
||||
if fileobj is not None and mode == 'r':
|
||||
raise ReadError("not a gzip file")
|
||||
raise
|
||||
|
||||
try:
|
||||
t = cls.taropen(name, mode, fileobj, **kwargs)
|
||||
except IOError:
|
||||
if not extfileobj and fileobj is not None:
|
||||
fileobj.close()
|
||||
if fileobj is None:
|
||||
raise
|
||||
raise ReadError("not a gzip file")
|
||||
except OSError:
|
||||
fileobj.close()
|
||||
if mode == 'r':
|
||||
raise ReadError("not a gzip file")
|
||||
raise
|
||||
except:
|
||||
if not extfileobj and fileobj is not None:
|
||||
fileobj.close()
|
||||
fileobj.close()
|
||||
raise
|
||||
t._extfileobj = False
|
||||
return t
|
||||
|
@ -1665,7 +1668,9 @@ class TarFile(object):
|
|||
t = cls.taropen(name, mode, fileobj, **kwargs)
|
||||
except (IOError, EOFError):
|
||||
fileobj.close()
|
||||
raise ReadError("not a bzip2 file")
|
||||
if mode == 'r':
|
||||
raise ReadError("not a bzip2 file")
|
||||
raise
|
||||
t._extfileobj = False
|
||||
return t
|
||||
|
||||
|
@ -1688,7 +1693,9 @@ class TarFile(object):
|
|||
t = cls.taropen(name, mode, fileobj, **kwargs)
|
||||
except (lzma.LZMAError, EOFError):
|
||||
fileobj.close()
|
||||
raise ReadError("not an lzma file")
|
||||
if mode == 'r':
|
||||
raise ReadError("not an lzma file")
|
||||
raise
|
||||
t._extfileobj = False
|
||||
return t
|
||||
|
||||
|
|
|
@ -1155,6 +1155,22 @@ class WriteTest(WriteTestBase, unittest.TestCase):
|
|||
finally:
|
||||
os.chdir(cwd)
|
||||
|
||||
def test_open_nonwritable_fileobj(self):
|
||||
for exctype in OSError, EOFError, RuntimeError:
|
||||
class BadFile(io.BytesIO):
|
||||
first = True
|
||||
def write(self, data):
|
||||
if self.first:
|
||||
self.first = False
|
||||
raise exctype
|
||||
|
||||
f = BadFile()
|
||||
with self.assertRaises(exctype):
|
||||
tar = tarfile.open(tmpname, self.mode, fileobj=f,
|
||||
format=tarfile.PAX_FORMAT,
|
||||
pax_headers={'non': 'empty'})
|
||||
self.assertFalse(f.closed)
|
||||
|
||||
class GzipWriteTest(GzipTest, WriteTest):
|
||||
pass
|
||||
|
||||
|
|
Loading…
Reference in New Issue