diff --git a/Lib/doctest.py b/Lib/doctest.py index e02e73ed722f7e..091d554c224769 100644 --- a/Lib/doctest.py +++ b/Lib/doctest.py @@ -1034,6 +1034,15 @@ def _find(self, tests, obj, name, module, source_lines, globs, seen): for valname, val in obj.__dict__.items(): valname = '%s.%s' % (name, valname) + try: + inspect.unwrap(val) + except ValueError: + # Do not catch the ValueError raised when a cycle is encountered. + pass + except Exception as exc: + raise ValueError("DocTestFinder.find: __wrapped__ threw %r: %r" + % (exc, type(val))) from None + # Recurse to functions & classes. if ((self._is_routine(val) or inspect.isclass(val)) and self._from_module(module, val)): diff --git a/Lib/test/test_doctest/test_doctest.py b/Lib/test/test_doctest/test_doctest.py index a4a49298bab3be..94f3fd580a72c3 100644 --- a/Lib/test/test_doctest/test_doctest.py +++ b/Lib/test/test_doctest/test_doctest.py @@ -3498,6 +3498,29 @@ def test_syntax_error_with_incorrect_expected_note(): """ +def test_unable_to_check_for_wrapped_attr(): + """ + Before gh-70186, DocTestFinder.find() failed when inspect.unwrap() + raised anything else but AttributeError while checking if a given + object had the __wrapped__ attribute. + + >>> # An unwrapable class + >>> class UnwrapMeAndDie: + ... def __getattr__(self, name): + ... raise RuntimeError('boom') + + >>> # A module using this class + >>> import types + >>> m = types.ModuleType('some_module') + >>> m.__dict__.update({'unwrap_me_not': UnwrapMeAndDie()}) + >>> # DocTestFinder.find() should fail with a specific ValueError, nothing else + >>> finder = doctest.DocTestFinder() + >>> finder.find(m) # doctest: +ELLIPSIS + Traceback (most recent call last): + ValueError: DocTestFinder.find: __wrapped__ threw RuntimeError('boom'): ... + """ + + def load_tests(loader, tests, pattern): tests.addTest(doctest.DocTestSuite(doctest)) tests.addTest(doctest.DocTestSuite()) diff --git a/Misc/NEWS.d/next/Tests/2024-11-29-10-24-16.gh-issue-70186.d_L_gd.rst b/Misc/NEWS.d/next/Tests/2024-11-29-10-24-16.gh-issue-70186.d_L_gd.rst new file mode 100644 index 00000000000000..887cb7e3ec4772 --- /dev/null +++ b/Misc/NEWS.d/next/Tests/2024-11-29-10-24-16.gh-issue-70186.d_L_gd.rst @@ -0,0 +1 @@ +Fix doctest badly handling unwrapable objects. Patch by Mickaƫl Schoentgen.