Skip to content

Commit c8f71c5

Browse files
committed
fix tarfile: zstopen uses except Exception
1 parent ba0aca3 commit c8f71c5

3 files changed

Lines changed: 18 additions & 1 deletion

File tree

Lib/tarfile.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2083,7 +2083,7 @@ def zstopen(cls, name, mode="r", fileobj=None, level=None, options=None,
20832083
if mode == 'r':
20842084
raise ReadError("not a zstd file") from e
20852085
raise
2086-
except Exception:
2086+
except:
20872087
fileobj.close()
20882088
raise
20892089
t._extfileobj = False

Lib/test/test_tarfile.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1065,6 +1065,21 @@ class LzmaDetectReadTest(LzmaTest, DetectReadTest):
10651065
class ZstdDetectReadTest(ZstdTest, DetectReadTest):
10661066
pass
10671067

1068+
@support.requires_zstd()
1069+
class ZstdOpenTest(unittest.TestCase):
1070+
"""
1071+
See: https://github.com/python/cpython/issues/150077
1072+
"""
1073+
def test_zstopen_closes_fileobj_on_base_exception(self):
1074+
fileobj = unittest.mock.Mock()
1075+
with unittest.mock.patch("compression.zstd.ZstdFile",
1076+
return_value=fileobj), \
1077+
unittest.mock.patch.object(tarfile.TarFile, "taropen",
1078+
side_effect=KeyboardInterrupt):
1079+
with self.assertRaises(KeyboardInterrupt):
1080+
tarfile.TarFile.zstopen("foo.tar.zst")
1081+
fileobj.close.assert_called_once()
1082+
10681083
class GzipBrokenHeaderCorrectException(GzipTest, unittest.TestCase):
10691084
"""
10701085
See: https://github.com/python/cpython/issues/107396
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :meth:`tarfile.TarFile.zstopen` to close the zstd file object when
2+
opening the tar archive fails with a :exc:`BaseException`.

0 commit comments

Comments
 (0)