gh-139946: distinguish stdout or stderr when colorizing output in argparse (#140495)

Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
Co-authored-by: Savannah Ostrowski <savannah@python.org>
This commit is contained in:
Frost Ming 2025-12-08 12:08:06 +08:00 committed by GitHub
parent 3fa1425bfb
commit 7099af8f5e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 65 additions and 14 deletions

View file

@ -7558,6 +7558,40 @@ def test_error_and_warning_not_colorized_when_disabled(self):
self.assertNotIn('\x1b[', warn)
self.assertIn('warning:', warn)
def test_print_help_uses_target_file_for_color_decision(self):
parser = argparse.ArgumentParser(prog='PROG', color=True)
parser.add_argument('--opt')
output = io.StringIO()
calls = []
def fake_can_colorize(*, file=None):
calls.append(file)
return file is None
with swap_attr(_colorize, 'can_colorize', fake_can_colorize):
parser.print_help(file=output)
self.assertIs(calls[-1], output)
self.assertIn(output, calls)
self.assertNotIn('\x1b[', output.getvalue())
def test_print_usage_uses_target_file_for_color_decision(self):
parser = argparse.ArgumentParser(prog='PROG', color=True)
parser.add_argument('--opt')
output = io.StringIO()
calls = []
def fake_can_colorize(*, file=None):
calls.append(file)
return file is None
with swap_attr(_colorize, 'can_colorize', fake_can_colorize):
parser.print_usage(file=output)
self.assertIs(calls[-1], output)
self.assertIn(output, calls)
self.assertNotIn('\x1b[', output.getvalue())
class TestModule(unittest.TestCase):
def test_deprecated__version__(self):