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
8 changes: 4 additions & 4 deletions Lib/tarfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -2951,12 +2951,12 @@ def next(self):
except Exception as e:
try:
import zlib
except ImportError:
pass
else:
if isinstance(e, zlib.error):
raise ReadError(f'zlib error: {e}') from None
else:
raise e
except ImportError:
raise e
raise
break

if tarinfo is not None:
Expand Down
27 changes: 27 additions & 0 deletions Lib/test/test_tarfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,33 @@ def test_zlib_error_does_not_leak(self):
with self.assertRaises(tarfile.ReadError):
tarfile.open(self.tarname)

def test_next_preserves_exception_traceback(self):
class FailingFile(io.BytesIO):
def read(self, *args):
raise error

for error_type in (OSError, ImportError):
for missing_zlib in (False, True):
with self.subTest(error_type=error_type,
missing_zlib=missing_zlib):
error = error_type("read failed")
modules = {"zlib": None} if missing_zlib else {}
with unittest.mock.patch.dict(sys.modules, modules):
try:
tarfile.open(fileobj=FailingFile(), mode="r:")
except error_type as exc:
self.assertIs(exc, error)
next_frames = 0
tb = exc.__traceback__
while tb is not None:
code = tb.tb_frame.f_code
if code is tarfile.TarFile.next.__code__:
next_frames += 1
tb = tb.tb_next
self.assertEqual(next_frames, 1)
else:
self.fail(f"{error_type.__name__} not raised")

def test_next_on_empty_tarfile(self):
fd = io.BytesIO()
tf = tarfile.open(fileobj=fd, mode="w")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Preserve the original traceback when :meth:`tarfile.TarFile.next`
reraises an exception.
Loading