[3.12] gh-72795: Make positional arguments with nargs='*' or REMAINDER non-required (GH-124306) (GH-124422)

This allows to use positional argument with nargs='*' and without default
in mutually exclusive group and improves error message about required
arguments.
(cherry picked from commit 3c83f9958c)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
This commit is contained in:
Miss Islington (bot) 2024-09-24 10:43:26 +02:00 committed by GitHub
parent 0e838b52fe
commit 7e2d414a59
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 32 additions and 8 deletions

View file

@ -3033,7 +3033,7 @@ class TestMutuallyExclusiveOptionalAndPositional(MEMixin, TestCase):
group = parser.add_mutually_exclusive_group(required=required)
group.add_argument('--foo', action='store_true', help='FOO')
group.add_argument('--spam', help='SPAM')
group.add_argument('badger', nargs='*', default='X', help='BADGER')
group.add_argument('badger', nargs='*', help='BADGER')
return parser
failures = [
@ -3044,13 +3044,13 @@ class TestMutuallyExclusiveOptionalAndPositional(MEMixin, TestCase):
'--foo X Y',
]
successes = [
('--foo', NS(foo=True, spam=None, badger='X')),
('--spam S', NS(foo=False, spam='S', badger='X')),
('--foo', NS(foo=True, spam=None, badger=[])),
('--spam S', NS(foo=False, spam='S', badger=[])),
('X', NS(foo=False, spam=None, badger=['X'])),
('X Y Z', NS(foo=False, spam=None, badger=['X', 'Y', 'Z'])),
]
successes_when_not_required = [
('', NS(foo=False, spam=None, badger='X')),
('', NS(foo=False, spam=None, badger=[])),
]
usage_when_not_required = '''\
@ -6020,7 +6020,28 @@ class TestExitOnError(TestCase):
self.parser.add_argument('bar')
self.parser.add_argument('baz')
self.assertRaisesRegex(argparse.ArgumentError,
'the following arguments are required: bar, baz',
'the following arguments are required: bar, baz$',
self.parser.parse_args, [])
def test_required_args_optional(self):
self.parser.add_argument('bar')
self.parser.add_argument('baz', nargs='?')
self.assertRaisesRegex(argparse.ArgumentError,
'the following arguments are required: bar$',
self.parser.parse_args, [])
def test_required_args_zero_or_more(self):
self.parser.add_argument('bar')
self.parser.add_argument('baz', nargs='*')
self.assertRaisesRegex(argparse.ArgumentError,
'the following arguments are required: bar$',
self.parser.parse_args, [])
def test_required_args_remainder(self):
self.parser.add_argument('bar')
self.parser.add_argument('baz', nargs='...')
self.assertRaisesRegex(argparse.ArgumentError,
'the following arguments are required: bar$',
self.parser.parse_args, [])
def test_required_mutually_exclusive_args(self):