diff options
author | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2021-07-23 13:27:17 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-07-23 13:27:17 (GMT) |
commit | 097801844c99ea3916bebe1cc761257ea7083d34 (patch) | |
tree | 220d2d6684c910e18b027deeb523dbd1215876e3 /Lib | |
parent | 0f55d21212a0fb6dec4479eb76249ab2b54e57a3 (diff) | |
download | cpython-097801844c99ea3916bebe1cc761257ea7083d34.zip cpython-097801844c99ea3916bebe1cc761257ea7083d34.tar.gz cpython-097801844c99ea3916bebe1cc761257ea7083d34.tar.bz2 |
bpo-29298: Fix crash with required subparsers without dest (GH-3680) (GH-27304)
(cherry picked from commit 17575f73ce2cb9f3a4eb4cc416c690f9a4e7205c)
Co-authored-by: Anthony Sottile <asottile@umich.edu>
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/argparse.py | 2 | ||||
-rw-r--r-- | Lib/test/test_argparse.py | 24 |
2 files changed, 26 insertions, 0 deletions
diff --git a/Lib/argparse.py b/Lib/argparse.py index 2fb1da5..ccb010d 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -727,6 +727,8 @@ def _get_action_name(argument): return argument.metavar elif argument.dest not in (None, SUPPRESS): return argument.dest + elif argument.choices: + return '{' + ','.join(argument.choices) + '}' else: return None diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 22cae62..e168544 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -2057,6 +2057,30 @@ class TestAddSubparsers(TestCase): ret = parser.parse_args(()) self.assertIsNone(ret.command) + def test_required_subparsers_no_destination_error(self): + parser = ErrorRaisingArgumentParser() + subparsers = parser.add_subparsers(required=True) + subparsers.add_parser('foo') + subparsers.add_parser('bar') + with self.assertRaises(ArgumentParserError) as excinfo: + parser.parse_args(()) + self.assertRegex( + excinfo.exception.stderr, + 'error: the following arguments are required: {foo,bar}\n$' + ) + + def test_wrong_argument_subparsers_no_destination_error(self): + parser = ErrorRaisingArgumentParser() + subparsers = parser.add_subparsers(required=True) + subparsers.add_parser('foo') + subparsers.add_parser('bar') + with self.assertRaises(ArgumentParserError) as excinfo: + parser.parse_args(('baz',)) + self.assertRegex( + excinfo.exception.stderr, + r"error: argument {foo,bar}: invalid choice: 'baz' \(choose from 'foo', 'bar'\)\n$" + ) + def test_optional_subparsers(self): parser = ErrorRaisingArgumentParser() subparsers = parser.add_subparsers(dest='command', required=False) |