From 38520218b0b44bb82a69b81c3e9bc91d50b5fb66 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Fri, 30 Aug 2019 14:46:42 -0700 Subject: [PATCH] [3.8] bpo-29553: Fix ArgumentParser.format_usage() for mutually exclusive groups (GH-14976) (GH-15494) --- Lib/argparse.py | 10 ++++++++-- Lib/test/test_argparse.py | 40 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/Lib/argparse.py b/Lib/argparse.py index a6ab3b3b898d4b..456ec8bb7fc86a 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -405,13 +405,19 @@ def _format_actions_usage(self, actions, groups): inserts[start] += ' [' else: inserts[start] = '[' - inserts[end] = ']' + if end in inserts: + inserts[end] += ']' + else: + inserts[end] = ']' else: if start in inserts: inserts[start] += ' (' else: inserts[start] = '(' - inserts[end] = ')' + if end in inserts: + inserts[end] += ')' + else: + inserts[end] = ')' for i in range(start + 1, end): inserts[i] = '|' diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index d6d16090eb0260..86ec6cca51acc4 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -2813,6 +2813,46 @@ def get_parser(self, required): -c c help ''' +class TestMutuallyExclusiveNested(MEMixin, TestCase): + + def get_parser(self, required): + parser = ErrorRaisingArgumentParser(prog='PROG') + group = parser.add_mutually_exclusive_group(required=required) + group.add_argument('-a') + group.add_argument('-b') + group2 = group.add_mutually_exclusive_group(required=required) + group2.add_argument('-c') + group2.add_argument('-d') + group3 = group2.add_mutually_exclusive_group(required=required) + group3.add_argument('-e') + group3.add_argument('-f') + return parser + + usage_when_not_required = '''\ + usage: PROG [-h] [-a A | -b B | [-c C | -d D | [-e E | -f F]]] + ''' + usage_when_required = '''\ + usage: PROG [-h] (-a A | -b B | (-c C | -d D | (-e E | -f F))) + ''' + + help = '''\ + + optional arguments: + -h, --help show this help message and exit + -a A + -b B + -c C + -d D + -e E + -f F + ''' + + # We are only interested in testing the behavior of format_usage(). + test_failures_when_not_required = None + test_failures_when_required = None + test_successes_when_not_required = None + test_successes_when_required = None + # ================================================= # Mutually exclusive group in parent parser tests # =================================================