This commit is contained in:
Sergey B Kirpichev 2025-07-10 06:56:21 +03:00 committed by GitHub
commit b4da51f65d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 35 additions and 17 deletions

View file

@ -1620,6 +1620,10 @@ DocTestRunner objects
output checker, and the results are formatted by the
:meth:`!DocTestRunner.report_\*` methods.
.. versionchanged:: 3.13
Added support for testing examples with a customized
:func:`sys.displayhook` value. Previously, this wasn't allowed and
the method was always using the :func:`sys.__displayhook__`.
.. method:: summarize(verbose=None)

View file

@ -1562,9 +1562,8 @@ class DocTestRunner:
self.save_linecache_getlines = linecache.getlines
linecache.getlines = self.__patched_linecache_getlines
# Make sure sys.displayhook just prints the value to stdout
# Make sure sys.displayhook restored at the end
save_displayhook = sys.displayhook
sys.displayhook = sys.__displayhook__
saved_can_colorize = _colorize.can_colorize
_colorize.can_colorize = lambda *args, **kwargs: False
color_variables = {"PYTHON_COLORS": None, "FORCE_COLOR": None}

View file

@ -1264,33 +1264,46 @@ unexpected exception:
>>> _colorize.COLORIZE = save_colorize
"""
def displayhook(): r"""
Test that changing sys.displayhook doesn't matter for doctest.
Test changing sys.displayhook.
Run with a custom displayhook:
>>> import sys
>>> orig_displayhook = sys.displayhook
>>> def my_displayhook(x):
... print('hi!')
... sys.__displayhook__(x)
>>> sys.displayhook = my_displayhook
>>> 3
hi!
3
>>> def f():
... '''
... >>> 3
... hi!
... 3
... '''
>>> test = doctest.DocTestFinder().find(f)[0]
>>> r = doctest.DocTestRunner(verbose=False).run(test)
>>> post_displayhook = sys.displayhook
We need to restore sys.displayhook now, so that we'll be able to test
results.
>>> sys.displayhook = orig_displayhook
Ok, now we can check that everything is ok.
>>> r
>>> doctest.DocTestRunner(verbose=False).run(test)
hi!
TestResults(failed=0, attempted=1)
>>> post_displayhook is my_displayhook
True
>>> sys.displayhook = sys.__displayhook__
>>> 3
3
Test changing displayhook in the doctest:
>>> def g():
... '''
... >>> import sys
... >>> sys.displayhook = lambda x: print('spam')
... >>> 3
... spam
... '''
>>> test = doctest.DocTestFinder().find(g)[0]
>>> doctest.DocTestRunner(verbose=False).run(test)
TestResults(failed=0, attempted=3)
>>> 42
42
"""
def optionflags(): r"""
Tests of `DocTestRunner`'s option flag handling.

View file

@ -0,0 +1,2 @@
Allow using custom sys.displayhook's with doctest. Patch by Sergey B
Kirpichev.