Skip to content

Commit 1e3e343

Browse files
Add fix to decolorize and test
1 parent e7e3d1d commit 1e3e343

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

Lib/argparse.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1963,7 +1963,7 @@ def add_subparsers(self, **kwargs):
19631963
positionals = self._get_positional_actions()
19641964
groups = self._mutually_exclusive_groups
19651965
formatter.add_usage(None, positionals, groups, '')
1966-
kwargs['prog'] = formatter.format_help().strip()
1966+
kwargs['prog'] = formatter._decolor(formatter.format_help().strip())
19671967

19681968
# create the parsers action and add it to the positionals list
19691969
parsers_class = self._pop_action_class(kwargs, 'parsers')

Lib/test/test_argparse.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from unittest import mock
3131

3232

33+
3334
py = os.path.basename(sys.executable)
3435

3536

@@ -7356,6 +7357,28 @@ def __init__(self, prog):
73567357
'''))
73577358

73587359

7360+
class TestColorEnvironment(TestCase):
7361+
"""Tests for color behavior with environment variable changes."""
7362+
7363+
def test_subparser_respects_no_color_environment(self):
7364+
# Cleanup to ensure environment is properly reset
7365+
self.addCleanup(os.environ.pop, 'FORCE_COLOR', None)
7366+
self.addCleanup(os.environ.pop, 'NO_COLOR', None)
7367+
7368+
# Create parser with FORCE_COLOR, capturing colored prog
7369+
os.environ['FORCE_COLOR'] = '1'
7370+
parser = argparse.ArgumentParser(prog='complex')
7371+
sub = parser.add_subparsers(dest='command')
7372+
demo_parser = sub.add_parser('demo')
7373+
7374+
# Switch to NO_COLOR environment
7375+
os.environ.pop('FORCE_COLOR', None)
7376+
os.environ['NO_COLOR'] = '1'
7377+
7378+
# Subparser help should have no color codes
7379+
help_text = demo_parser.format_help()
7380+
self.assertNotIn('\x1b[', help_text)
7381+
73597382
class TestModule(unittest.TestCase):
73607383
def test_deprecated__version__(self):
73617384
with self.assertWarnsRegex(

0 commit comments

Comments
 (0)