]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-29298: Fix crash with required subparsers without dest (GH-3680) (GH-27304)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Fri, 23 Jul 2021 13:27:17 +0000 (06:27 -0700)
committerGitHub <noreply@github.com>
Fri, 23 Jul 2021 13:27:17 +0000 (15:27 +0200)
(cherry picked from commit 17575f73ce2cb9f3a4eb4cc416c690f9a4e7205c)

Co-authored-by: Anthony Sottile <asottile@umich.edu>
Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2017-09-20-14-43-03.bpo-29298._78CSN.rst [new file with mode: 0644]

index 2fb1da59f942cff7fbfc136ebd08ee8ec14bcbaa..ccb010d0d5cae536d6707600ec58efebbee62264 100644 (file)
@@ -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
 
index 22cae626ccc2973cf31ce76b72852d6f73a16e94..e1685443248ef224d6f2b3a08de056dd54f018c6 100644 (file)
@@ -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)
diff --git a/Misc/NEWS.d/next/Library/2017-09-20-14-43-03.bpo-29298._78CSN.rst b/Misc/NEWS.d/next/Library/2017-09-20-14-43-03.bpo-29298._78CSN.rst
new file mode 100644 (file)
index 0000000..e84c6de
--- /dev/null
@@ -0,0 +1,2 @@
+Fix ``TypeError`` when required subparsers without ``dest`` do not receive
+arguments. Patch by Anthony Sottile.