Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-117225: Add color to doctest output #117583

Merged
merged 27 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
2c1108b
Add colour to doctest output and create _colorize module
hugovk Apr 6, 2024
d27c0a8
Use _colorize in traceback module
hugovk Apr 6, 2024
bb591b6
Fix whitespace
hugovk Apr 6, 2024
42079be
Use f-strings
hugovk Apr 6, 2024
0088579
Remove underscores from members of an underscored module
hugovk Apr 6, 2024
d3034fa
Add blurb
hugovk Apr 6, 2024
39780cb
Remove underscores from members of an underscored module
hugovk Apr 6, 2024
c5aec15
Revert "Fix whitespace"
hugovk Apr 6, 2024
7e40133
Move _colorize to stdlib block, colour->color
hugovk Apr 6, 2024
e484465
Move imports together
hugovk Apr 6, 2024
1c7b025
Move imports together
hugovk Apr 6, 2024
ab2c94c
Move imports together
hugovk Apr 6, 2024
1aaeab8
Revert notests -> no_tests
hugovk Apr 6, 2024
cd02e4a
Revert "Use f-strings"
hugovk Apr 6, 2024
06543ff
Fix local tests
hugovk Apr 6, 2024
31c6647
Use red divider for failed test
hugovk Apr 7, 2024
9be3d81
Fix local tests
hugovk Apr 7, 2024
e4ff3e3
Less red
hugovk Apr 7, 2024
b62500a
Revert unnecessary changes
hugovk Apr 7, 2024
eb4f8dc
Move colour tests to test__colorize.py
hugovk Apr 7, 2024
976bfb4
Refactor asserts
hugovk Apr 7, 2024
ad7a946
Add missing captured_output to test.support's __all__ to fix IDE warning
hugovk Apr 7, 2024
796e9f2
Only move test_colorized_detection_checks_for_environment_variables f…
hugovk Apr 7, 2024
99d4d0c
Apply suggestions from code review
hugovk Apr 7, 2024
95b9831
Use unittest's enterContext
hugovk Apr 7, 2024
d5417b4
Merge remote-tracking branch 'upstream/main' into doctest-tidy-output…
hugovk Apr 16, 2024
ece3ce0
Keep colorize functionality in traceback module for now
hugovk Apr 17, 2024
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
49 changes: 38 additions & 11 deletions Lib/doctest.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ def _test():
import unittest
from io import StringIO, IncrementalNewlineDecoder
from collections import namedtuple
from traceback import _ANSIColors, _can_colorize


class TestResults(namedtuple('TestResults', 'failed attempted')):
Expand Down Expand Up @@ -1179,6 +1180,9 @@ class DocTestRunner:
The `run` method is used to process a single DocTest case. It
returns a TestResults instance.

>>> save_colorize = traceback._COLORIZE
>>> traceback._COLORIZE = False

>>> tests = DocTestFinder().find(_TestClass)
>>> runner = DocTestRunner(verbose=False)
>>> tests.sort(key = lambda test: test.name)
Expand Down Expand Up @@ -1229,6 +1233,8 @@ class DocTestRunner:
can be also customized by subclassing DocTestRunner, and
overriding the methods `report_start`, `report_success`,
`report_unexpected_exception`, and `report_failure`.

>>> traceback._COLORIZE = save_colorize
"""
# This divider string is used to separate failure messages, and to
# separate sections of the summary.
Expand Down Expand Up @@ -1307,7 +1313,10 @@ def report_unexpected_exception(self, out, test, example, exc_info):
'Exception raised:\n' + _indent(_exception_traceback(exc_info)))

def _failure_header(self, test, example):
out = [self.DIVIDER]
red, reset = (
(_ANSIColors.RED, _ANSIColors.RESET) if _can_colorize() else ("", "")
)
out = [f"{red}{self.DIVIDER}{reset}"]
if test.filename:
if test.lineno is not None and example.lineno is not None:
lineno = test.lineno + example.lineno + 1
Expand Down Expand Up @@ -1592,6 +1601,21 @@ def summarize(self, verbose=None):
else:
failed.append((name, (failures, tries, skips)))

if _can_colorize():
bold_green = _ANSIColors.BOLD_GREEN
bold_red = _ANSIColors.BOLD_RED
green = _ANSIColors.GREEN
red = _ANSIColors.RED
reset = _ANSIColors.RESET
yellow = _ANSIColors.YELLOW
else:
bold_green = ""
bold_red = ""
green = ""
red = ""
reset = ""
yellow = ""

if verbose:
if notests:
print(f"{_n_items(notests)} had no tests:")
Expand All @@ -1600,13 +1624,13 @@ def summarize(self, verbose=None):
print(f" {name}")

if passed:
print(f"{_n_items(passed)} passed all tests:")
print(f"{green}{_n_items(passed)} passed all tests:{reset}")
for name, count in sorted(passed):
s = "" if count == 1 else "s"
print(f" {count:3d} test{s} in {name}")
print(f" {green}{count:3d} test{s} in {name}{reset}")

if failed:
print(self.DIVIDER)
print(f"{red}{self.DIVIDER}{reset}")
print(f"{_n_items(failed)} had failures:")
for name, (failures, tries, skips) in sorted(failed):
print(f" {failures:3d} of {tries:3d} in {name}")
Expand All @@ -1615,18 +1639,21 @@ def summarize(self, verbose=None):
s = "" if total_tries == 1 else "s"
print(f"{total_tries} test{s} in {_n_items(self._stats)}.")

and_f = f" and {total_failures} failed" if total_failures else ""
print(f"{total_tries - total_failures} passed{and_f}.")
and_f = (
f" and {red}{total_failures} failed{reset}"
if total_failures else ""
)
print(f"{green}{total_tries - total_failures} passed{reset}{and_f}.")

if total_failures:
s = "" if total_failures == 1 else "s"
msg = f"***Test Failed*** {total_failures} failure{s}"
msg = f"{bold_red}***Test Failed*** {total_failures} failure{s}{reset}"
if total_skips:
s = "" if total_skips == 1 else "s"
msg = f"{msg} and {total_skips} skipped test{s}"
msg = f"{msg} and {yellow}{total_skips} skipped test{s}{reset}"
print(f"{msg}.")
elif verbose:
print("Test passed.")
print(f"{bold_green}Test passed.{reset}")

return TestResults(total_failures, total_tries, skipped=total_skips)

Expand All @@ -1644,7 +1671,7 @@ def merge(self, other):
d[name] = (failures, tries, skips)


def _n_items(items: list) -> str:
def _n_items(items: list | dict) -> str:
"""
Helper to pluralise the number of items in a list.
"""
Expand All @@ -1655,7 +1682,7 @@ def _n_items(items: list) -> str:

class OutputChecker:
"""
A class used to check the whether the actual output from a doctest
A class used to check whether the actual output from a doctest
example matches the expected output. `OutputChecker` defines two
methods: `check_output`, which compares a given pair of outputs,
and returns true if they match; and `output_difference`, which
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/support/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"Error", "TestFailed", "TestDidNotRun", "ResourceDenied",
# io
"record_original_stdout", "get_original_stdout", "captured_stdout",
"captured_stdin", "captured_stderr",
"captured_stdin", "captured_stderr", "captured_output",
# unittest
"is_resource_enabled", "requires", "requires_freebsd_version",
"requires_gil_enabled", "requires_linux_version", "requires_mac_ver",
Expand Down
51 changes: 48 additions & 3 deletions Lib/test/test_doctest/test_doctest.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import tempfile
import types
import contextlib
import traceback


def doctest_skip_if(condition):
Expand Down Expand Up @@ -470,7 +471,7 @@ def basics(): r"""
>>> tests = finder.find(sample_func)

>>> print(tests) # doctest: +ELLIPSIS
[<DocTest sample_func from test_doctest.py:37 (1 example)>]
[<DocTest sample_func from test_doctest.py:38 (1 example)>]

The exact name depends on how test_doctest was invoked, so allow for
leading path components.
Expand Down Expand Up @@ -892,6 +893,9 @@ def basics(): r"""
DocTestRunner is used to run DocTest test cases, and to accumulate
statistics. Here's a simple DocTest case we can use:

>>> save_colorize = traceback._COLORIZE
>>> traceback._COLORIZE = False

>>> def f(x):
... '''
... >>> x = 12
Expand Down Expand Up @@ -946,6 +950,8 @@ def basics(): r"""
6
ok
TestResults(failed=1, attempted=3)

>>> traceback._COLORIZE = save_colorize
"""
def verbose_flag(): r"""
The `verbose` flag makes the test runner generate more detailed
Expand Down Expand Up @@ -1021,6 +1027,9 @@ def exceptions(): r"""
lines between the first line and the type/value may be omitted or
replaced with any other string:

>>> save_colorize = traceback._COLORIZE
>>> traceback._COLORIZE = False

>>> def f(x):
... '''
... >>> x = 12
Expand Down Expand Up @@ -1251,6 +1260,8 @@ def exceptions(): r"""
...
ZeroDivisionError: integer division or modulo by zero
TestResults(failed=1, attempted=1)

>>> traceback._COLORIZE = save_colorize
"""
def displayhook(): r"""
Test that changing sys.displayhook doesn't matter for doctest.
Expand Down Expand Up @@ -1292,6 +1303,9 @@ def optionflags(): r"""
The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
and 1/0:

>>> save_colorize = traceback._COLORIZE
>>> traceback._COLORIZE = False

>>> def f(x):
... '>>> True\n1\n'

Expand Down Expand Up @@ -1711,6 +1725,7 @@ def optionflags(): r"""

Clean up.
>>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
>>> traceback._COLORIZE = save_colorize

"""

Expand All @@ -1721,6 +1736,9 @@ def option_directives(): r"""
single example. To turn an option on for an example, follow that
example with a comment of the form ``# doctest: +OPTION``:

>>> save_colorize = traceback._COLORIZE
>>> traceback._COLORIZE = False

>>> def f(x): r'''
... >>> print(list(range(10))) # should fail: no ellipsis
... [0, 1, ..., 9]
Expand Down Expand Up @@ -1928,6 +1946,8 @@ def option_directives(): r"""
>>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
Traceback (most recent call last):
ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'

>>> traceback._COLORIZE = save_colorize
"""

def test_testsource(): r"""
Expand Down Expand Up @@ -2011,6 +2031,9 @@ def test_pdb_set_trace():
with a version that restores stdout. This is necessary for you to
see debugger output.

>>> save_colorize = traceback._COLORIZE
>>> traceback._COLORIZE = False

>>> doc = '''
... >>> x = 42
... >>> raise Exception('clé')
Expand Down Expand Up @@ -2065,7 +2088,7 @@ def test_pdb_set_trace():
... finally:
... sys.stdin = real_stdin
--Return--
> <doctest test.test_doctest.test_doctest.test_pdb_set_trace[7]>(3)calls_set_trace()->None
> <doctest test.test_doctest.test_doctest.test_pdb_set_trace[9]>(3)calls_set_trace()->None
-> import pdb; pdb.set_trace()
(Pdb) print(y)
2
Expand Down Expand Up @@ -2133,6 +2156,8 @@ def test_pdb_set_trace():
Got:
9
TestResults(failed=1, attempted=3)

>>> traceback._COLORIZE = save_colorize
"""

def test_pdb_set_trace_nested():
Expand Down Expand Up @@ -2652,7 +2677,10 @@ def test_testfile(): r"""
called with the name of a file, which is taken to be relative to the
calling module. The return value is (#failures, #tests).

We don't want `-v` in sys.argv for these tests.
We don't want color or `-v` in sys.argv for these tests.

>>> save_colorize = traceback._COLORIZE
>>> traceback._COLORIZE = False

>>> save_argv = sys.argv
>>> if '-v' in sys.argv:
Expand Down Expand Up @@ -2820,6 +2848,7 @@ def test_testfile(): r"""
TestResults(failed=0, attempted=2)
>>> doctest.master = None # Reset master.
>>> sys.argv = save_argv
>>> traceback._COLORIZE = save_colorize
"""

class TestImporter(importlib.abc.MetaPathFinder, importlib.abc.ResourceLoader):
Expand Down Expand Up @@ -2957,6 +2986,9 @@ def test_testmod(): r"""
def test_unicode(): """
Check doctest with a non-ascii filename:

>>> save_colorize = traceback._COLORIZE
>>> traceback._COLORIZE = False

>>> doc = '''
... >>> raise Exception('clé')
... '''
Expand All @@ -2982,8 +3014,11 @@ def test_unicode(): """
raise Exception('clé')
Exception: clé
TestResults(failed=1, attempted=1)

>>> traceback._COLORIZE = save_colorize
"""


@doctest_skip_if(not support.has_subprocess_support)
def test_CLI(): r"""
The doctest module can be used to run doctests against an arbitrary file.
Expand Down Expand Up @@ -3275,6 +3310,9 @@ def test_run_doctestsuite_multiple_times():

def test_exception_with_note(note):
"""
>>> save_colorize = traceback._COLORIZE
>>> traceback._COLORIZE = False

>>> test_exception_with_note('Note')
Traceback (most recent call last):
...
Expand Down Expand Up @@ -3324,6 +3362,8 @@ def test_exception_with_note(note):
ValueError: message
note
TestResults(failed=1, attempted=...)

>>> traceback._COLORIZE = save_colorize
"""
exc = ValueError('Text')
exc.add_note(note)
Expand Down Expand Up @@ -3404,6 +3444,9 @@ def test_syntax_error_subclass_from_stdlib():

def test_syntax_error_with_incorrect_expected_note():
"""
>>> save_colorize = traceback._COLORIZE
>>> traceback._COLORIZE = False

>>> def f(x):
... r'''
... >>> exc = SyntaxError("error", ("x.py", 23, None, "bad syntax"))
Expand Down Expand Up @@ -3432,6 +3475,8 @@ def test_syntax_error_with_incorrect_expected_note():
note1
note2
TestResults(failed=1, attempted=...)

>>> traceback._COLORIZE = save_colorize
"""


Expand Down
4 changes: 4 additions & 0 deletions Lib/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,8 +448,12 @@ class _ANSIColors:
BOLD_RED = '\x1b[1;31m'
MAGENTA = '\x1b[35m'
BOLD_MAGENTA = '\x1b[1;35m'
GREEN = "\x1b[32m"
BOLD_GREEN = "\x1b[1;32m"
Comment on lines +451 to +452
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, is there a reason why these colours might have been omitted from the original changes to colourise Python's tracebacks in general? Maybe to avoid accessibility issues for people who are red-green colourblind? Or to avoid issues for people who have light themes on their terminals?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think because when there's a traceback error there's nothing "good" to report in green :)

GREY = '\x1b[90m'
RESET = '\x1b[0m'
YELLOW = "\x1b[33m"


class StackSummary(list):
"""A list of FrameSummary objects, representing a stack of frames."""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add colour to doctest output. Patch by Hugo van Kemenade.
Loading