Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Lib/tarfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -2083,7 +2083,7 @@ def zstopen(cls, name, mode="r", fileobj=None, level=None, options=None,
if mode == 'r':
raise ReadError("not a zstd file") from e
raise
except Exception:
except:
fileobj.close()
raise
t._extfileobj = False
Expand Down
15 changes: 15 additions & 0 deletions Lib/test/test_tarfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1065,6 +1065,21 @@ class LzmaDetectReadTest(LzmaTest, DetectReadTest):
class ZstdDetectReadTest(ZstdTest, DetectReadTest):
pass

@support.requires_zstd()
class ZstdOpenTest(unittest.TestCase):
"""
See: https://github.com/python/cpython/issues/150077
"""
def test_zstopen_closes_fileobj_on_base_exception(self):
fileobj = unittest.mock.Mock()
with unittest.mock.patch("compression.zstd.ZstdFile",
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest not to use a mock and check if a real file is closed or not.

return_value=fileobj), \
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return_value=fileobj), \
return_value=fileobj),

You can use with ( instead of \

unittest.mock.patch.object(tarfile.TarFile, "taropen",
side_effect=KeyboardInterrupt):
with self.assertRaises(KeyboardInterrupt):
tarfile.TarFile.zstopen("foo.tar.zst")
fileobj.close.assert_called_once()

class GzipBrokenHeaderCorrectException(GzipTest, unittest.TestCase):
"""
See: https://github.com/python/cpython/issues/107396
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix ``tarfile.TarFile.zstopen`` to close the underlying zstd file object
when opening the tar archive is interrupted by a :exc:`BaseException`
subclass such as :exc:`KeyboardInterrupt`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

Loading