GH-139946: Colorize error and warning messages in argparse (#140695)

Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
This commit is contained in:
Savannah Ostrowski 2025-11-04 08:31:35 -08:00 committed by GitHub
parent 1326d2a808
commit 40096da95a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 73 additions and 5 deletions

View file

@ -2283,6 +2283,7 @@ class TestNegativeNumber(ParserTestCase):
('--complex -1e-3j', NS(int=None, float=None, complex=-0.001j)),
]
@force_not_colorized_test_class
class TestArgumentAndSubparserSuggestions(TestCase):
"""Test error handling and suggestion when a user makes a typo"""
@ -6147,6 +6148,7 @@ def spam(string_to_convert):
# Check that deprecated arguments output warning
# ==============================================
@force_not_colorized_test_class
class TestDeprecatedArguments(TestCase):
def test_deprecated_option(self):
@ -7370,6 +7372,45 @@ def test_subparser_prog_is_stored_without_color(self):
help_text = demo_parser.format_help()
self.assertNotIn('\x1b[', help_text)
def test_error_and_warning_keywords_colorized(self):
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('foo')
with self.assertRaises(SystemExit):
with captured_stderr() as stderr:
parser.parse_args([])
err = stderr.getvalue()
error_color = self.theme.error
reset = self.theme.reset
self.assertIn(f'{error_color}error:{reset}', err)
with captured_stderr() as stderr:
parser._warning('test warning')
warn = stderr.getvalue()
warning_color = self.theme.warning
self.assertIn(f'{warning_color}warning:{reset}', warn)
def test_error_and_warning_not_colorized_when_disabled(self):
parser = argparse.ArgumentParser(prog='PROG', color=False)
parser.add_argument('foo')
with self.assertRaises(SystemExit):
with captured_stderr() as stderr:
parser.parse_args([])
err = stderr.getvalue()
self.assertNotIn('\x1b[', err)
self.assertIn('error:', err)
with captured_stderr() as stderr:
parser._warning('test warning')
warn = stderr.getvalue()
self.assertNotIn('\x1b[', warn)
self.assertIn('warning:', warn)
class TestModule(unittest.TestCase):
def test_deprecated__version__(self):