8000 bpo-8978: improve tarfile.open error message when lzma / bz2 are miss… · python/cpython@9aea31d · GitHub
[go: up one dir, main page]

Skip to content

Commit 9aea31d

Browse files
authored
bpo-8978: improve tarfile.open error message when lzma / bz2 are missing (GH-24850)
Automerge-Triggered-By: GH:pablogsal
1 parent 8a37463 commit 9aea31d

File tree

4 files changed

+19
-2
lines changed

4 files changed

+19
-2
lines changed

Lib/tarfile.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1604,17 +1604,20 @@ def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs):
16041604
# Find out which *open() is appropriate for opening the file.
16051605
def not_compressed(comptype):
16061606
return cls.OPEN_METH[comptype] == 'taropen'
1607+
error_msgs = []
16071608
for comptype in sorted(cls.OPEN_METH, key=not_compressed):
16081609
func = getattr(cls, cls.OPEN_METH[comptype])
16091610
if fileobj is not None:
16101611
saved_pos = fileobj.tell()
16111612
try:
16121613
return func(name, "r", fileobj, **kwargs)
1613-
except (ReadError, CompressionError):
1614+
except (ReadError, CompressionError) as e:
1615+
error_msgs.append(f'- method {comptype}: {e!r}')
16141616
if fileobj is not None:
16151617
fileobj.seek(saved_pos)
16161618
continue
1617-
raise ReadError("file could not be opened successfully")
1619+
error_msgs_summary = '\n'.join(error_msgs)
1620+
raise ReadError(f"file could not be opened successfully:\n{error_msgs_summary}")
16181621

16191622
elif ":" in mode:
16201623
filemode, comptype = mode.split(":", 1)

Lib/test/test_tarfile.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2283,6 +2283,18 @@ def test__all__(self):
22832283
'SubsequentHeaderError', 'ExFileObject', 'main'}
22842284
support.check__all__(self, tarfile, not_exported=not_exported)
22852285

2286+
def test_useful_error_message_when_modules_missing(self):
2287+
fname = os.path.join(os.path.dirname(__file__), 'testtar.tar.xz')
2288+
with self.assertRaises(tarfile.ReadError) as excinfo:
2289+
error = tarfile.CompressionError('lzma module is not available'),
2290+
with unittest.mock.patch.object(tarfile.TarFile, 'xzopen', side_effect=error):
2291+
tarfile.open(fname)
2292+
2293+
self.assertIn(
2294+
"\n- method xz: CompressionError('lzma module is not available')\n",
2295+
str(excinfo.exception),
2296+
)
2297+
22862298

22872299
class CommandLineTest(unittest.TestCase):
22882300

Lib/test/testtar.tar.xz

172 Bytes
Binary file not shown.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve error message for :func:`tarfile.open` when :mod:`lzma` / :mod:`bz2`
2+
are unavailable. Patch by Anthony Sottile.

0 commit comments

Comments
 (0)
0