gh-74185: repr() of ImportError now contains attributes name and path (#136770)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
Co-authored-by: Oleg Iarygin <oleg@arhadthedev.net>
Co-authored-by: ynir3 <ynir3@bloomberg.net>
This commit is contained in:
Yoav Nir 2025-08-14 14:14:00 +01:00 committed by GitHub
parent c47ffbf1a3
commit c87b66bc7c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 128 additions and 6 deletions

View file

@ -2079,6 +2079,50 @@ def test_copy_pickle(self):
self.assertEqual(exc.name, orig.name)
self.assertEqual(exc.path, orig.path)
def test_repr(self):
exc = ImportError()
self.assertEqual(repr(exc), "ImportError()")
exc = ImportError('test')
self.assertEqual(repr(exc), "ImportError('test')")
exc = ImportError('test', 'case')
self.assertEqual(repr(exc), "ImportError('test', 'case')")
exc = ImportError(name='somemodule')
self.assertEqual(repr(exc), "ImportError(name='somemodule')")
exc = ImportError('test', name='somemodule')
self.assertEqual(repr(exc), "ImportError('test', name='somemodule')")
exc = ImportError(path='somepath')
self.assertEqual(repr(exc), "ImportError(path='somepath')")
exc = ImportError('test', path='somepath')
self.assertEqual(repr(exc), "ImportError('test', path='somepath')")
exc = ImportError(name='somename', path='somepath')
self.assertEqual(repr(exc),
"ImportError(name='somename', path='somepath')")
exc = ImportError('test', name='somename', path='somepath')
self.assertEqual(repr(exc),
"ImportError('test', name='somename', path='somepath')")
exc = ModuleNotFoundError('test', name='somename', path='somepath')
self.assertEqual(repr(exc),
"ModuleNotFoundError('test', name='somename', path='somepath')")
def test_ModuleNotFoundError_repr_with_failed_import(self):
with self.assertRaises(ModuleNotFoundError) as cm:
import does_not_exist # type: ignore[import] # noqa: F401
self.assertEqual(cm.exception.name, "does_not_exist")
self.assertIsNone(cm.exception.path)
self.assertEqual(repr(cm.exception),
"ModuleNotFoundError(\"No module named 'does_not_exist'\", name='does_not_exist')")
def run_script(source):
if isinstance(source, str):