blob: ec49b2acbbb8523ffef0486793445c44e891b753 [file] [log] [blame]
Steven Bethardcd4ec0e2010-03-24 23:07:31 +00001# Author: Steven J. Bethard <steven.bethard@gmail.com>.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002
Steven Bethard72c55382010-11-01 15:23:12 +00003import inspect
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004import os
5import shutil
Steven Bethardb0270112011-01-24 21:02:50 +00006import stat
Benjamin Peterson698a18a2010-03-02 22:34:37 +00007import sys
8import textwrap
9import tempfile
10import unittest
Benjamin Peterson698a18a2010-03-02 22:34:37 +000011import argparse
12
Benjamin Peterson16f2fd02010-03-02 23:09:38 +000013from io import StringIO
14
Hai Shi46605972020-08-04 00:49:18 +080015from test.support import os_helper
Petri Lehtinen74d6c252012-12-15 22:39:32 +020016from unittest import mock
Benjamin Petersonb48af542010-04-11 20:43:16 +000017class StdIOBuffer(StringIO):
18 pass
Benjamin Peterson698a18a2010-03-02 22:34:37 +000019
Benjamin Peterson698a18a2010-03-02 22:34:37 +000020class TestCase(unittest.TestCase):
21
Steven Bethard1f1c2472010-11-01 13:56:09 +000022 def setUp(self):
23 # The tests assume that line wrapping occurs at 80 columns, but this
24 # behaviour can be overridden by setting the COLUMNS environment
Berker Peksag74102c92018-07-25 18:23:44 +030025 # variable. To ensure that this width is used, set COLUMNS to 80.
Hai Shi46605972020-08-04 00:49:18 +080026 env = os_helper.EnvironmentVarGuard()
Berker Peksag74102c92018-07-25 18:23:44 +030027 env['COLUMNS'] = '80'
Steven Bethard1f1c2472010-11-01 13:56:09 +000028 self.addCleanup(env.__exit__)
Benjamin Peterson698a18a2010-03-02 22:34:37 +000029
Benjamin Petersonb48af542010-04-11 20:43:16 +000030
Benjamin Peterson698a18a2010-03-02 22:34:37 +000031class TempDirMixin(object):
32
33 def setUp(self):
34 self.temp_dir = tempfile.mkdtemp()
35 self.old_dir = os.getcwd()
36 os.chdir(self.temp_dir)
37
38 def tearDown(self):
39 os.chdir(self.old_dir)
Benjamin Peterson511e2222014-04-04 13:55:56 -040040 for root, dirs, files in os.walk(self.temp_dir, topdown=False):
41 for name in files:
42 os.chmod(os.path.join(self.temp_dir, name), stat.S_IWRITE)
Steven Bethardb0270112011-01-24 21:02:50 +000043 shutil.rmtree(self.temp_dir, True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +000044
Steven Bethardb0270112011-01-24 21:02:50 +000045 def create_readonly_file(self, filename):
46 file_path = os.path.join(self.temp_dir, filename)
Inada Naoki8bbfeb32021-04-02 12:53:46 +090047 with open(file_path, 'w', encoding="utf-8") as file:
Steven Bethardb0270112011-01-24 21:02:50 +000048 file.write(filename)
49 os.chmod(file_path, stat.S_IREAD)
Benjamin Peterson698a18a2010-03-02 22:34:37 +000050
51class Sig(object):
52
53 def __init__(self, *args, **kwargs):
54 self.args = args
55 self.kwargs = kwargs
56
57
58class NS(object):
59
60 def __init__(self, **kwargs):
61 self.__dict__.update(kwargs)
62
63 def __repr__(self):
64 sorted_items = sorted(self.__dict__.items())
65 kwarg_str = ', '.join(['%s=%r' % tup for tup in sorted_items])
66 return '%s(%s)' % (type(self).__name__, kwarg_str)
67
68 def __eq__(self, other):
69 return vars(self) == vars(other)
70
Benjamin Peterson698a18a2010-03-02 22:34:37 +000071
72class ArgumentParserError(Exception):
73
74 def __init__(self, message, stdout=None, stderr=None, error_code=None):
75 Exception.__init__(self, message, stdout, stderr)
76 self.message = message
77 self.stdout = stdout
78 self.stderr = stderr
79 self.error_code = error_code
80
81
82def stderr_to_parser_error(parse_args, *args, **kwargs):
83 # if this is being called recursively and stderr or stdout is already being
84 # redirected, simply call the function and let the enclosing function
85 # catch the exception
Benjamin Petersonb48af542010-04-11 20:43:16 +000086 if isinstance(sys.stderr, StdIOBuffer) or isinstance(sys.stdout, StdIOBuffer):
Benjamin Peterson698a18a2010-03-02 22:34:37 +000087 return parse_args(*args, **kwargs)
88
89 # if this is not being called recursively, redirect stderr and
90 # use it as the ArgumentParserError message
91 old_stdout = sys.stdout
92 old_stderr = sys.stderr
Benjamin Petersonb48af542010-04-11 20:43:16 +000093 sys.stdout = StdIOBuffer()
94 sys.stderr = StdIOBuffer()
Benjamin Peterson698a18a2010-03-02 22:34:37 +000095 try:
96 try:
97 result = parse_args(*args, **kwargs)
98 for key in list(vars(result)):
99 if getattr(result, key) is sys.stdout:
100 setattr(result, key, old_stdout)
101 if getattr(result, key) is sys.stderr:
102 setattr(result, key, old_stderr)
103 return result
104 except SystemExit:
105 code = sys.exc_info()[1].code
106 stdout = sys.stdout.getvalue()
107 stderr = sys.stderr.getvalue()
alclarksd4331c52020-02-21 08:48:36 +0000108 raise ArgumentParserError(
109 "SystemExit", stdout, stderr, code) from None
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000110 finally:
111 sys.stdout = old_stdout
112 sys.stderr = old_stderr
113
114
115class ErrorRaisingArgumentParser(argparse.ArgumentParser):
116
117 def parse_args(self, *args, **kwargs):
118 parse_args = super(ErrorRaisingArgumentParser, self).parse_args
119 return stderr_to_parser_error(parse_args, *args, **kwargs)
120
121 def exit(self, *args, **kwargs):
122 exit = super(ErrorRaisingArgumentParser, self).exit
123 return stderr_to_parser_error(exit, *args, **kwargs)
124
125 def error(self, *args, **kwargs):
126 error = super(ErrorRaisingArgumentParser, self).error
127 return stderr_to_parser_error(error, *args, **kwargs)
128
129
130class ParserTesterMetaclass(type):
131 """Adds parser tests using the class attributes.
132
133 Classes of this type should specify the following attributes:
134
135 argument_signatures -- a list of Sig objects which specify
136 the signatures of Argument objects to be created
137 failures -- a list of args lists that should cause the parser
138 to fail
139 successes -- a list of (initial_args, options, remaining_args) tuples
140 where initial_args specifies the string args to be parsed,
141 options is a dict that should match the vars() of the options
142 parsed out of initial_args, and remaining_args should be any
143 remaining unparsed arguments
144 """
145
146 def __init__(cls, name, bases, bodydict):
147 if name == 'ParserTestCase':
148 return
149
150 # default parser signature is empty
151 if not hasattr(cls, 'parser_signature'):
152 cls.parser_signature = Sig()
153 if not hasattr(cls, 'parser_class'):
154 cls.parser_class = ErrorRaisingArgumentParser
155
156 # ---------------------------------------
157 # functions for adding optional arguments
158 # ---------------------------------------
159 def no_groups(parser, argument_signatures):
160 """Add all arguments directly to the parser"""
161 for sig in argument_signatures:
162 parser.add_argument(*sig.args, **sig.kwargs)
163
164 def one_group(parser, argument_signatures):
165 """Add all arguments under a single group in the parser"""
166 group = parser.add_argument_group('foo')
167 for sig in argument_signatures:
168 group.add_argument(*sig.args, **sig.kwargs)
169
170 def many_groups(parser, argument_signatures):
171 """Add each argument in its own group to the parser"""
172 for i, sig in enumerate(argument_signatures):
173 group = parser.add_argument_group('foo:%i' % i)
174 group.add_argument(*sig.args, **sig.kwargs)
175
176 # --------------------------
177 # functions for parsing args
178 # --------------------------
179 def listargs(parser, args):
180 """Parse the args by passing in a list"""
181 return parser.parse_args(args)
182
183 def sysargs(parser, args):
184 """Parse the args by defaulting to sys.argv"""
185 old_sys_argv = sys.argv
186 sys.argv = [old_sys_argv[0]] + args
187 try:
188 return parser.parse_args()
189 finally:
190 sys.argv = old_sys_argv
191
192 # class that holds the combination of one optional argument
193 # addition method and one arg parsing method
194 class AddTests(object):
195
196 def __init__(self, tester_cls, add_arguments, parse_args):
197 self._add_arguments = add_arguments
198 self._parse_args = parse_args
199
200 add_arguments_name = self._add_arguments.__name__
201 parse_args_name = self._parse_args.__name__
202 for test_func in [self.test_failures, self.test_successes]:
203 func_name = test_func.__name__
204 names = func_name, add_arguments_name, parse_args_name
205 test_name = '_'.join(names)
206
207 def wrapper(self, test_func=test_func):
208 test_func(self)
209 try:
210 wrapper.__name__ = test_name
211 except TypeError:
212 pass
213 setattr(tester_cls, test_name, wrapper)
214
215 def _get_parser(self, tester):
216 args = tester.parser_signature.args
217 kwargs = tester.parser_signature.kwargs
218 parser = tester.parser_class(*args, **kwargs)
219 self._add_arguments(parser, tester.argument_signatures)
220 return parser
221
222 def test_failures(self, tester):
223 parser = self._get_parser(tester)
224 for args_str in tester.failures:
225 args = args_str.split()
Ezio Melotti12b7f482014-08-05 02:24:03 +0300226 with tester.assertRaises(ArgumentParserError, msg=args):
227 parser.parse_args(args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000228
229 def test_successes(self, tester):
230 parser = self._get_parser(tester)
231 for args, expected_ns in tester.successes:
232 if isinstance(args, str):
233 args = args.split()
234 result_ns = self._parse_args(parser, args)
235 tester.assertEqual(expected_ns, result_ns)
236
237 # add tests for each combination of an optionals adding method
238 # and an arg parsing method
239 for add_arguments in [no_groups, one_group, many_groups]:
240 for parse_args in [listargs, sysargs]:
241 AddTests(cls, add_arguments, parse_args)
242
243bases = TestCase,
244ParserTestCase = ParserTesterMetaclass('ParserTestCase', bases, {})
245
246# ===============
247# Optionals tests
248# ===============
249
250class TestOptionalsSingleDash(ParserTestCase):
251 """Test an Optional with a single-dash option string"""
252
253 argument_signatures = [Sig('-x')]
254 failures = ['-x', 'a', '--foo', '-x --foo', '-x -y']
255 successes = [
256 ('', NS(x=None)),
257 ('-x a', NS(x='a')),
258 ('-xa', NS(x='a')),
259 ('-x -1', NS(x='-1')),
260 ('-x-1', NS(x='-1')),
261 ]
262
263
264class TestOptionalsSingleDashCombined(ParserTestCase):
265 """Test an Optional with a single-dash option string"""
266
267 argument_signatures = [
268 Sig('-x', action='store_true'),
269 Sig('-yyy', action='store_const', const=42),
270 Sig('-z'),
271 ]
272 failures = ['a', '--foo', '-xa', '-x --foo', '-x -z', '-z -x',
273 '-yx', '-yz a', '-yyyx', '-yyyza', '-xyza']
274 successes = [
275 ('', NS(x=False, yyy=None, z=None)),
276 ('-x', NS(x=True, yyy=None, z=None)),
277 ('-za', NS(x=False, yyy=None, z='a')),
278 ('-z a', NS(x=False, yyy=None, z='a')),
279 ('-xza', NS(x=True, yyy=None, z='a')),
280 ('-xz a', NS(x=True, yyy=None, z='a')),
281 ('-x -za', NS(x=True, yyy=None, z='a')),
282 ('-x -z a', NS(x=True, yyy=None, z='a')),
283 ('-y', NS(x=False, yyy=42, z=None)),
284 ('-yyy', NS(x=False, yyy=42, z=None)),
285 ('-x -yyy -za', NS(x=True, yyy=42, z='a')),
286 ('-x -yyy -z a', NS(x=True, yyy=42, z='a')),
287 ]
288
289
290class TestOptionalsSingleDashLong(ParserTestCase):
291 """Test an Optional with a multi-character single-dash option string"""
292
293 argument_signatures = [Sig('-foo')]
294 failures = ['-foo', 'a', '--foo', '-foo --foo', '-foo -y', '-fooa']
295 successes = [
296 ('', NS(foo=None)),
297 ('-foo a', NS(foo='a')),
298 ('-foo -1', NS(foo='-1')),
299 ('-fo a', NS(foo='a')),
300 ('-f a', NS(foo='a')),
301 ]
302
303
304class TestOptionalsSingleDashSubsetAmbiguous(ParserTestCase):
305 """Test Optionals where option strings are subsets of each other"""
306
307 argument_signatures = [Sig('-f'), Sig('-foobar'), Sig('-foorab')]
308 failures = ['-f', '-foo', '-fo', '-foo b', '-foob', '-fooba', '-foora']
309 successes = [
310 ('', NS(f=None, foobar=None, foorab=None)),
311 ('-f a', NS(f='a', foobar=None, foorab=None)),
312 ('-fa', NS(f='a', foobar=None, foorab=None)),
313 ('-foa', NS(f='oa', foobar=None, foorab=None)),
314 ('-fooa', NS(f='ooa', foobar=None, foorab=None)),
315 ('-foobar a', NS(f=None, foobar='a', foorab=None)),
316 ('-foorab a', NS(f=None, foobar=None, foorab='a')),
317 ]
318
319
320class TestOptionalsSingleDashAmbiguous(ParserTestCase):
321 """Test Optionals that partially match but are not subsets"""
322
323 argument_signatures = [Sig('-foobar'), Sig('-foorab')]
324 failures = ['-f', '-f a', '-fa', '-foa', '-foo', '-fo', '-foo b']
325 successes = [
326 ('', NS(foobar=None, foorab=None)),
327 ('-foob a', NS(foobar='a', foorab=None)),
328 ('-foor a', NS(foobar=None, foorab='a')),
329 ('-fooba a', NS(foobar='a', foorab=None)),
330 ('-foora a', NS(foobar=None, foorab='a')),
331 ('-foobar a', NS(foobar='a', foorab=None)),
332 ('-foorab a', NS(foobar=None, foorab='a')),
333 ]
334
335
336class TestOptionalsNumeric(ParserTestCase):
337 """Test an Optional with a short opt string"""
338
339 argument_signatures = [Sig('-1', dest='one')]
340 failures = ['-1', 'a', '-1 --foo', '-1 -y', '-1 -1', '-1 -2']
341 successes = [
342 ('', NS(one=None)),
343 ('-1 a', NS(one='a')),
344 ('-1a', NS(one='a')),
345 ('-1-2', NS(one='-2')),
346 ]
347
348
349class TestOptionalsDoubleDash(ParserTestCase):
350 """Test an Optional with a double-dash option string"""
351
352 argument_signatures = [Sig('--foo')]
353 failures = ['--foo', '-f', '-f a', 'a', '--foo -x', '--foo --bar']
354 successes = [
355 ('', NS(foo=None)),
356 ('--foo a', NS(foo='a')),
357 ('--foo=a', NS(foo='a')),
358 ('--foo -2.5', NS(foo='-2.5')),
359 ('--foo=-2.5', NS(foo='-2.5')),
360 ]
361
362
363class TestOptionalsDoubleDashPartialMatch(ParserTestCase):
364 """Tests partial matching with a double-dash option string"""
365
366 argument_signatures = [
367 Sig('--badger', action='store_true'),
368 Sig('--bat'),
369 ]
370 failures = ['--bar', '--b', '--ba', '--b=2', '--ba=4', '--badge 5']
371 successes = [
372 ('', NS(badger=False, bat=None)),
373 ('--bat X', NS(badger=False, bat='X')),
374 ('--bad', NS(badger=True, bat=None)),
375 ('--badg', NS(badger=True, bat=None)),
376 ('--badge', NS(badger=True, bat=None)),
377 ('--badger', NS(badger=True, bat=None)),
378 ]
379
380
381class TestOptionalsDoubleDashPrefixMatch(ParserTestCase):
382 """Tests when one double-dash option string is a prefix of another"""
383
384 argument_signatures = [
385 Sig('--badger', action='store_true'),
386 Sig('--ba'),
387 ]
388 failures = ['--bar', '--b', '--ba', '--b=2', '--badge 5']
389 successes = [
390 ('', NS(badger=False, ba=None)),
391 ('--ba X', NS(badger=False, ba='X')),
392 ('--ba=X', NS(badger=False, ba='X')),
393 ('--bad', NS(badger=True, ba=None)),
394 ('--badg', NS(badger=True, ba=None)),
395 ('--badge', NS(badger=True, ba=None)),
396 ('--badger', NS(badger=True, ba=None)),
397 ]
398
399
400class TestOptionalsSingleDoubleDash(ParserTestCase):
401 """Test an Optional with single- and double-dash option strings"""
402
403 argument_signatures = [
404 Sig('-f', action='store_true'),
405 Sig('--bar'),
406 Sig('-baz', action='store_const', const=42),
407 ]
408 failures = ['--bar', '-fbar', '-fbaz', '-bazf', '-b B', 'B']
409 successes = [
410 ('', NS(f=False, bar=None, baz=None)),
411 ('-f', NS(f=True, bar=None, baz=None)),
412 ('--ba B', NS(f=False, bar='B', baz=None)),
413 ('-f --bar B', NS(f=True, bar='B', baz=None)),
414 ('-f -b', NS(f=True, bar=None, baz=42)),
415 ('-ba -f', NS(f=True, bar=None, baz=42)),
416 ]
417
418
419class TestOptionalsAlternatePrefixChars(ParserTestCase):
R. David Murray88c49fe2010-08-03 17:56:09 +0000420 """Test an Optional with option strings with custom prefixes"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000421
422 parser_signature = Sig(prefix_chars='+:/', add_help=False)
423 argument_signatures = [
424 Sig('+f', action='store_true'),
425 Sig('::bar'),
426 Sig('/baz', action='store_const', const=42),
427 ]
R. David Murray88c49fe2010-08-03 17:56:09 +0000428 failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz', '-h', '--help', '+h', '::help', '/help']
429 successes = [
430 ('', NS(f=False, bar=None, baz=None)),
431 ('+f', NS(f=True, bar=None, baz=None)),
432 ('::ba B', NS(f=False, bar='B', baz=None)),
433 ('+f ::bar B', NS(f=True, bar='B', baz=None)),
434 ('+f /b', NS(f=True, bar=None, baz=42)),
435 ('/ba +f', NS(f=True, bar=None, baz=42)),
436 ]
437
438
439class TestOptionalsAlternatePrefixCharsAddedHelp(ParserTestCase):
440 """When ``-`` not in prefix_chars, default operators created for help
441 should use the prefix_chars in use rather than - or --
442 http://bugs.python.org/issue9444"""
443
444 parser_signature = Sig(prefix_chars='+:/', add_help=True)
445 argument_signatures = [
446 Sig('+f', action='store_true'),
447 Sig('::bar'),
448 Sig('/baz', action='store_const', const=42),
449 ]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000450 failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz']
451 successes = [
452 ('', NS(f=False, bar=None, baz=None)),
453 ('+f', NS(f=True, bar=None, baz=None)),
454 ('::ba B', NS(f=False, bar='B', baz=None)),
455 ('+f ::bar B', NS(f=True, bar='B', baz=None)),
456 ('+f /b', NS(f=True, bar=None, baz=42)),
R. David Murray88c49fe2010-08-03 17:56:09 +0000457 ('/ba +f', NS(f=True, bar=None, baz=42))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000458 ]
459
Steven Bethard1ca45a52010-11-01 15:57:36 +0000460
461class TestOptionalsAlternatePrefixCharsMultipleShortArgs(ParserTestCase):
462 """Verify that Optionals must be called with their defined prefixes"""
463
464 parser_signature = Sig(prefix_chars='+-', add_help=False)
465 argument_signatures = [
466 Sig('-x', action='store_true'),
467 Sig('+y', action='store_true'),
468 Sig('+z', action='store_true'),
469 ]
470 failures = ['-w',
471 '-xyz',
472 '+x',
473 '-y',
474 '+xyz',
475 ]
476 successes = [
477 ('', NS(x=False, y=False, z=False)),
478 ('-x', NS(x=True, y=False, z=False)),
479 ('+y -x', NS(x=True, y=True, z=False)),
480 ('+yz -x', NS(x=True, y=True, z=True)),
481 ]
482
483
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000484class TestOptionalsShortLong(ParserTestCase):
485 """Test a combination of single- and double-dash option strings"""
486
487 argument_signatures = [
488 Sig('-v', '--verbose', '-n', '--noisy', action='store_true'),
489 ]
490 failures = ['--x --verbose', '-N', 'a', '-v x']
491 successes = [
492 ('', NS(verbose=False)),
493 ('-v', NS(verbose=True)),
494 ('--verbose', NS(verbose=True)),
495 ('-n', NS(verbose=True)),
496 ('--noisy', NS(verbose=True)),
497 ]
498
499
500class TestOptionalsDest(ParserTestCase):
501 """Tests various means of setting destination"""
502
503 argument_signatures = [Sig('--foo-bar'), Sig('--baz', dest='zabbaz')]
504 failures = ['a']
505 successes = [
506 ('--foo-bar f', NS(foo_bar='f', zabbaz=None)),
507 ('--baz g', NS(foo_bar=None, zabbaz='g')),
508 ('--foo-bar h --baz i', NS(foo_bar='h', zabbaz='i')),
509 ('--baz j --foo-bar k', NS(foo_bar='k', zabbaz='j')),
510 ]
511
512
513class TestOptionalsDefault(ParserTestCase):
514 """Tests specifying a default for an Optional"""
515
516 argument_signatures = [Sig('-x'), Sig('-y', default=42)]
517 failures = ['a']
518 successes = [
519 ('', NS(x=None, y=42)),
520 ('-xx', NS(x='x', y=42)),
521 ('-yy', NS(x=None, y='y')),
522 ]
523
524
525class TestOptionalsNargsDefault(ParserTestCase):
526 """Tests not specifying the number of args for an Optional"""
527
528 argument_signatures = [Sig('-x')]
529 failures = ['a', '-x']
530 successes = [
531 ('', NS(x=None)),
532 ('-x a', NS(x='a')),
533 ]
534
535
536class TestOptionalsNargs1(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +0000537 """Tests specifying 1 arg for an Optional"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000538
539 argument_signatures = [Sig('-x', nargs=1)]
540 failures = ['a', '-x']
541 successes = [
542 ('', NS(x=None)),
543 ('-x a', NS(x=['a'])),
544 ]
545
546
547class TestOptionalsNargs3(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +0000548 """Tests specifying 3 args for an Optional"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000549
550 argument_signatures = [Sig('-x', nargs=3)]
551 failures = ['a', '-x', '-x a', '-x a b', 'a -x', 'a -x b']
552 successes = [
553 ('', NS(x=None)),
554 ('-x a b c', NS(x=['a', 'b', 'c'])),
555 ]
556
557
558class TestOptionalsNargsOptional(ParserTestCase):
559 """Tests specifying an Optional arg for an Optional"""
560
561 argument_signatures = [
562 Sig('-w', nargs='?'),
563 Sig('-x', nargs='?', const=42),
564 Sig('-y', nargs='?', default='spam'),
565 Sig('-z', nargs='?', type=int, const='42', default='84'),
566 ]
567 failures = ['2']
568 successes = [
569 ('', NS(w=None, x=None, y='spam', z=84)),
570 ('-w', NS(w=None, x=None, y='spam', z=84)),
571 ('-w 2', NS(w='2', x=None, y='spam', z=84)),
572 ('-x', NS(w=None, x=42, y='spam', z=84)),
573 ('-x 2', NS(w=None, x='2', y='spam', z=84)),
574 ('-y', NS(w=None, x=None, y=None, z=84)),
575 ('-y 2', NS(w=None, x=None, y='2', z=84)),
576 ('-z', NS(w=None, x=None, y='spam', z=42)),
577 ('-z 2', NS(w=None, x=None, y='spam', z=2)),
578 ]
579
580
581class TestOptionalsNargsZeroOrMore(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +0000582 """Tests specifying args for an Optional that accepts zero or more"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000583
584 argument_signatures = [
585 Sig('-x', nargs='*'),
586 Sig('-y', nargs='*', default='spam'),
587 ]
588 failures = ['a']
589 successes = [
590 ('', NS(x=None, y='spam')),
591 ('-x', NS(x=[], y='spam')),
592 ('-x a', NS(x=['a'], y='spam')),
593 ('-x a b', NS(x=['a', 'b'], y='spam')),
594 ('-y', NS(x=None, y=[])),
595 ('-y a', NS(x=None, y=['a'])),
596 ('-y a b', NS(x=None, y=['a', 'b'])),
597 ]
598
599
600class TestOptionalsNargsOneOrMore(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +0000601 """Tests specifying args for an Optional that accepts one or more"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000602
603 argument_signatures = [
604 Sig('-x', nargs='+'),
605 Sig('-y', nargs='+', default='spam'),
606 ]
607 failures = ['a', '-x', '-y', 'a -x', 'a -y b']
608 successes = [
609 ('', NS(x=None, y='spam')),
610 ('-x a', NS(x=['a'], y='spam')),
611 ('-x a b', NS(x=['a', 'b'], y='spam')),
612 ('-y a', NS(x=None, y=['a'])),
613 ('-y a b', NS(x=None, y=['a', 'b'])),
614 ]
615
616
617class TestOptionalsChoices(ParserTestCase):
618 """Tests specifying the choices for an Optional"""
619
620 argument_signatures = [
621 Sig('-f', choices='abc'),
622 Sig('-g', type=int, choices=range(5))]
623 failures = ['a', '-f d', '-fad', '-ga', '-g 6']
624 successes = [
625 ('', NS(f=None, g=None)),
626 ('-f a', NS(f='a', g=None)),
627 ('-f c', NS(f='c', g=None)),
628 ('-g 0', NS(f=None, g=0)),
629 ('-g 03', NS(f=None, g=3)),
630 ('-fb -g4', NS(f='b', g=4)),
631 ]
632
633
634class TestOptionalsRequired(ParserTestCase):
Benjamin Peterson82f34ad2015-01-13 09:17:24 -0500635 """Tests an optional action that is required"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000636
637 argument_signatures = [
638 Sig('-x', type=int, required=True),
639 ]
640 failures = ['a', '']
641 successes = [
642 ('-x 1', NS(x=1)),
643 ('-x42', NS(x=42)),
644 ]
645
646
647class TestOptionalsActionStore(ParserTestCase):
648 """Tests the store action for an Optional"""
649
650 argument_signatures = [Sig('-x', action='store')]
651 failures = ['a', 'a -x']
652 successes = [
653 ('', NS(x=None)),
654 ('-xfoo', NS(x='foo')),
655 ]
656
657
658class TestOptionalsActionStoreConst(ParserTestCase):
659 """Tests the store_const action for an Optional"""
660
661 argument_signatures = [Sig('-y', action='store_const', const=object)]
662 failures = ['a']
663 successes = [
664 ('', NS(y=None)),
665 ('-y', NS(y=object)),
666 ]
667
668
669class TestOptionalsActionStoreFalse(ParserTestCase):
670 """Tests the store_false action for an Optional"""
671
672 argument_signatures = [Sig('-z', action='store_false')]
673 failures = ['a', '-za', '-z a']
674 successes = [
675 ('', NS(z=True)),
676 ('-z', NS(z=False)),
677 ]
678
679
680class TestOptionalsActionStoreTrue(ParserTestCase):
681 """Tests the store_true action for an Optional"""
682
683 argument_signatures = [Sig('--apple', action='store_true')]
684 failures = ['a', '--apple=b', '--apple b']
685 successes = [
686 ('', NS(apple=False)),
687 ('--apple', NS(apple=True)),
688 ]
689
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200690class TestBooleanOptionalAction(ParserTestCase):
691 """Tests BooleanOptionalAction"""
692
693 argument_signatures = [Sig('--foo', action=argparse.BooleanOptionalAction)]
694 failures = ['--foo bar', '--foo=bar']
695 successes = [
696 ('', NS(foo=None)),
697 ('--foo', NS(foo=True)),
698 ('--no-foo', NS(foo=False)),
699 ('--foo --no-foo', NS(foo=False)), # useful for aliases
700 ('--no-foo --foo', NS(foo=True)),
701 ]
702
Rémi Lapeyreb084d1b2020-06-06 00:00:42 +0200703 def test_const(self):
704 # See bpo-40862
705 parser = argparse.ArgumentParser()
706 with self.assertRaises(TypeError) as cm:
707 parser.add_argument('--foo', const=True, action=argparse.BooleanOptionalAction)
708
709 self.assertIn("got an unexpected keyword argument 'const'", str(cm.exception))
710
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200711class TestBooleanOptionalActionRequired(ParserTestCase):
712 """Tests BooleanOptionalAction required"""
713
714 argument_signatures = [
715 Sig('--foo', required=True, action=argparse.BooleanOptionalAction)
716 ]
717 failures = ['']
718 successes = [
719 ('--foo', NS(foo=True)),
720 ('--no-foo', NS(foo=False)),
721 ]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000722
723class TestOptionalsActionAppend(ParserTestCase):
724 """Tests the append action for an Optional"""
725
726 argument_signatures = [Sig('--baz', action='append')]
727 failures = ['a', '--baz', 'a --baz', '--baz a b']
728 successes = [
729 ('', NS(baz=None)),
730 ('--baz a', NS(baz=['a'])),
731 ('--baz a --baz b', NS(baz=['a', 'b'])),
732 ]
733
734
735class TestOptionalsActionAppendWithDefault(ParserTestCase):
736 """Tests the append action for an Optional"""
737
738 argument_signatures = [Sig('--baz', action='append', default=['X'])]
739 failures = ['a', '--baz', 'a --baz', '--baz a b']
740 successes = [
741 ('', NS(baz=['X'])),
742 ('--baz a', NS(baz=['X', 'a'])),
743 ('--baz a --baz b', NS(baz=['X', 'a', 'b'])),
744 ]
745
746
747class TestOptionalsActionAppendConst(ParserTestCase):
748 """Tests the append_const action for an Optional"""
749
750 argument_signatures = [
751 Sig('-b', action='append_const', const=Exception),
752 Sig('-c', action='append', dest='b'),
753 ]
754 failures = ['a', '-c', 'a -c', '-bx', '-b x']
755 successes = [
756 ('', NS(b=None)),
757 ('-b', NS(b=[Exception])),
758 ('-b -cx -b -cyz', NS(b=[Exception, 'x', Exception, 'yz'])),
759 ]
760
761
762class TestOptionalsActionAppendConstWithDefault(ParserTestCase):
763 """Tests the append_const action for an Optional"""
764
765 argument_signatures = [
766 Sig('-b', action='append_const', const=Exception, default=['X']),
767 Sig('-c', action='append', dest='b'),
768 ]
769 failures = ['a', '-c', 'a -c', '-bx', '-b x']
770 successes = [
771 ('', NS(b=['X'])),
772 ('-b', NS(b=['X', Exception])),
773 ('-b -cx -b -cyz', NS(b=['X', Exception, 'x', Exception, 'yz'])),
774 ]
775
776
777class TestOptionalsActionCount(ParserTestCase):
778 """Tests the count action for an Optional"""
779
780 argument_signatures = [Sig('-x', action='count')]
781 failures = ['a', '-x a', '-x b', '-x a -x b']
782 successes = [
783 ('', NS(x=None)),
784 ('-x', NS(x=1)),
785 ]
786
787
Berker Peksag8089cd62015-02-14 01:39:17 +0200788class TestOptionalsAllowLongAbbreviation(ParserTestCase):
789 """Allow long options to be abbreviated unambiguously"""
790
791 argument_signatures = [
792 Sig('--foo'),
793 Sig('--foobaz'),
794 Sig('--fooble', action='store_true'),
795 ]
796 failures = ['--foob 5', '--foob']
797 successes = [
798 ('', NS(foo=None, foobaz=None, fooble=False)),
799 ('--foo 7', NS(foo='7', foobaz=None, fooble=False)),
800 ('--fooba a', NS(foo=None, foobaz='a', fooble=False)),
801 ('--foobl --foo g', NS(foo='g', foobaz=None, fooble=True)),
802 ]
803
804
805class TestOptionalsDisallowLongAbbreviation(ParserTestCase):
806 """Do not allow abbreviations of long options at all"""
807
808 parser_signature = Sig(allow_abbrev=False)
809 argument_signatures = [
810 Sig('--foo'),
811 Sig('--foodle', action='store_true'),
812 Sig('--foonly'),
813 ]
814 failures = ['-foon 3', '--foon 3', '--food', '--food --foo 2']
815 successes = [
816 ('', NS(foo=None, foodle=False, foonly=None)),
817 ('--foo 3', NS(foo='3', foodle=False, foonly=None)),
818 ('--foonly 7 --foodle --foo 2', NS(foo='2', foodle=True, foonly='7')),
819 ]
820
Zac Hatfield-Doddsdffca9e2019-07-14 00:35:58 -0500821
Kyle Meyer8edfc472020-02-18 04:48:57 -0500822class TestOptionalsDisallowLongAbbreviationPrefixChars(ParserTestCase):
823 """Disallowing abbreviations works with alternative prefix characters"""
824
825 parser_signature = Sig(prefix_chars='+', allow_abbrev=False)
826 argument_signatures = [
827 Sig('++foo'),
828 Sig('++foodle', action='store_true'),
829 Sig('++foonly'),
830 ]
831 failures = ['+foon 3', '++foon 3', '++food', '++food ++foo 2']
832 successes = [
833 ('', NS(foo=None, foodle=False, foonly=None)),
834 ('++foo 3', NS(foo='3', foodle=False, foonly=None)),
835 ('++foonly 7 ++foodle ++foo 2', NS(foo='2', foodle=True, foonly='7')),
836 ]
837
838
Zac Hatfield-Doddsdffca9e2019-07-14 00:35:58 -0500839class TestDisallowLongAbbreviationAllowsShortGrouping(ParserTestCase):
840 """Do not allow abbreviations of long options at all"""
841
842 parser_signature = Sig(allow_abbrev=False)
843 argument_signatures = [
844 Sig('-r'),
845 Sig('-c', action='count'),
846 ]
847 failures = ['-r', '-c -r']
848 successes = [
849 ('', NS(r=None, c=None)),
850 ('-ra', NS(r='a', c=None)),
851 ('-rcc', NS(r='cc', c=None)),
852 ('-cc', NS(r=None, c=2)),
853 ('-cc -ra', NS(r='a', c=2)),
854 ('-ccrcc', NS(r='cc', c=2)),
855 ]
856
Kyle Meyer8edfc472020-02-18 04:48:57 -0500857
858class TestDisallowLongAbbreviationAllowsShortGroupingPrefix(ParserTestCase):
859 """Short option grouping works with custom prefix and allow_abbrev=False"""
860
861 parser_signature = Sig(prefix_chars='+', allow_abbrev=False)
862 argument_signatures = [
863 Sig('+r'),
864 Sig('+c', action='count'),
865 ]
866 failures = ['+r', '+c +r']
867 successes = [
868 ('', NS(r=None, c=None)),
869 ('+ra', NS(r='a', c=None)),
870 ('+rcc', NS(r='cc', c=None)),
871 ('+cc', NS(r=None, c=2)),
872 ('+cc +ra', NS(r='a', c=2)),
873 ('+ccrcc', NS(r='cc', c=2)),
874 ]
875
876
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000877# ================
878# Positional tests
879# ================
880
881class TestPositionalsNargsNone(ParserTestCase):
882 """Test a Positional that doesn't specify nargs"""
883
884 argument_signatures = [Sig('foo')]
885 failures = ['', '-x', 'a b']
886 successes = [
887 ('a', NS(foo='a')),
888 ]
889
890
891class TestPositionalsNargs1(ParserTestCase):
892 """Test a Positional that specifies an nargs of 1"""
893
894 argument_signatures = [Sig('foo', nargs=1)]
895 failures = ['', '-x', 'a b']
896 successes = [
897 ('a', NS(foo=['a'])),
898 ]
899
900
901class TestPositionalsNargs2(ParserTestCase):
902 """Test a Positional that specifies an nargs of 2"""
903
904 argument_signatures = [Sig('foo', nargs=2)]
905 failures = ['', 'a', '-x', 'a b c']
906 successes = [
907 ('a b', NS(foo=['a', 'b'])),
908 ]
909
910
911class TestPositionalsNargsZeroOrMore(ParserTestCase):
912 """Test a Positional that specifies unlimited nargs"""
913
914 argument_signatures = [Sig('foo', nargs='*')]
915 failures = ['-x']
916 successes = [
917 ('', NS(foo=[])),
918 ('a', NS(foo=['a'])),
919 ('a b', NS(foo=['a', 'b'])),
920 ]
921
922
923class TestPositionalsNargsZeroOrMoreDefault(ParserTestCase):
924 """Test a Positional that specifies unlimited nargs and a default"""
925
926 argument_signatures = [Sig('foo', nargs='*', default='bar')]
927 failures = ['-x']
928 successes = [
929 ('', NS(foo='bar')),
930 ('a', NS(foo=['a'])),
931 ('a b', NS(foo=['a', 'b'])),
932 ]
933
934
935class TestPositionalsNargsOneOrMore(ParserTestCase):
936 """Test a Positional that specifies one or more nargs"""
937
938 argument_signatures = [Sig('foo', nargs='+')]
939 failures = ['', '-x']
940 successes = [
941 ('a', NS(foo=['a'])),
942 ('a b', NS(foo=['a', 'b'])),
943 ]
944
945
946class TestPositionalsNargsOptional(ParserTestCase):
947 """Tests an Optional Positional"""
948
949 argument_signatures = [Sig('foo', nargs='?')]
950 failures = ['-x', 'a b']
951 successes = [
952 ('', NS(foo=None)),
953 ('a', NS(foo='a')),
954 ]
955
956
957class TestPositionalsNargsOptionalDefault(ParserTestCase):
958 """Tests an Optional Positional with a default value"""
959
960 argument_signatures = [Sig('foo', nargs='?', default=42)]
961 failures = ['-x', 'a b']
962 successes = [
963 ('', NS(foo=42)),
964 ('a', NS(foo='a')),
965 ]
966
967
968class TestPositionalsNargsOptionalConvertedDefault(ParserTestCase):
969 """Tests an Optional Positional with a default value
970 that needs to be converted to the appropriate type.
971 """
972
973 argument_signatures = [
974 Sig('foo', nargs='?', type=int, default='42'),
975 ]
976 failures = ['-x', 'a b', '1 2']
977 successes = [
978 ('', NS(foo=42)),
979 ('1', NS(foo=1)),
980 ]
981
982
983class TestPositionalsNargsNoneNone(ParserTestCase):
984 """Test two Positionals that don't specify nargs"""
985
986 argument_signatures = [Sig('foo'), Sig('bar')]
987 failures = ['', '-x', 'a', 'a b c']
988 successes = [
989 ('a b', NS(foo='a', bar='b')),
990 ]
991
992
993class TestPositionalsNargsNone1(ParserTestCase):
994 """Test a Positional with no nargs followed by one with 1"""
995
996 argument_signatures = [Sig('foo'), Sig('bar', nargs=1)]
997 failures = ['', '--foo', 'a', 'a b c']
998 successes = [
999 ('a b', NS(foo='a', bar=['b'])),
1000 ]
1001
1002
1003class TestPositionalsNargs2None(ParserTestCase):
1004 """Test a Positional with 2 nargs followed by one with none"""
1005
1006 argument_signatures = [Sig('foo', nargs=2), Sig('bar')]
1007 failures = ['', '--foo', 'a', 'a b', 'a b c d']
1008 successes = [
1009 ('a b c', NS(foo=['a', 'b'], bar='c')),
1010 ]
1011
1012
1013class TestPositionalsNargsNoneZeroOrMore(ParserTestCase):
1014 """Test a Positional with no nargs followed by one with unlimited"""
1015
1016 argument_signatures = [Sig('foo'), Sig('bar', nargs='*')]
1017 failures = ['', '--foo']
1018 successes = [
1019 ('a', NS(foo='a', bar=[])),
1020 ('a b', NS(foo='a', bar=['b'])),
1021 ('a b c', NS(foo='a', bar=['b', 'c'])),
1022 ]
1023
1024
1025class TestPositionalsNargsNoneOneOrMore(ParserTestCase):
1026 """Test a Positional with no nargs followed by one with one or more"""
1027
1028 argument_signatures = [Sig('foo'), Sig('bar', nargs='+')]
1029 failures = ['', '--foo', 'a']
1030 successes = [
1031 ('a b', NS(foo='a', bar=['b'])),
1032 ('a b c', NS(foo='a', bar=['b', 'c'])),
1033 ]
1034
1035
1036class TestPositionalsNargsNoneOptional(ParserTestCase):
1037 """Test a Positional with no nargs followed by one with an Optional"""
1038
1039 argument_signatures = [Sig('foo'), Sig('bar', nargs='?')]
1040 failures = ['', '--foo', 'a b c']
1041 successes = [
1042 ('a', NS(foo='a', bar=None)),
1043 ('a b', NS(foo='a', bar='b')),
1044 ]
1045
1046
1047class TestPositionalsNargsZeroOrMoreNone(ParserTestCase):
1048 """Test a Positional with unlimited nargs followed by one with none"""
1049
1050 argument_signatures = [Sig('foo', nargs='*'), Sig('bar')]
1051 failures = ['', '--foo']
1052 successes = [
1053 ('a', NS(foo=[], bar='a')),
1054 ('a b', NS(foo=['a'], bar='b')),
1055 ('a b c', NS(foo=['a', 'b'], bar='c')),
1056 ]
1057
1058
1059class TestPositionalsNargsOneOrMoreNone(ParserTestCase):
1060 """Test a Positional with one or more nargs followed by one with none"""
1061
1062 argument_signatures = [Sig('foo', nargs='+'), Sig('bar')]
1063 failures = ['', '--foo', 'a']
1064 successes = [
1065 ('a b', NS(foo=['a'], bar='b')),
1066 ('a b c', NS(foo=['a', 'b'], bar='c')),
1067 ]
1068
1069
1070class TestPositionalsNargsOptionalNone(ParserTestCase):
1071 """Test a Positional with an Optional nargs followed by one with none"""
1072
1073 argument_signatures = [Sig('foo', nargs='?', default=42), Sig('bar')]
1074 failures = ['', '--foo', 'a b c']
1075 successes = [
1076 ('a', NS(foo=42, bar='a')),
1077 ('a b', NS(foo='a', bar='b')),
1078 ]
1079
1080
1081class TestPositionalsNargs2ZeroOrMore(ParserTestCase):
1082 """Test a Positional with 2 nargs followed by one with unlimited"""
1083
1084 argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='*')]
1085 failures = ['', '--foo', 'a']
1086 successes = [
1087 ('a b', NS(foo=['a', 'b'], bar=[])),
1088 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1089 ]
1090
1091
1092class TestPositionalsNargs2OneOrMore(ParserTestCase):
1093 """Test a Positional with 2 nargs followed by one with one or more"""
1094
1095 argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='+')]
1096 failures = ['', '--foo', 'a', 'a b']
1097 successes = [
1098 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1099 ]
1100
1101
1102class TestPositionalsNargs2Optional(ParserTestCase):
1103 """Test a Positional with 2 nargs followed by one optional"""
1104
1105 argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='?')]
1106 failures = ['', '--foo', 'a', 'a b c d']
1107 successes = [
1108 ('a b', NS(foo=['a', 'b'], bar=None)),
1109 ('a b c', NS(foo=['a', 'b'], bar='c')),
1110 ]
1111
1112
1113class TestPositionalsNargsZeroOrMore1(ParserTestCase):
1114 """Test a Positional with unlimited nargs followed by one with 1"""
1115
1116 argument_signatures = [Sig('foo', nargs='*'), Sig('bar', nargs=1)]
1117 failures = ['', '--foo', ]
1118 successes = [
1119 ('a', NS(foo=[], bar=['a'])),
1120 ('a b', NS(foo=['a'], bar=['b'])),
1121 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1122 ]
1123
1124
1125class TestPositionalsNargsOneOrMore1(ParserTestCase):
1126 """Test a Positional with one or more nargs followed by one with 1"""
1127
1128 argument_signatures = [Sig('foo', nargs='+'), Sig('bar', nargs=1)]
1129 failures = ['', '--foo', 'a']
1130 successes = [
1131 ('a b', NS(foo=['a'], bar=['b'])),
1132 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1133 ]
1134
1135
1136class TestPositionalsNargsOptional1(ParserTestCase):
1137 """Test a Positional with an Optional nargs followed by one with 1"""
1138
1139 argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs=1)]
1140 failures = ['', '--foo', 'a b c']
1141 successes = [
1142 ('a', NS(foo=None, bar=['a'])),
1143 ('a b', NS(foo='a', bar=['b'])),
1144 ]
1145
1146
1147class TestPositionalsNargsNoneZeroOrMore1(ParserTestCase):
1148 """Test three Positionals: no nargs, unlimited nargs and 1 nargs"""
1149
1150 argument_signatures = [
1151 Sig('foo'),
1152 Sig('bar', nargs='*'),
1153 Sig('baz', nargs=1),
1154 ]
1155 failures = ['', '--foo', 'a']
1156 successes = [
1157 ('a b', NS(foo='a', bar=[], baz=['b'])),
1158 ('a b c', NS(foo='a', bar=['b'], baz=['c'])),
1159 ]
1160
1161
1162class TestPositionalsNargsNoneOneOrMore1(ParserTestCase):
1163 """Test three Positionals: no nargs, one or more nargs and 1 nargs"""
1164
1165 argument_signatures = [
1166 Sig('foo'),
1167 Sig('bar', nargs='+'),
1168 Sig('baz', nargs=1),
1169 ]
1170 failures = ['', '--foo', 'a', 'b']
1171 successes = [
1172 ('a b c', NS(foo='a', bar=['b'], baz=['c'])),
1173 ('a b c d', NS(foo='a', bar=['b', 'c'], baz=['d'])),
1174 ]
1175
1176
1177class TestPositionalsNargsNoneOptional1(ParserTestCase):
1178 """Test three Positionals: no nargs, optional narg and 1 nargs"""
1179
1180 argument_signatures = [
1181 Sig('foo'),
1182 Sig('bar', nargs='?', default=0.625),
1183 Sig('baz', nargs=1),
1184 ]
1185 failures = ['', '--foo', 'a']
1186 successes = [
1187 ('a b', NS(foo='a', bar=0.625, baz=['b'])),
1188 ('a b c', NS(foo='a', bar='b', baz=['c'])),
1189 ]
1190
1191
1192class TestPositionalsNargsOptionalOptional(ParserTestCase):
1193 """Test two optional nargs"""
1194
1195 argument_signatures = [
1196 Sig('foo', nargs='?'),
1197 Sig('bar', nargs='?', default=42),
1198 ]
1199 failures = ['--foo', 'a b c']
1200 successes = [
1201 ('', NS(foo=None, bar=42)),
1202 ('a', NS(foo='a', bar=42)),
1203 ('a b', NS(foo='a', bar='b')),
1204 ]
1205
1206
1207class TestPositionalsNargsOptionalZeroOrMore(ParserTestCase):
1208 """Test an Optional narg followed by unlimited nargs"""
1209
1210 argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs='*')]
1211 failures = ['--foo']
1212 successes = [
1213 ('', NS(foo=None, bar=[])),
1214 ('a', NS(foo='a', bar=[])),
1215 ('a b', NS(foo='a', bar=['b'])),
1216 ('a b c', NS(foo='a', bar=['b', 'c'])),
1217 ]
1218
1219
1220class TestPositionalsNargsOptionalOneOrMore(ParserTestCase):
1221 """Test an Optional narg followed by one or more nargs"""
1222
1223 argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs='+')]
1224 failures = ['', '--foo']
1225 successes = [
1226 ('a', NS(foo=None, bar=['a'])),
1227 ('a b', NS(foo='a', bar=['b'])),
1228 ('a b c', NS(foo='a', bar=['b', 'c'])),
1229 ]
1230
1231
1232class TestPositionalsChoicesString(ParserTestCase):
1233 """Test a set of single-character choices"""
1234
1235 argument_signatures = [Sig('spam', choices=set('abcdefg'))]
1236 failures = ['', '--foo', 'h', '42', 'ef']
1237 successes = [
1238 ('a', NS(spam='a')),
1239 ('g', NS(spam='g')),
1240 ]
1241
1242
1243class TestPositionalsChoicesInt(ParserTestCase):
1244 """Test a set of integer choices"""
1245
1246 argument_signatures = [Sig('spam', type=int, choices=range(20))]
1247 failures = ['', '--foo', 'h', '42', 'ef']
1248 successes = [
1249 ('4', NS(spam=4)),
1250 ('15', NS(spam=15)),
1251 ]
1252
1253
1254class TestPositionalsActionAppend(ParserTestCase):
1255 """Test the 'append' action"""
1256
1257 argument_signatures = [
1258 Sig('spam', action='append'),
1259 Sig('spam', action='append', nargs=2),
1260 ]
1261 failures = ['', '--foo', 'a', 'a b', 'a b c d']
1262 successes = [
1263 ('a b c', NS(spam=['a', ['b', 'c']])),
1264 ]
1265
1266# ========================================
1267# Combined optionals and positionals tests
1268# ========================================
1269
1270class TestOptionalsNumericAndPositionals(ParserTestCase):
1271 """Tests negative number args when numeric options are present"""
1272
1273 argument_signatures = [
1274 Sig('x', nargs='?'),
1275 Sig('-4', dest='y', action='store_true'),
1276 ]
1277 failures = ['-2', '-315']
1278 successes = [
1279 ('', NS(x=None, y=False)),
1280 ('a', NS(x='a', y=False)),
1281 ('-4', NS(x=None, y=True)),
1282 ('-4 a', NS(x='a', y=True)),
1283 ]
1284
1285
1286class TestOptionalsAlmostNumericAndPositionals(ParserTestCase):
1287 """Tests negative number args when almost numeric options are present"""
1288
1289 argument_signatures = [
1290 Sig('x', nargs='?'),
1291 Sig('-k4', dest='y', action='store_true'),
1292 ]
1293 failures = ['-k3']
1294 successes = [
1295 ('', NS(x=None, y=False)),
1296 ('-2', NS(x='-2', y=False)),
1297 ('a', NS(x='a', y=False)),
1298 ('-k4', NS(x=None, y=True)),
1299 ('-k4 a', NS(x='a', y=True)),
1300 ]
1301
1302
1303class TestEmptyAndSpaceContainingArguments(ParserTestCase):
1304
1305 argument_signatures = [
1306 Sig('x', nargs='?'),
1307 Sig('-y', '--yyy', dest='y'),
1308 ]
1309 failures = ['-y']
1310 successes = [
1311 ([''], NS(x='', y=None)),
1312 (['a badger'], NS(x='a badger', y=None)),
1313 (['-a badger'], NS(x='-a badger', y=None)),
1314 (['-y', ''], NS(x=None, y='')),
1315 (['-y', 'a badger'], NS(x=None, y='a badger')),
1316 (['-y', '-a badger'], NS(x=None, y='-a badger')),
1317 (['--yyy=a badger'], NS(x=None, y='a badger')),
1318 (['--yyy=-a badger'], NS(x=None, y='-a badger')),
1319 ]
1320
1321
1322class TestPrefixCharacterOnlyArguments(ParserTestCase):
1323
1324 parser_signature = Sig(prefix_chars='-+')
1325 argument_signatures = [
1326 Sig('-', dest='x', nargs='?', const='badger'),
1327 Sig('+', dest='y', type=int, default=42),
1328 Sig('-+-', dest='z', action='store_true'),
1329 ]
1330 failures = ['-y', '+ -']
1331 successes = [
1332 ('', NS(x=None, y=42, z=False)),
1333 ('-', NS(x='badger', y=42, z=False)),
1334 ('- X', NS(x='X', y=42, z=False)),
1335 ('+ -3', NS(x=None, y=-3, z=False)),
1336 ('-+-', NS(x=None, y=42, z=True)),
1337 ('- ===', NS(x='===', y=42, z=False)),
1338 ]
1339
1340
1341class TestNargsZeroOrMore(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +00001342 """Tests specifying args for an Optional that accepts zero or more"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001343
1344 argument_signatures = [Sig('-x', nargs='*'), Sig('y', nargs='*')]
1345 failures = []
1346 successes = [
1347 ('', NS(x=None, y=[])),
1348 ('-x', NS(x=[], y=[])),
1349 ('-x a', NS(x=['a'], y=[])),
1350 ('-x a -- b', NS(x=['a'], y=['b'])),
1351 ('a', NS(x=None, y=['a'])),
1352 ('a -x', NS(x=[], y=['a'])),
1353 ('a -x b', NS(x=['b'], y=['a'])),
1354 ]
1355
1356
1357class TestNargsRemainder(ParserTestCase):
1358 """Tests specifying a positional with nargs=REMAINDER"""
1359
1360 argument_signatures = [Sig('x'), Sig('y', nargs='...'), Sig('-z')]
1361 failures = ['', '-z', '-z Z']
1362 successes = [
1363 ('X', NS(x='X', y=[], z=None)),
1364 ('-z Z X', NS(x='X', y=[], z='Z')),
1365 ('X A B -z Z', NS(x='X', y=['A', 'B', '-z', 'Z'], z=None)),
1366 ('X Y --foo', NS(x='X', y=['Y', '--foo'], z=None)),
1367 ]
1368
1369
1370class TestOptionLike(ParserTestCase):
1371 """Tests options that may or may not be arguments"""
1372
1373 argument_signatures = [
1374 Sig('-x', type=float),
1375 Sig('-3', type=float, dest='y'),
1376 Sig('z', nargs='*'),
1377 ]
1378 failures = ['-x', '-y2.5', '-xa', '-x -a',
1379 '-x -3', '-x -3.5', '-3 -3.5',
1380 '-x -2.5', '-x -2.5 a', '-3 -.5',
1381 'a x -1', '-x -1 a', '-3 -1 a']
1382 successes = [
1383 ('', NS(x=None, y=None, z=[])),
1384 ('-x 2.5', NS(x=2.5, y=None, z=[])),
1385 ('-x 2.5 a', NS(x=2.5, y=None, z=['a'])),
1386 ('-3.5', NS(x=None, y=0.5, z=[])),
1387 ('-3-.5', NS(x=None, y=-0.5, z=[])),
1388 ('-3 .5', NS(x=None, y=0.5, z=[])),
1389 ('a -3.5', NS(x=None, y=0.5, z=['a'])),
1390 ('a', NS(x=None, y=None, z=['a'])),
1391 ('a -x 1', NS(x=1.0, y=None, z=['a'])),
1392 ('-x 1 a', NS(x=1.0, y=None, z=['a'])),
1393 ('-3 1 a', NS(x=None, y=1.0, z=['a'])),
1394 ]
1395
1396
1397class TestDefaultSuppress(ParserTestCase):
1398 """Test actions with suppressed defaults"""
1399
1400 argument_signatures = [
1401 Sig('foo', nargs='?', default=argparse.SUPPRESS),
1402 Sig('bar', nargs='*', default=argparse.SUPPRESS),
1403 Sig('--baz', action='store_true', default=argparse.SUPPRESS),
1404 ]
1405 failures = ['-x']
1406 successes = [
1407 ('', NS()),
1408 ('a', NS(foo='a')),
1409 ('a b', NS(foo='a', bar=['b'])),
1410 ('--baz', NS(baz=True)),
1411 ('a --baz', NS(foo='a', baz=True)),
1412 ('--baz a b', NS(foo='a', bar=['b'], baz=True)),
1413 ]
1414
1415
1416class TestParserDefaultSuppress(ParserTestCase):
1417 """Test actions with a parser-level default of SUPPRESS"""
1418
1419 parser_signature = Sig(argument_default=argparse.SUPPRESS)
1420 argument_signatures = [
1421 Sig('foo', nargs='?'),
1422 Sig('bar', nargs='*'),
1423 Sig('--baz', action='store_true'),
1424 ]
1425 failures = ['-x']
1426 successes = [
1427 ('', NS()),
1428 ('a', NS(foo='a')),
1429 ('a b', NS(foo='a', bar=['b'])),
1430 ('--baz', NS(baz=True)),
1431 ('a --baz', NS(foo='a', baz=True)),
1432 ('--baz a b', NS(foo='a', bar=['b'], baz=True)),
1433 ]
1434
1435
1436class TestParserDefault42(ParserTestCase):
1437 """Test actions with a parser-level default of 42"""
1438
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001439 parser_signature = Sig(argument_default=42)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001440 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001441 Sig('--version', action='version', version='1.0'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001442 Sig('foo', nargs='?'),
1443 Sig('bar', nargs='*'),
1444 Sig('--baz', action='store_true'),
1445 ]
1446 failures = ['-x']
1447 successes = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001448 ('', NS(foo=42, bar=42, baz=42, version=42)),
1449 ('a', NS(foo='a', bar=42, baz=42, version=42)),
1450 ('a b', NS(foo='a', bar=['b'], baz=42, version=42)),
1451 ('--baz', NS(foo=42, bar=42, baz=True, version=42)),
1452 ('a --baz', NS(foo='a', bar=42, baz=True, version=42)),
1453 ('--baz a b', NS(foo='a', bar=['b'], baz=True, version=42)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001454 ]
1455
1456
1457class TestArgumentsFromFile(TempDirMixin, ParserTestCase):
1458 """Test reading arguments from a file"""
1459
1460 def setUp(self):
1461 super(TestArgumentsFromFile, self).setUp()
1462 file_texts = [
1463 ('hello', 'hello world!\n'),
1464 ('recursive', '-a\n'
1465 'A\n'
1466 '@hello'),
1467 ('invalid', '@no-such-path\n'),
1468 ]
1469 for path, text in file_texts:
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001470 with open(path, 'w', encoding="utf-8") as file:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001471 file.write(text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001472
1473 parser_signature = Sig(fromfile_prefix_chars='@')
1474 argument_signatures = [
1475 Sig('-a'),
1476 Sig('x'),
1477 Sig('y', nargs='+'),
1478 ]
1479 failures = ['', '-b', 'X', '@invalid', '@missing']
1480 successes = [
1481 ('X Y', NS(a=None, x='X', y=['Y'])),
1482 ('X -a A Y Z', NS(a='A', x='X', y=['Y', 'Z'])),
1483 ('@hello X', NS(a=None, x='hello world!', y=['X'])),
1484 ('X @hello', NS(a=None, x='X', y=['hello world!'])),
1485 ('-a B @recursive Y Z', NS(a='A', x='hello world!', y=['Y', 'Z'])),
1486 ('X @recursive Z -a B', NS(a='B', x='X', y=['hello world!', 'Z'])),
R David Murrayb94082a2012-07-21 22:20:11 -04001487 (["-a", "", "X", "Y"], NS(a='', x='X', y=['Y'])),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001488 ]
1489
1490
1491class TestArgumentsFromFileConverter(TempDirMixin, ParserTestCase):
1492 """Test reading arguments from a file"""
1493
1494 def setUp(self):
1495 super(TestArgumentsFromFileConverter, self).setUp()
1496 file_texts = [
1497 ('hello', 'hello world!\n'),
1498 ]
1499 for path, text in file_texts:
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001500 with open(path, 'w', encoding="utf-8") as file:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001501 file.write(text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001502
1503 class FromFileConverterArgumentParser(ErrorRaisingArgumentParser):
1504
1505 def convert_arg_line_to_args(self, arg_line):
1506 for arg in arg_line.split():
1507 if not arg.strip():
1508 continue
1509 yield arg
1510 parser_class = FromFileConverterArgumentParser
1511 parser_signature = Sig(fromfile_prefix_chars='@')
1512 argument_signatures = [
1513 Sig('y', nargs='+'),
1514 ]
1515 failures = []
1516 successes = [
1517 ('@hello X', NS(y=['hello', 'world!', 'X'])),
1518 ]
1519
1520
1521# =====================
1522# Type conversion tests
1523# =====================
1524
1525class TestFileTypeRepr(TestCase):
1526
1527 def test_r(self):
1528 type = argparse.FileType('r')
1529 self.assertEqual("FileType('r')", repr(type))
1530
1531 def test_wb_1(self):
1532 type = argparse.FileType('wb', 1)
1533 self.assertEqual("FileType('wb', 1)", repr(type))
1534
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001535 def test_r_latin(self):
1536 type = argparse.FileType('r', encoding='latin_1')
1537 self.assertEqual("FileType('r', encoding='latin_1')", repr(type))
1538
1539 def test_w_big5_ignore(self):
1540 type = argparse.FileType('w', encoding='big5', errors='ignore')
1541 self.assertEqual("FileType('w', encoding='big5', errors='ignore')",
1542 repr(type))
1543
1544 def test_r_1_replace(self):
1545 type = argparse.FileType('r', 1, errors='replace')
1546 self.assertEqual("FileType('r', 1, errors='replace')", repr(type))
1547
Steve Dowerd0f49d22018-09-18 09:10:26 -07001548class StdStreamComparer:
1549 def __init__(self, attr):
1550 self.attr = attr
1551
1552 def __eq__(self, other):
1553 return other == getattr(sys, self.attr)
1554
1555eq_stdin = StdStreamComparer('stdin')
1556eq_stdout = StdStreamComparer('stdout')
1557eq_stderr = StdStreamComparer('stderr')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001558
1559class RFile(object):
1560 seen = {}
1561
1562 def __init__(self, name):
1563 self.name = name
1564
1565 def __eq__(self, other):
1566 if other in self.seen:
1567 text = self.seen[other]
1568 else:
1569 text = self.seen[other] = other.read()
1570 other.close()
1571 if not isinstance(text, str):
1572 text = text.decode('ascii')
1573 return self.name == other.name == text
1574
1575
1576class TestFileTypeR(TempDirMixin, ParserTestCase):
1577 """Test the FileType option/argument type for reading files"""
1578
1579 def setUp(self):
1580 super(TestFileTypeR, self).setUp()
1581 for file_name in ['foo', 'bar']:
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001582 with open(os.path.join(self.temp_dir, file_name),
1583 'w', encoding="utf-8") as file:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001584 file.write(file_name)
Steven Bethardb0270112011-01-24 21:02:50 +00001585 self.create_readonly_file('readonly')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001586
1587 argument_signatures = [
1588 Sig('-x', type=argparse.FileType()),
1589 Sig('spam', type=argparse.FileType('r')),
1590 ]
Steven Bethardb0270112011-01-24 21:02:50 +00001591 failures = ['-x', '', 'non-existent-file.txt']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001592 successes = [
1593 ('foo', NS(x=None, spam=RFile('foo'))),
1594 ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
1595 ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001596 ('-x - -', NS(x=eq_stdin, spam=eq_stdin)),
Steven Bethardb0270112011-01-24 21:02:50 +00001597 ('readonly', NS(x=None, spam=RFile('readonly'))),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001598 ]
1599
R David Murray6fb8fb12012-08-31 22:45:20 -04001600class TestFileTypeDefaults(TempDirMixin, ParserTestCase):
1601 """Test that a file is not created unless the default is needed"""
1602 def setUp(self):
1603 super(TestFileTypeDefaults, self).setUp()
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001604 file = open(os.path.join(self.temp_dir, 'good'), 'w', encoding="utf-8")
R David Murray6fb8fb12012-08-31 22:45:20 -04001605 file.write('good')
1606 file.close()
1607
1608 argument_signatures = [
1609 Sig('-c', type=argparse.FileType('r'), default='no-file.txt'),
1610 ]
1611 # should provoke no such file error
1612 failures = ['']
1613 # should not provoke error because default file is created
1614 successes = [('-c good', NS(c=RFile('good')))]
1615
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001616
1617class TestFileTypeRB(TempDirMixin, ParserTestCase):
1618 """Test the FileType option/argument type for reading files"""
1619
1620 def setUp(self):
1621 super(TestFileTypeRB, self).setUp()
1622 for file_name in ['foo', 'bar']:
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001623 with open(os.path.join(self.temp_dir, file_name),
1624 'w', encoding="utf-8") as file:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001625 file.write(file_name)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001626
1627 argument_signatures = [
1628 Sig('-x', type=argparse.FileType('rb')),
1629 Sig('spam', type=argparse.FileType('rb')),
1630 ]
1631 failures = ['-x', '']
1632 successes = [
1633 ('foo', NS(x=None, spam=RFile('foo'))),
1634 ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
1635 ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001636 ('-x - -', NS(x=eq_stdin, spam=eq_stdin)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001637 ]
1638
1639
1640class WFile(object):
1641 seen = set()
1642
1643 def __init__(self, name):
1644 self.name = name
1645
1646 def __eq__(self, other):
1647 if other not in self.seen:
1648 text = 'Check that file is writable.'
1649 if 'b' in other.mode:
1650 text = text.encode('ascii')
1651 other.write(text)
1652 other.close()
1653 self.seen.add(other)
1654 return self.name == other.name
1655
1656
Victor Stinnera04b39b2011-11-20 23:09:09 +01001657@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
1658 "non-root user required")
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001659class TestFileTypeW(TempDirMixin, ParserTestCase):
1660 """Test the FileType option/argument type for writing files"""
1661
Steven Bethardb0270112011-01-24 21:02:50 +00001662 def setUp(self):
1663 super(TestFileTypeW, self).setUp()
1664 self.create_readonly_file('readonly')
1665
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001666 argument_signatures = [
1667 Sig('-x', type=argparse.FileType('w')),
1668 Sig('spam', type=argparse.FileType('w')),
1669 ]
Steven Bethardb0270112011-01-24 21:02:50 +00001670 failures = ['-x', '', 'readonly']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001671 successes = [
1672 ('foo', NS(x=None, spam=WFile('foo'))),
1673 ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
1674 ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001675 ('-x - -', NS(x=eq_stdout, spam=eq_stdout)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001676 ]
1677
1678
1679class TestFileTypeWB(TempDirMixin, ParserTestCase):
1680
1681 argument_signatures = [
1682 Sig('-x', type=argparse.FileType('wb')),
1683 Sig('spam', type=argparse.FileType('wb')),
1684 ]
1685 failures = ['-x', '']
1686 successes = [
1687 ('foo', NS(x=None, spam=WFile('foo'))),
1688 ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
1689 ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001690 ('-x - -', NS(x=eq_stdout, spam=eq_stdout)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001691 ]
1692
1693
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001694class TestFileTypeOpenArgs(TestCase):
1695 """Test that open (the builtin) is correctly called"""
1696
1697 def test_open_args(self):
1698 FT = argparse.FileType
1699 cases = [
1700 (FT('rb'), ('rb', -1, None, None)),
1701 (FT('w', 1), ('w', 1, None, None)),
1702 (FT('w', errors='replace'), ('w', -1, None, 'replace')),
1703 (FT('wb', encoding='big5'), ('wb', -1, 'big5', None)),
1704 (FT('w', 0, 'l1', 'strict'), ('w', 0, 'l1', 'strict')),
1705 ]
1706 with mock.patch('builtins.open') as m:
1707 for type, args in cases:
1708 type('foo')
1709 m.assert_called_with('foo', *args)
1710
1711
zygocephalus03d58312019-06-07 23:08:36 +03001712class TestFileTypeMissingInitialization(TestCase):
1713 """
1714 Test that add_argument throws an error if FileType class
1715 object was passed instead of instance of FileType
1716 """
1717
1718 def test(self):
1719 parser = argparse.ArgumentParser()
1720 with self.assertRaises(ValueError) as cm:
1721 parser.add_argument('-x', type=argparse.FileType)
1722
1723 self.assertEqual(
1724 '%r is a FileType class object, instance of it must be passed'
1725 % (argparse.FileType,),
1726 str(cm.exception)
1727 )
1728
1729
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001730class TestTypeCallable(ParserTestCase):
1731 """Test some callables as option/argument types"""
1732
1733 argument_signatures = [
1734 Sig('--eggs', type=complex),
1735 Sig('spam', type=float),
1736 ]
1737 failures = ['a', '42j', '--eggs a', '--eggs 2i']
1738 successes = [
1739 ('--eggs=42 42', NS(eggs=42, spam=42.0)),
1740 ('--eggs 2j -- -1.5', NS(eggs=2j, spam=-1.5)),
1741 ('1024.675', NS(eggs=None, spam=1024.675)),
1742 ]
1743
1744
1745class TestTypeUserDefined(ParserTestCase):
1746 """Test a user-defined option/argument type"""
1747
1748 class MyType(TestCase):
1749
1750 def __init__(self, value):
1751 self.value = value
1752
1753 def __eq__(self, other):
1754 return (type(self), self.value) == (type(other), other.value)
1755
1756 argument_signatures = [
1757 Sig('-x', type=MyType),
1758 Sig('spam', type=MyType),
1759 ]
1760 failures = []
1761 successes = [
1762 ('a -x b', NS(x=MyType('b'), spam=MyType('a'))),
1763 ('-xf g', NS(x=MyType('f'), spam=MyType('g'))),
1764 ]
1765
1766
1767class TestTypeClassicClass(ParserTestCase):
1768 """Test a classic class type"""
1769
1770 class C:
1771
1772 def __init__(self, value):
1773 self.value = value
1774
1775 def __eq__(self, other):
1776 return (type(self), self.value) == (type(other), other.value)
1777
1778 argument_signatures = [
1779 Sig('-x', type=C),
1780 Sig('spam', type=C),
1781 ]
1782 failures = []
1783 successes = [
1784 ('a -x b', NS(x=C('b'), spam=C('a'))),
1785 ('-xf g', NS(x=C('f'), spam=C('g'))),
1786 ]
1787
1788
1789class TestTypeRegistration(TestCase):
1790 """Test a user-defined type by registering it"""
1791
1792 def test(self):
1793
1794 def get_my_type(string):
1795 return 'my_type{%s}' % string
1796
1797 parser = argparse.ArgumentParser()
1798 parser.register('type', 'my_type', get_my_type)
1799 parser.add_argument('-x', type='my_type')
1800 parser.add_argument('y', type='my_type')
1801
1802 self.assertEqual(parser.parse_args('1'.split()),
1803 NS(x=None, y='my_type{1}'))
1804 self.assertEqual(parser.parse_args('-x 1 42'.split()),
1805 NS(x='my_type{1}', y='my_type{42}'))
1806
1807
1808# ============
1809# Action tests
1810# ============
1811
1812class TestActionUserDefined(ParserTestCase):
1813 """Test a user-defined option/argument action"""
1814
1815 class OptionalAction(argparse.Action):
1816
1817 def __call__(self, parser, namespace, value, option_string=None):
1818 try:
1819 # check destination and option string
1820 assert self.dest == 'spam', 'dest: %s' % self.dest
1821 assert option_string == '-s', 'flag: %s' % option_string
1822 # when option is before argument, badger=2, and when
1823 # option is after argument, badger=<whatever was set>
1824 expected_ns = NS(spam=0.25)
1825 if value in [0.125, 0.625]:
1826 expected_ns.badger = 2
1827 elif value in [2.0]:
1828 expected_ns.badger = 84
1829 else:
1830 raise AssertionError('value: %s' % value)
1831 assert expected_ns == namespace, ('expected %s, got %s' %
1832 (expected_ns, namespace))
1833 except AssertionError:
1834 e = sys.exc_info()[1]
1835 raise ArgumentParserError('opt_action failed: %s' % e)
1836 setattr(namespace, 'spam', value)
1837
1838 class PositionalAction(argparse.Action):
1839
1840 def __call__(self, parser, namespace, value, option_string=None):
1841 try:
1842 assert option_string is None, ('option_string: %s' %
1843 option_string)
1844 # check destination
1845 assert self.dest == 'badger', 'dest: %s' % self.dest
1846 # when argument is before option, spam=0.25, and when
1847 # option is after argument, spam=<whatever was set>
1848 expected_ns = NS(badger=2)
1849 if value in [42, 84]:
1850 expected_ns.spam = 0.25
1851 elif value in [1]:
1852 expected_ns.spam = 0.625
1853 elif value in [2]:
1854 expected_ns.spam = 0.125
1855 else:
1856 raise AssertionError('value: %s' % value)
1857 assert expected_ns == namespace, ('expected %s, got %s' %
1858 (expected_ns, namespace))
1859 except AssertionError:
1860 e = sys.exc_info()[1]
1861 raise ArgumentParserError('arg_action failed: %s' % e)
1862 setattr(namespace, 'badger', value)
1863
1864 argument_signatures = [
1865 Sig('-s', dest='spam', action=OptionalAction,
1866 type=float, default=0.25),
1867 Sig('badger', action=PositionalAction,
1868 type=int, nargs='?', default=2),
1869 ]
1870 failures = []
1871 successes = [
1872 ('-s0.125', NS(spam=0.125, badger=2)),
1873 ('42', NS(spam=0.25, badger=42)),
1874 ('-s 0.625 1', NS(spam=0.625, badger=1)),
1875 ('84 -s2', NS(spam=2.0, badger=84)),
1876 ]
1877
1878
1879class TestActionRegistration(TestCase):
1880 """Test a user-defined action supplied by registering it"""
1881
1882 class MyAction(argparse.Action):
1883
1884 def __call__(self, parser, namespace, values, option_string=None):
1885 setattr(namespace, self.dest, 'foo[%s]' % values)
1886
1887 def test(self):
1888
1889 parser = argparse.ArgumentParser()
1890 parser.register('action', 'my_action', self.MyAction)
1891 parser.add_argument('badger', action='my_action')
1892
1893 self.assertEqual(parser.parse_args(['1']), NS(badger='foo[1]'))
1894 self.assertEqual(parser.parse_args(['42']), NS(badger='foo[42]'))
1895
1896
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001897class TestActionExtend(ParserTestCase):
1898 argument_signatures = [
1899 Sig('--foo', action="extend", nargs="+", type=str),
1900 ]
1901 failures = ()
1902 successes = [
1903 ('--foo f1 --foo f2 f3 f4', NS(foo=['f1', 'f2', 'f3', 'f4'])),
1904 ]
1905
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001906# ================
1907# Subparsers tests
1908# ================
1909
1910class TestAddSubparsers(TestCase):
1911 """Test the add_subparsers method"""
1912
1913 def assertArgumentParserError(self, *args, **kwargs):
1914 self.assertRaises(ArgumentParserError, *args, **kwargs)
1915
Steven Bethardfd311a72010-12-18 11:19:23 +00001916 def _get_parser(self, subparser_help=False, prefix_chars=None,
1917 aliases=False):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001918 # create a parser with a subparsers argument
R. David Murray88c49fe2010-08-03 17:56:09 +00001919 if prefix_chars:
1920 parser = ErrorRaisingArgumentParser(
1921 prog='PROG', description='main description', prefix_chars=prefix_chars)
1922 parser.add_argument(
1923 prefix_chars[0] * 2 + 'foo', action='store_true', help='foo help')
1924 else:
1925 parser = ErrorRaisingArgumentParser(
1926 prog='PROG', description='main description')
1927 parser.add_argument(
1928 '--foo', action='store_true', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001929 parser.add_argument(
1930 'bar', type=float, help='bar help')
1931
1932 # check that only one subparsers argument can be added
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001933 subparsers_kwargs = {'required': False}
Steven Bethardfd311a72010-12-18 11:19:23 +00001934 if aliases:
1935 subparsers_kwargs['metavar'] = 'COMMAND'
1936 subparsers_kwargs['title'] = 'commands'
1937 else:
1938 subparsers_kwargs['help'] = 'command help'
1939 subparsers = parser.add_subparsers(**subparsers_kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001940 self.assertArgumentParserError(parser.add_subparsers)
1941
1942 # add first sub-parser
1943 parser1_kwargs = dict(description='1 description')
1944 if subparser_help:
1945 parser1_kwargs['help'] = '1 help'
Steven Bethardfd311a72010-12-18 11:19:23 +00001946 if aliases:
1947 parser1_kwargs['aliases'] = ['1alias1', '1alias2']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001948 parser1 = subparsers.add_parser('1', **parser1_kwargs)
1949 parser1.add_argument('-w', type=int, help='w help')
1950 parser1.add_argument('x', choices='abc', help='x help')
1951
1952 # add second sub-parser
1953 parser2_kwargs = dict(description='2 description')
1954 if subparser_help:
1955 parser2_kwargs['help'] = '2 help'
1956 parser2 = subparsers.add_parser('2', **parser2_kwargs)
1957 parser2.add_argument('-y', choices='123', help='y help')
1958 parser2.add_argument('z', type=complex, nargs='*', help='z help')
1959
R David Murray00528e82012-07-21 22:48:35 -04001960 # add third sub-parser
1961 parser3_kwargs = dict(description='3 description')
1962 if subparser_help:
1963 parser3_kwargs['help'] = '3 help'
1964 parser3 = subparsers.add_parser('3', **parser3_kwargs)
1965 parser3.add_argument('t', type=int, help='t help')
1966 parser3.add_argument('u', nargs='...', help='u help')
1967
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001968 # return the main parser
1969 return parser
1970
1971 def setUp(self):
Steven Bethard1f1c2472010-11-01 13:56:09 +00001972 super().setUp()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001973 self.parser = self._get_parser()
1974 self.command_help_parser = self._get_parser(subparser_help=True)
1975
1976 def test_parse_args_failures(self):
1977 # check some failure cases:
1978 for args_str in ['', 'a', 'a a', '0.5 a', '0.5 1',
1979 '0.5 1 -y', '0.5 2 -w']:
1980 args = args_str.split()
1981 self.assertArgumentParserError(self.parser.parse_args, args)
1982
1983 def test_parse_args(self):
1984 # check some non-failure cases:
1985 self.assertEqual(
1986 self.parser.parse_args('0.5 1 b -w 7'.split()),
1987 NS(foo=False, bar=0.5, w=7, x='b'),
1988 )
1989 self.assertEqual(
1990 self.parser.parse_args('0.25 --foo 2 -y 2 3j -- -1j'.split()),
1991 NS(foo=True, bar=0.25, y='2', z=[3j, -1j]),
1992 )
1993 self.assertEqual(
1994 self.parser.parse_args('--foo 0.125 1 c'.split()),
1995 NS(foo=True, bar=0.125, w=None, x='c'),
1996 )
R David Murray00528e82012-07-21 22:48:35 -04001997 self.assertEqual(
1998 self.parser.parse_args('-1.5 3 11 -- a --foo 7 -- b'.split()),
1999 NS(foo=False, bar=-1.5, t=11, u=['a', '--foo', '7', '--', 'b']),
2000 )
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002001
Steven Bethardfca2e8a2010-11-02 12:47:22 +00002002 def test_parse_known_args(self):
2003 self.assertEqual(
2004 self.parser.parse_known_args('0.5 1 b -w 7'.split()),
2005 (NS(foo=False, bar=0.5, w=7, x='b'), []),
2006 )
2007 self.assertEqual(
2008 self.parser.parse_known_args('0.5 -p 1 b -w 7'.split()),
2009 (NS(foo=False, bar=0.5, w=7, x='b'), ['-p']),
2010 )
2011 self.assertEqual(
2012 self.parser.parse_known_args('0.5 1 b -w 7 -p'.split()),
2013 (NS(foo=False, bar=0.5, w=7, x='b'), ['-p']),
2014 )
2015 self.assertEqual(
2016 self.parser.parse_known_args('0.5 1 b -q -rs -w 7'.split()),
2017 (NS(foo=False, bar=0.5, w=7, x='b'), ['-q', '-rs']),
2018 )
2019 self.assertEqual(
2020 self.parser.parse_known_args('0.5 -W 1 b -X Y -w 7 Z'.split()),
2021 (NS(foo=False, bar=0.5, w=7, x='b'), ['-W', '-X', 'Y', 'Z']),
2022 )
2023
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002024 def test_dest(self):
2025 parser = ErrorRaisingArgumentParser()
2026 parser.add_argument('--foo', action='store_true')
2027 subparsers = parser.add_subparsers(dest='bar')
2028 parser1 = subparsers.add_parser('1')
2029 parser1.add_argument('baz')
2030 self.assertEqual(NS(foo=False, bar='1', baz='2'),
2031 parser.parse_args('1 2'.split()))
2032
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07002033 def _test_required_subparsers(self, parser):
2034 # Should parse the sub command
2035 ret = parser.parse_args(['run'])
2036 self.assertEqual(ret.command, 'run')
2037
2038 # Error when the command is missing
2039 self.assertArgumentParserError(parser.parse_args, ())
2040
2041 def test_required_subparsers_via_attribute(self):
2042 parser = ErrorRaisingArgumentParser()
2043 subparsers = parser.add_subparsers(dest='command')
2044 subparsers.required = True
2045 subparsers.add_parser('run')
2046 self._test_required_subparsers(parser)
2047
2048 def test_required_subparsers_via_kwarg(self):
2049 parser = ErrorRaisingArgumentParser()
2050 subparsers = parser.add_subparsers(dest='command', required=True)
2051 subparsers.add_parser('run')
2052 self._test_required_subparsers(parser)
2053
2054 def test_required_subparsers_default(self):
2055 parser = ErrorRaisingArgumentParser()
2056 subparsers = parser.add_subparsers(dest='command')
2057 subparsers.add_parser('run')
Ned Deily8ebf5ce2018-05-23 21:55:15 -04002058 # No error here
2059 ret = parser.parse_args(())
2060 self.assertIsNone(ret.command)
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07002061
Miss Islington (bot)c5899922021-07-23 06:27:05 -07002062 def test_required_subparsers_no_destination_error(self):
2063 parser = ErrorRaisingArgumentParser()
2064 subparsers = parser.add_subparsers(required=True)
2065 subparsers.add_parser('foo')
2066 subparsers.add_parser('bar')
2067 with self.assertRaises(ArgumentParserError) as excinfo:
2068 parser.parse_args(())
2069 self.assertRegex(
2070 excinfo.exception.stderr,
2071 'error: the following arguments are required: {foo,bar}\n$'
2072 )
2073
2074 def test_wrong_argument_subparsers_no_destination_error(self):
2075 parser = ErrorRaisingArgumentParser()
2076 subparsers = parser.add_subparsers(required=True)
2077 subparsers.add_parser('foo')
2078 subparsers.add_parser('bar')
2079 with self.assertRaises(ArgumentParserError) as excinfo:
2080 parser.parse_args(('baz',))
2081 self.assertRegex(
2082 excinfo.exception.stderr,
2083 r"error: argument {foo,bar}: invalid choice: 'baz' \(choose from 'foo', 'bar'\)\n$"
2084 )
2085
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07002086 def test_optional_subparsers(self):
2087 parser = ErrorRaisingArgumentParser()
2088 subparsers = parser.add_subparsers(dest='command', required=False)
2089 subparsers.add_parser('run')
2090 # No error here
2091 ret = parser.parse_args(())
2092 self.assertIsNone(ret.command)
2093
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002094 def test_help(self):
2095 self.assertEqual(self.parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002096 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002097 self.assertEqual(self.parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002098 usage: PROG [-h] [--foo] bar {1,2,3} ...
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002099
2100 main description
2101
2102 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002103 bar bar help
2104 {1,2,3} command help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002105
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002106 options:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002107 -h, --help show this help message and exit
2108 --foo foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002109 '''))
2110
R. David Murray88c49fe2010-08-03 17:56:09 +00002111 def test_help_extra_prefix_chars(self):
2112 # Make sure - is still used for help if it is a non-first prefix char
2113 parser = self._get_parser(prefix_chars='+:-')
2114 self.assertEqual(parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002115 'usage: PROG [-h] [++foo] bar {1,2,3} ...\n')
R. David Murray88c49fe2010-08-03 17:56:09 +00002116 self.assertEqual(parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002117 usage: PROG [-h] [++foo] bar {1,2,3} ...
R. David Murray88c49fe2010-08-03 17:56:09 +00002118
2119 main description
2120
2121 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002122 bar bar help
2123 {1,2,3} command help
R. David Murray88c49fe2010-08-03 17:56:09 +00002124
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002125 options:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002126 -h, --help show this help message and exit
2127 ++foo foo help
R. David Murray88c49fe2010-08-03 17:56:09 +00002128 '''))
2129
Xiang Zhang7fe28ad2017-01-22 14:37:22 +08002130 def test_help_non_breaking_spaces(self):
2131 parser = ErrorRaisingArgumentParser(
2132 prog='PROG', description='main description')
2133 parser.add_argument(
2134 "--non-breaking", action='store_false',
2135 help='help message containing non-breaking spaces shall not '
2136 'wrap\N{NO-BREAK SPACE}at non-breaking spaces')
2137 self.assertEqual(parser.format_help(), textwrap.dedent('''\
2138 usage: PROG [-h] [--non-breaking]
2139
2140 main description
2141
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002142 options:
Xiang Zhang7fe28ad2017-01-22 14:37:22 +08002143 -h, --help show this help message and exit
2144 --non-breaking help message containing non-breaking spaces shall not
2145 wrap\N{NO-BREAK SPACE}at non-breaking spaces
2146 '''))
R. David Murray88c49fe2010-08-03 17:56:09 +00002147
Miss Islington (bot)fd2be6d2021-10-13 10:15:43 -07002148 def test_help_blank(self):
2149 # Issue 24444
2150 parser = ErrorRaisingArgumentParser(
2151 prog='PROG', description='main description')
2152 parser.add_argument(
2153 'foo',
2154 help=' ')
2155 self.assertEqual(parser.format_help(), textwrap.dedent('''\
2156 usage: PROG [-h] foo
2157
2158 main description
2159
2160 positional arguments:
2161 foo
2162
2163 options:
2164 -h, --help show this help message and exit
2165 '''))
2166
2167 parser = ErrorRaisingArgumentParser(
2168 prog='PROG', description='main description')
2169 parser.add_argument(
2170 'foo', choices=[],
2171 help='%(choices)s')
2172 self.assertEqual(parser.format_help(), textwrap.dedent('''\
2173 usage: PROG [-h] {}
2174
2175 main description
2176
2177 positional arguments:
2178 {}
2179
2180 options:
2181 -h, --help show this help message and exit
2182 '''))
2183
R. David Murray88c49fe2010-08-03 17:56:09 +00002184 def test_help_alternate_prefix_chars(self):
2185 parser = self._get_parser(prefix_chars='+:/')
2186 self.assertEqual(parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002187 'usage: PROG [+h] [++foo] bar {1,2,3} ...\n')
R. David Murray88c49fe2010-08-03 17:56:09 +00002188 self.assertEqual(parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002189 usage: PROG [+h] [++foo] bar {1,2,3} ...
R. David Murray88c49fe2010-08-03 17:56:09 +00002190
2191 main description
2192
2193 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002194 bar bar help
2195 {1,2,3} command help
R. David Murray88c49fe2010-08-03 17:56:09 +00002196
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002197 options:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002198 +h, ++help show this help message and exit
2199 ++foo foo help
R. David Murray88c49fe2010-08-03 17:56:09 +00002200 '''))
2201
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002202 def test_parser_command_help(self):
2203 self.assertEqual(self.command_help_parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002204 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002205 self.assertEqual(self.command_help_parser.format_help(),
2206 textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002207 usage: PROG [-h] [--foo] bar {1,2,3} ...
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002208
2209 main description
2210
2211 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002212 bar bar help
2213 {1,2,3} command help
2214 1 1 help
2215 2 2 help
2216 3 3 help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002217
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002218 options:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002219 -h, --help show this help message and exit
2220 --foo foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002221 '''))
2222
2223 def test_subparser_title_help(self):
2224 parser = ErrorRaisingArgumentParser(prog='PROG',
2225 description='main description')
2226 parser.add_argument('--foo', action='store_true', help='foo help')
2227 parser.add_argument('bar', help='bar help')
2228 subparsers = parser.add_subparsers(title='subcommands',
2229 description='command help',
2230 help='additional text')
2231 parser1 = subparsers.add_parser('1')
2232 parser2 = subparsers.add_parser('2')
2233 self.assertEqual(parser.format_usage(),
2234 'usage: PROG [-h] [--foo] bar {1,2} ...\n')
2235 self.assertEqual(parser.format_help(), textwrap.dedent('''\
2236 usage: PROG [-h] [--foo] bar {1,2} ...
2237
2238 main description
2239
2240 positional arguments:
2241 bar bar help
2242
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002243 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002244 -h, --help show this help message and exit
2245 --foo foo help
2246
2247 subcommands:
2248 command help
2249
2250 {1,2} additional text
2251 '''))
2252
2253 def _test_subparser_help(self, args_str, expected_help):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002254 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002255 self.parser.parse_args(args_str.split())
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002256 self.assertEqual(expected_help, cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002257
2258 def test_subparser1_help(self):
2259 self._test_subparser_help('5.0 1 -h', textwrap.dedent('''\
2260 usage: PROG bar 1 [-h] [-w W] {a,b,c}
2261
2262 1 description
2263
2264 positional arguments:
2265 {a,b,c} x help
2266
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002267 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002268 -h, --help show this help message and exit
2269 -w W w help
2270 '''))
2271
2272 def test_subparser2_help(self):
2273 self._test_subparser_help('5.0 2 -h', textwrap.dedent('''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08002274 usage: PROG bar 2 [-h] [-y {1,2,3}] [z ...]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002275
2276 2 description
2277
2278 positional arguments:
2279 z z help
2280
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002281 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002282 -h, --help show this help message and exit
2283 -y {1,2,3} y help
2284 '''))
2285
Steven Bethardfd311a72010-12-18 11:19:23 +00002286 def test_alias_invocation(self):
2287 parser = self._get_parser(aliases=True)
2288 self.assertEqual(
2289 parser.parse_known_args('0.5 1alias1 b'.split()),
2290 (NS(foo=False, bar=0.5, w=None, x='b'), []),
2291 )
2292 self.assertEqual(
2293 parser.parse_known_args('0.5 1alias2 b'.split()),
2294 (NS(foo=False, bar=0.5, w=None, x='b'), []),
2295 )
2296
2297 def test_error_alias_invocation(self):
2298 parser = self._get_parser(aliases=True)
2299 self.assertArgumentParserError(parser.parse_args,
2300 '0.5 1alias3 b'.split())
2301
2302 def test_alias_help(self):
2303 parser = self._get_parser(aliases=True, subparser_help=True)
2304 self.maxDiff = None
2305 self.assertEqual(parser.format_help(), textwrap.dedent("""\
2306 usage: PROG [-h] [--foo] bar COMMAND ...
2307
2308 main description
2309
2310 positional arguments:
2311 bar bar help
2312
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002313 options:
Steven Bethardfd311a72010-12-18 11:19:23 +00002314 -h, --help show this help message and exit
2315 --foo foo help
2316
2317 commands:
2318 COMMAND
2319 1 (1alias1, 1alias2)
2320 1 help
2321 2 2 help
R David Murray00528e82012-07-21 22:48:35 -04002322 3 3 help
Steven Bethardfd311a72010-12-18 11:19:23 +00002323 """))
2324
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002325# ============
2326# Groups tests
2327# ============
2328
2329class TestPositionalsGroups(TestCase):
2330 """Tests that order of group positionals matches construction order"""
2331
2332 def test_nongroup_first(self):
2333 parser = ErrorRaisingArgumentParser()
2334 parser.add_argument('foo')
2335 group = parser.add_argument_group('g')
2336 group.add_argument('bar')
2337 parser.add_argument('baz')
2338 expected = NS(foo='1', bar='2', baz='3')
2339 result = parser.parse_args('1 2 3'.split())
2340 self.assertEqual(expected, result)
2341
2342 def test_group_first(self):
2343 parser = ErrorRaisingArgumentParser()
2344 group = parser.add_argument_group('xxx')
2345 group.add_argument('foo')
2346 parser.add_argument('bar')
2347 parser.add_argument('baz')
2348 expected = NS(foo='1', bar='2', baz='3')
2349 result = parser.parse_args('1 2 3'.split())
2350 self.assertEqual(expected, result)
2351
2352 def test_interleaved_groups(self):
2353 parser = ErrorRaisingArgumentParser()
2354 group = parser.add_argument_group('xxx')
2355 parser.add_argument('foo')
2356 group.add_argument('bar')
2357 parser.add_argument('baz')
2358 group = parser.add_argument_group('yyy')
2359 group.add_argument('frell')
2360 expected = NS(foo='1', bar='2', baz='3', frell='4')
2361 result = parser.parse_args('1 2 3 4'.split())
2362 self.assertEqual(expected, result)
2363
2364# ===================
2365# Parent parser tests
2366# ===================
2367
2368class TestParentParsers(TestCase):
2369 """Tests that parsers can be created with parent parsers"""
2370
2371 def assertArgumentParserError(self, *args, **kwargs):
2372 self.assertRaises(ArgumentParserError, *args, **kwargs)
2373
2374 def setUp(self):
Steven Bethard1f1c2472010-11-01 13:56:09 +00002375 super().setUp()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002376 self.wxyz_parent = ErrorRaisingArgumentParser(add_help=False)
2377 self.wxyz_parent.add_argument('--w')
2378 x_group = self.wxyz_parent.add_argument_group('x')
2379 x_group.add_argument('-y')
2380 self.wxyz_parent.add_argument('z')
2381
2382 self.abcd_parent = ErrorRaisingArgumentParser(add_help=False)
2383 self.abcd_parent.add_argument('a')
2384 self.abcd_parent.add_argument('-b')
2385 c_group = self.abcd_parent.add_argument_group('c')
2386 c_group.add_argument('--d')
2387
2388 self.w_parent = ErrorRaisingArgumentParser(add_help=False)
2389 self.w_parent.add_argument('--w')
2390
2391 self.z_parent = ErrorRaisingArgumentParser(add_help=False)
2392 self.z_parent.add_argument('z')
2393
2394 # parents with mutually exclusive groups
2395 self.ab_mutex_parent = ErrorRaisingArgumentParser(add_help=False)
2396 group = self.ab_mutex_parent.add_mutually_exclusive_group()
2397 group.add_argument('-a', action='store_true')
2398 group.add_argument('-b', action='store_true')
2399
2400 self.main_program = os.path.basename(sys.argv[0])
2401
2402 def test_single_parent(self):
2403 parser = ErrorRaisingArgumentParser(parents=[self.wxyz_parent])
2404 self.assertEqual(parser.parse_args('-y 1 2 --w 3'.split()),
2405 NS(w='3', y='1', z='2'))
2406
2407 def test_single_parent_mutex(self):
2408 self._test_mutex_ab(self.ab_mutex_parent.parse_args)
2409 parser = ErrorRaisingArgumentParser(parents=[self.ab_mutex_parent])
2410 self._test_mutex_ab(parser.parse_args)
2411
2412 def test_single_granparent_mutex(self):
2413 parents = [self.ab_mutex_parent]
2414 parser = ErrorRaisingArgumentParser(add_help=False, parents=parents)
2415 parser = ErrorRaisingArgumentParser(parents=[parser])
2416 self._test_mutex_ab(parser.parse_args)
2417
2418 def _test_mutex_ab(self, parse_args):
2419 self.assertEqual(parse_args([]), NS(a=False, b=False))
2420 self.assertEqual(parse_args(['-a']), NS(a=True, b=False))
2421 self.assertEqual(parse_args(['-b']), NS(a=False, b=True))
2422 self.assertArgumentParserError(parse_args, ['-a', '-b'])
2423 self.assertArgumentParserError(parse_args, ['-b', '-a'])
2424 self.assertArgumentParserError(parse_args, ['-c'])
2425 self.assertArgumentParserError(parse_args, ['-a', '-c'])
2426 self.assertArgumentParserError(parse_args, ['-b', '-c'])
2427
2428 def test_multiple_parents(self):
2429 parents = [self.abcd_parent, self.wxyz_parent]
2430 parser = ErrorRaisingArgumentParser(parents=parents)
2431 self.assertEqual(parser.parse_args('--d 1 --w 2 3 4'.split()),
2432 NS(a='3', b=None, d='1', w='2', y=None, z='4'))
2433
2434 def test_multiple_parents_mutex(self):
2435 parents = [self.ab_mutex_parent, self.wxyz_parent]
2436 parser = ErrorRaisingArgumentParser(parents=parents)
2437 self.assertEqual(parser.parse_args('-a --w 2 3'.split()),
2438 NS(a=True, b=False, w='2', y=None, z='3'))
2439 self.assertArgumentParserError(
2440 parser.parse_args, '-a --w 2 3 -b'.split())
2441 self.assertArgumentParserError(
2442 parser.parse_args, '-a -b --w 2 3'.split())
2443
2444 def test_conflicting_parents(self):
2445 self.assertRaises(
2446 argparse.ArgumentError,
2447 argparse.ArgumentParser,
2448 parents=[self.w_parent, self.wxyz_parent])
2449
2450 def test_conflicting_parents_mutex(self):
2451 self.assertRaises(
2452 argparse.ArgumentError,
2453 argparse.ArgumentParser,
2454 parents=[self.abcd_parent, self.ab_mutex_parent])
2455
2456 def test_same_argument_name_parents(self):
2457 parents = [self.wxyz_parent, self.z_parent]
2458 parser = ErrorRaisingArgumentParser(parents=parents)
2459 self.assertEqual(parser.parse_args('1 2'.split()),
2460 NS(w=None, y=None, z='2'))
2461
2462 def test_subparser_parents(self):
2463 parser = ErrorRaisingArgumentParser()
2464 subparsers = parser.add_subparsers()
2465 abcde_parser = subparsers.add_parser('bar', parents=[self.abcd_parent])
2466 abcde_parser.add_argument('e')
2467 self.assertEqual(parser.parse_args('bar -b 1 --d 2 3 4'.split()),
2468 NS(a='3', b='1', d='2', e='4'))
2469
2470 def test_subparser_parents_mutex(self):
2471 parser = ErrorRaisingArgumentParser()
2472 subparsers = parser.add_subparsers()
2473 parents = [self.ab_mutex_parent]
2474 abc_parser = subparsers.add_parser('foo', parents=parents)
2475 c_group = abc_parser.add_argument_group('c_group')
2476 c_group.add_argument('c')
2477 parents = [self.wxyz_parent, self.ab_mutex_parent]
2478 wxyzabe_parser = subparsers.add_parser('bar', parents=parents)
2479 wxyzabe_parser.add_argument('e')
2480 self.assertEqual(parser.parse_args('foo -a 4'.split()),
2481 NS(a=True, b=False, c='4'))
2482 self.assertEqual(parser.parse_args('bar -b --w 2 3 4'.split()),
2483 NS(a=False, b=True, w='2', y=None, z='3', e='4'))
2484 self.assertArgumentParserError(
2485 parser.parse_args, 'foo -a -b 4'.split())
2486 self.assertArgumentParserError(
2487 parser.parse_args, 'bar -b -a 4'.split())
2488
2489 def test_parent_help(self):
2490 parents = [self.abcd_parent, self.wxyz_parent]
2491 parser = ErrorRaisingArgumentParser(parents=parents)
2492 parser_help = parser.format_help()
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002493 progname = self.main_program
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002494 self.assertEqual(parser_help, textwrap.dedent('''\
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002495 usage: {}{}[-h] [-b B] [--d D] [--w W] [-y Y] a z
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002496
2497 positional arguments:
2498 a
2499 z
2500
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002501 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002502 -h, --help show this help message and exit
2503 -b B
2504 --w W
2505
2506 c:
2507 --d D
2508
2509 x:
2510 -y Y
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002511 '''.format(progname, ' ' if progname else '' )))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002512
2513 def test_groups_parents(self):
2514 parent = ErrorRaisingArgumentParser(add_help=False)
2515 g = parent.add_argument_group(title='g', description='gd')
2516 g.add_argument('-w')
2517 g.add_argument('-x')
2518 m = parent.add_mutually_exclusive_group()
2519 m.add_argument('-y')
2520 m.add_argument('-z')
2521 parser = ErrorRaisingArgumentParser(parents=[parent])
2522
2523 self.assertRaises(ArgumentParserError, parser.parse_args,
2524 ['-y', 'Y', '-z', 'Z'])
2525
2526 parser_help = parser.format_help()
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002527 progname = self.main_program
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002528 self.assertEqual(parser_help, textwrap.dedent('''\
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002529 usage: {}{}[-h] [-w W] [-x X] [-y Y | -z Z]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002530
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002531 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002532 -h, --help show this help message and exit
2533 -y Y
2534 -z Z
2535
2536 g:
2537 gd
2538
2539 -w W
2540 -x X
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002541 '''.format(progname, ' ' if progname else '' )))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002542
2543# ==============================
2544# Mutually exclusive group tests
2545# ==============================
2546
2547class TestMutuallyExclusiveGroupErrors(TestCase):
2548
2549 def test_invalid_add_argument_group(self):
2550 parser = ErrorRaisingArgumentParser()
2551 raises = self.assertRaises
2552 raises(TypeError, parser.add_mutually_exclusive_group, title='foo')
2553
2554 def test_invalid_add_argument(self):
2555 parser = ErrorRaisingArgumentParser()
2556 group = parser.add_mutually_exclusive_group()
2557 add_argument = group.add_argument
2558 raises = self.assertRaises
2559 raises(ValueError, add_argument, '--foo', required=True)
2560 raises(ValueError, add_argument, 'bar')
2561 raises(ValueError, add_argument, 'bar', nargs='+')
2562 raises(ValueError, add_argument, 'bar', nargs=1)
2563 raises(ValueError, add_argument, 'bar', nargs=argparse.PARSER)
2564
Steven Bethard49998ee2010-11-01 16:29:26 +00002565 def test_help(self):
2566 parser = ErrorRaisingArgumentParser(prog='PROG')
2567 group1 = parser.add_mutually_exclusive_group()
2568 group1.add_argument('--foo', action='store_true')
2569 group1.add_argument('--bar', action='store_false')
2570 group2 = parser.add_mutually_exclusive_group()
2571 group2.add_argument('--soup', action='store_true')
2572 group2.add_argument('--nuts', action='store_false')
2573 expected = '''\
2574 usage: PROG [-h] [--foo | --bar] [--soup | --nuts]
2575
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002576 options:
Steven Bethard49998ee2010-11-01 16:29:26 +00002577 -h, --help show this help message and exit
2578 --foo
2579 --bar
2580 --soup
2581 --nuts
2582 '''
2583 self.assertEqual(parser.format_help(), textwrap.dedent(expected))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002584
2585class MEMixin(object):
2586
2587 def test_failures_when_not_required(self):
2588 parse_args = self.get_parser(required=False).parse_args
2589 error = ArgumentParserError
2590 for args_string in self.failures:
2591 self.assertRaises(error, parse_args, args_string.split())
2592
2593 def test_failures_when_required(self):
2594 parse_args = self.get_parser(required=True).parse_args
2595 error = ArgumentParserError
2596 for args_string in self.failures + ['']:
2597 self.assertRaises(error, parse_args, args_string.split())
2598
2599 def test_successes_when_not_required(self):
2600 parse_args = self.get_parser(required=False).parse_args
2601 successes = self.successes + self.successes_when_not_required
2602 for args_string, expected_ns in successes:
2603 actual_ns = parse_args(args_string.split())
2604 self.assertEqual(actual_ns, expected_ns)
2605
2606 def test_successes_when_required(self):
2607 parse_args = self.get_parser(required=True).parse_args
2608 for args_string, expected_ns in self.successes:
2609 actual_ns = parse_args(args_string.split())
2610 self.assertEqual(actual_ns, expected_ns)
2611
2612 def test_usage_when_not_required(self):
2613 format_usage = self.get_parser(required=False).format_usage
2614 expected_usage = self.usage_when_not_required
2615 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))
2616
2617 def test_usage_when_required(self):
2618 format_usage = self.get_parser(required=True).format_usage
2619 expected_usage = self.usage_when_required
2620 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))
2621
2622 def test_help_when_not_required(self):
2623 format_help = self.get_parser(required=False).format_help
2624 help = self.usage_when_not_required + self.help
2625 self.assertEqual(format_help(), textwrap.dedent(help))
2626
2627 def test_help_when_required(self):
2628 format_help = self.get_parser(required=True).format_help
2629 help = self.usage_when_required + self.help
2630 self.assertEqual(format_help(), textwrap.dedent(help))
2631
2632
2633class TestMutuallyExclusiveSimple(MEMixin, TestCase):
2634
2635 def get_parser(self, required=None):
2636 parser = ErrorRaisingArgumentParser(prog='PROG')
2637 group = parser.add_mutually_exclusive_group(required=required)
2638 group.add_argument('--bar', help='bar help')
2639 group.add_argument('--baz', nargs='?', const='Z', help='baz help')
2640 return parser
2641
2642 failures = ['--bar X --baz Y', '--bar X --baz']
2643 successes = [
2644 ('--bar X', NS(bar='X', baz=None)),
2645 ('--bar X --bar Z', NS(bar='Z', baz=None)),
2646 ('--baz Y', NS(bar=None, baz='Y')),
2647 ('--baz', NS(bar=None, baz='Z')),
2648 ]
2649 successes_when_not_required = [
2650 ('', NS(bar=None, baz=None)),
2651 ]
2652
2653 usage_when_not_required = '''\
2654 usage: PROG [-h] [--bar BAR | --baz [BAZ]]
2655 '''
2656 usage_when_required = '''\
2657 usage: PROG [-h] (--bar BAR | --baz [BAZ])
2658 '''
2659 help = '''\
2660
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002661 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002662 -h, --help show this help message and exit
2663 --bar BAR bar help
2664 --baz [BAZ] baz help
2665 '''
2666
2667
2668class TestMutuallyExclusiveLong(MEMixin, TestCase):
2669
2670 def get_parser(self, required=None):
2671 parser = ErrorRaisingArgumentParser(prog='PROG')
2672 parser.add_argument('--abcde', help='abcde help')
2673 parser.add_argument('--fghij', help='fghij help')
2674 group = parser.add_mutually_exclusive_group(required=required)
2675 group.add_argument('--klmno', help='klmno help')
2676 group.add_argument('--pqrst', help='pqrst help')
2677 return parser
2678
2679 failures = ['--klmno X --pqrst Y']
2680 successes = [
2681 ('--klmno X', NS(abcde=None, fghij=None, klmno='X', pqrst=None)),
2682 ('--abcde Y --klmno X',
2683 NS(abcde='Y', fghij=None, klmno='X', pqrst=None)),
2684 ('--pqrst X', NS(abcde=None, fghij=None, klmno=None, pqrst='X')),
2685 ('--pqrst X --fghij Y',
2686 NS(abcde=None, fghij='Y', klmno=None, pqrst='X')),
2687 ]
2688 successes_when_not_required = [
2689 ('', NS(abcde=None, fghij=None, klmno=None, pqrst=None)),
2690 ]
2691
2692 usage_when_not_required = '''\
2693 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]
2694 [--klmno KLMNO | --pqrst PQRST]
2695 '''
2696 usage_when_required = '''\
2697 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]
2698 (--klmno KLMNO | --pqrst PQRST)
2699 '''
2700 help = '''\
2701
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002702 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002703 -h, --help show this help message and exit
2704 --abcde ABCDE abcde help
2705 --fghij FGHIJ fghij help
2706 --klmno KLMNO klmno help
2707 --pqrst PQRST pqrst help
2708 '''
2709
2710
2711class TestMutuallyExclusiveFirstSuppressed(MEMixin, TestCase):
2712
2713 def get_parser(self, required):
2714 parser = ErrorRaisingArgumentParser(prog='PROG')
2715 group = parser.add_mutually_exclusive_group(required=required)
2716 group.add_argument('-x', help=argparse.SUPPRESS)
2717 group.add_argument('-y', action='store_false', help='y help')
2718 return parser
2719
2720 failures = ['-x X -y']
2721 successes = [
2722 ('-x X', NS(x='X', y=True)),
2723 ('-x X -x Y', NS(x='Y', y=True)),
2724 ('-y', NS(x=None, y=False)),
2725 ]
2726 successes_when_not_required = [
2727 ('', NS(x=None, y=True)),
2728 ]
2729
2730 usage_when_not_required = '''\
2731 usage: PROG [-h] [-y]
2732 '''
2733 usage_when_required = '''\
2734 usage: PROG [-h] -y
2735 '''
2736 help = '''\
2737
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002738 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002739 -h, --help show this help message and exit
2740 -y y help
2741 '''
2742
2743
2744class TestMutuallyExclusiveManySuppressed(MEMixin, TestCase):
2745
2746 def get_parser(self, required):
2747 parser = ErrorRaisingArgumentParser(prog='PROG')
2748 group = parser.add_mutually_exclusive_group(required=required)
2749 add = group.add_argument
2750 add('--spam', action='store_true', help=argparse.SUPPRESS)
2751 add('--badger', action='store_false', help=argparse.SUPPRESS)
2752 add('--bladder', help=argparse.SUPPRESS)
2753 return parser
2754
2755 failures = [
2756 '--spam --badger',
2757 '--badger --bladder B',
2758 '--bladder B --spam',
2759 ]
2760 successes = [
2761 ('--spam', NS(spam=True, badger=True, bladder=None)),
2762 ('--badger', NS(spam=False, badger=False, bladder=None)),
2763 ('--bladder B', NS(spam=False, badger=True, bladder='B')),
2764 ('--spam --spam', NS(spam=True, badger=True, bladder=None)),
2765 ]
2766 successes_when_not_required = [
2767 ('', NS(spam=False, badger=True, bladder=None)),
2768 ]
2769
2770 usage_when_required = usage_when_not_required = '''\
2771 usage: PROG [-h]
2772 '''
2773 help = '''\
2774
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002775 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002776 -h, --help show this help message and exit
2777 '''
2778
2779
2780class TestMutuallyExclusiveOptionalAndPositional(MEMixin, TestCase):
2781
2782 def get_parser(self, required):
2783 parser = ErrorRaisingArgumentParser(prog='PROG')
2784 group = parser.add_mutually_exclusive_group(required=required)
2785 group.add_argument('--foo', action='store_true', help='FOO')
2786 group.add_argument('--spam', help='SPAM')
2787 group.add_argument('badger', nargs='*', default='X', help='BADGER')
2788 return parser
2789
2790 failures = [
2791 '--foo --spam S',
2792 '--spam S X',
2793 'X --foo',
2794 'X Y Z --spam S',
2795 '--foo X Y',
2796 ]
2797 successes = [
2798 ('--foo', NS(foo=True, spam=None, badger='X')),
2799 ('--spam S', NS(foo=False, spam='S', badger='X')),
2800 ('X', NS(foo=False, spam=None, badger=['X'])),
2801 ('X Y Z', NS(foo=False, spam=None, badger=['X', 'Y', 'Z'])),
2802 ]
2803 successes_when_not_required = [
2804 ('', NS(foo=False, spam=None, badger='X')),
2805 ]
2806
2807 usage_when_not_required = '''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08002808 usage: PROG [-h] [--foo | --spam SPAM | badger ...]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002809 '''
2810 usage_when_required = '''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08002811 usage: PROG [-h] (--foo | --spam SPAM | badger ...)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002812 '''
2813 help = '''\
2814
2815 positional arguments:
2816 badger BADGER
2817
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002818 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002819 -h, --help show this help message and exit
2820 --foo FOO
2821 --spam SPAM SPAM
2822 '''
2823
2824
2825class TestMutuallyExclusiveOptionalsMixed(MEMixin, TestCase):
2826
2827 def get_parser(self, required):
2828 parser = ErrorRaisingArgumentParser(prog='PROG')
2829 parser.add_argument('-x', action='store_true', help='x help')
2830 group = parser.add_mutually_exclusive_group(required=required)
2831 group.add_argument('-a', action='store_true', help='a help')
2832 group.add_argument('-b', action='store_true', help='b help')
2833 parser.add_argument('-y', action='store_true', help='y help')
2834 group.add_argument('-c', action='store_true', help='c help')
2835 return parser
2836
2837 failures = ['-a -b', '-b -c', '-a -c', '-a -b -c']
2838 successes = [
2839 ('-a', NS(a=True, b=False, c=False, x=False, y=False)),
2840 ('-b', NS(a=False, b=True, c=False, x=False, y=False)),
2841 ('-c', NS(a=False, b=False, c=True, x=False, y=False)),
2842 ('-a -x', NS(a=True, b=False, c=False, x=True, y=False)),
2843 ('-y -b', NS(a=False, b=True, c=False, x=False, y=True)),
2844 ('-x -y -c', NS(a=False, b=False, c=True, x=True, y=True)),
2845 ]
2846 successes_when_not_required = [
2847 ('', NS(a=False, b=False, c=False, x=False, y=False)),
2848 ('-x', NS(a=False, b=False, c=False, x=True, y=False)),
2849 ('-y', NS(a=False, b=False, c=False, x=False, y=True)),
2850 ]
2851
2852 usage_when_required = usage_when_not_required = '''\
2853 usage: PROG [-h] [-x] [-a] [-b] [-y] [-c]
2854 '''
2855 help = '''\
2856
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002857 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002858 -h, --help show this help message and exit
2859 -x x help
2860 -a a help
2861 -b b help
2862 -y y help
2863 -c c help
2864 '''
2865
2866
Georg Brandl0f6b47a2011-01-30 12:19:35 +00002867class TestMutuallyExclusiveInGroup(MEMixin, TestCase):
2868
2869 def get_parser(self, required=None):
2870 parser = ErrorRaisingArgumentParser(prog='PROG')
2871 titled_group = parser.add_argument_group(
2872 title='Titled group', description='Group description')
2873 mutex_group = \
2874 titled_group.add_mutually_exclusive_group(required=required)
2875 mutex_group.add_argument('--bar', help='bar help')
2876 mutex_group.add_argument('--baz', help='baz help')
2877 return parser
2878
2879 failures = ['--bar X --baz Y', '--baz X --bar Y']
2880 successes = [
2881 ('--bar X', NS(bar='X', baz=None)),
2882 ('--baz Y', NS(bar=None, baz='Y')),
2883 ]
2884 successes_when_not_required = [
2885 ('', NS(bar=None, baz=None)),
2886 ]
2887
2888 usage_when_not_required = '''\
2889 usage: PROG [-h] [--bar BAR | --baz BAZ]
2890 '''
2891 usage_when_required = '''\
2892 usage: PROG [-h] (--bar BAR | --baz BAZ)
2893 '''
2894 help = '''\
2895
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002896 options:
Georg Brandl0f6b47a2011-01-30 12:19:35 +00002897 -h, --help show this help message and exit
2898
2899 Titled group:
2900 Group description
2901
2902 --bar BAR bar help
2903 --baz BAZ baz help
2904 '''
2905
2906
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002907class TestMutuallyExclusiveOptionalsAndPositionalsMixed(MEMixin, TestCase):
2908
2909 def get_parser(self, required):
2910 parser = ErrorRaisingArgumentParser(prog='PROG')
2911 parser.add_argument('x', help='x help')
2912 parser.add_argument('-y', action='store_true', help='y help')
2913 group = parser.add_mutually_exclusive_group(required=required)
2914 group.add_argument('a', nargs='?', help='a help')
2915 group.add_argument('-b', action='store_true', help='b help')
2916 group.add_argument('-c', action='store_true', help='c help')
2917 return parser
2918
2919 failures = ['X A -b', '-b -c', '-c X A']
2920 successes = [
2921 ('X A', NS(a='A', b=False, c=False, x='X', y=False)),
2922 ('X -b', NS(a=None, b=True, c=False, x='X', y=False)),
2923 ('X -c', NS(a=None, b=False, c=True, x='X', y=False)),
2924 ('X A -y', NS(a='A', b=False, c=False, x='X', y=True)),
2925 ('X -y -b', NS(a=None, b=True, c=False, x='X', y=True)),
2926 ]
2927 successes_when_not_required = [
2928 ('X', NS(a=None, b=False, c=False, x='X', y=False)),
2929 ('X -y', NS(a=None, b=False, c=False, x='X', y=True)),
2930 ]
2931
2932 usage_when_required = usage_when_not_required = '''\
2933 usage: PROG [-h] [-y] [-b] [-c] x [a]
2934 '''
2935 help = '''\
2936
2937 positional arguments:
2938 x x help
2939 a a help
2940
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002941 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002942 -h, --help show this help message and exit
2943 -y y help
2944 -b b help
2945 -c c help
2946 '''
2947
Flavian Hautboisda27d9b2019-08-25 21:06:45 +02002948class TestMutuallyExclusiveNested(MEMixin, TestCase):
2949
2950 def get_parser(self, required):
2951 parser = ErrorRaisingArgumentParser(prog='PROG')
2952 group = parser.add_mutually_exclusive_group(required=required)
2953 group.add_argument('-a')
2954 group.add_argument('-b')
2955 group2 = group.add_mutually_exclusive_group(required=required)
2956 group2.add_argument('-c')
2957 group2.add_argument('-d')
2958 group3 = group2.add_mutually_exclusive_group(required=required)
2959 group3.add_argument('-e')
2960 group3.add_argument('-f')
2961 return parser
2962
2963 usage_when_not_required = '''\
2964 usage: PROG [-h] [-a A | -b B | [-c C | -d D | [-e E | -f F]]]
2965 '''
2966 usage_when_required = '''\
2967 usage: PROG [-h] (-a A | -b B | (-c C | -d D | (-e E | -f F)))
2968 '''
2969
2970 help = '''\
2971
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002972 options:
Flavian Hautboisda27d9b2019-08-25 21:06:45 +02002973 -h, --help show this help message and exit
2974 -a A
2975 -b B
2976 -c C
2977 -d D
2978 -e E
2979 -f F
2980 '''
2981
2982 # We are only interested in testing the behavior of format_usage().
2983 test_failures_when_not_required = None
2984 test_failures_when_required = None
2985 test_successes_when_not_required = None
2986 test_successes_when_required = None
2987
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002988# =================================================
2989# Mutually exclusive group in parent parser tests
2990# =================================================
2991
2992class MEPBase(object):
2993
2994 def get_parser(self, required=None):
2995 parent = super(MEPBase, self).get_parser(required=required)
2996 parser = ErrorRaisingArgumentParser(
2997 prog=parent.prog, add_help=False, parents=[parent])
2998 return parser
2999
3000
3001class TestMutuallyExclusiveGroupErrorsParent(
3002 MEPBase, TestMutuallyExclusiveGroupErrors):
3003 pass
3004
3005
3006class TestMutuallyExclusiveSimpleParent(
3007 MEPBase, TestMutuallyExclusiveSimple):
3008 pass
3009
3010
3011class TestMutuallyExclusiveLongParent(
3012 MEPBase, TestMutuallyExclusiveLong):
3013 pass
3014
3015
3016class TestMutuallyExclusiveFirstSuppressedParent(
3017 MEPBase, TestMutuallyExclusiveFirstSuppressed):
3018 pass
3019
3020
3021class TestMutuallyExclusiveManySuppressedParent(
3022 MEPBase, TestMutuallyExclusiveManySuppressed):
3023 pass
3024
3025
3026class TestMutuallyExclusiveOptionalAndPositionalParent(
3027 MEPBase, TestMutuallyExclusiveOptionalAndPositional):
3028 pass
3029
3030
3031class TestMutuallyExclusiveOptionalsMixedParent(
3032 MEPBase, TestMutuallyExclusiveOptionalsMixed):
3033 pass
3034
3035
3036class TestMutuallyExclusiveOptionalsAndPositionalsMixedParent(
3037 MEPBase, TestMutuallyExclusiveOptionalsAndPositionalsMixed):
3038 pass
3039
3040# =================
3041# Set default tests
3042# =================
3043
3044class TestSetDefaults(TestCase):
3045
3046 def test_set_defaults_no_args(self):
3047 parser = ErrorRaisingArgumentParser()
3048 parser.set_defaults(x='foo')
3049 parser.set_defaults(y='bar', z=1)
3050 self.assertEqual(NS(x='foo', y='bar', z=1),
3051 parser.parse_args([]))
3052 self.assertEqual(NS(x='foo', y='bar', z=1),
3053 parser.parse_args([], NS()))
3054 self.assertEqual(NS(x='baz', y='bar', z=1),
3055 parser.parse_args([], NS(x='baz')))
3056 self.assertEqual(NS(x='baz', y='bar', z=2),
3057 parser.parse_args([], NS(x='baz', z=2)))
3058
3059 def test_set_defaults_with_args(self):
3060 parser = ErrorRaisingArgumentParser()
3061 parser.set_defaults(x='foo', y='bar')
3062 parser.add_argument('-x', default='xfoox')
3063 self.assertEqual(NS(x='xfoox', y='bar'),
3064 parser.parse_args([]))
3065 self.assertEqual(NS(x='xfoox', y='bar'),
3066 parser.parse_args([], NS()))
3067 self.assertEqual(NS(x='baz', y='bar'),
3068 parser.parse_args([], NS(x='baz')))
3069 self.assertEqual(NS(x='1', y='bar'),
3070 parser.parse_args('-x 1'.split()))
3071 self.assertEqual(NS(x='1', y='bar'),
3072 parser.parse_args('-x 1'.split(), NS()))
3073 self.assertEqual(NS(x='1', y='bar'),
3074 parser.parse_args('-x 1'.split(), NS(x='baz')))
3075
3076 def test_set_defaults_subparsers(self):
3077 parser = ErrorRaisingArgumentParser()
3078 parser.set_defaults(x='foo')
3079 subparsers = parser.add_subparsers()
3080 parser_a = subparsers.add_parser('a')
3081 parser_a.set_defaults(y='bar')
3082 self.assertEqual(NS(x='foo', y='bar'),
3083 parser.parse_args('a'.split()))
3084
3085 def test_set_defaults_parents(self):
3086 parent = ErrorRaisingArgumentParser(add_help=False)
3087 parent.set_defaults(x='foo')
3088 parser = ErrorRaisingArgumentParser(parents=[parent])
3089 self.assertEqual(NS(x='foo'), parser.parse_args([]))
3090
R David Murray7570cbd2014-10-17 19:55:11 -04003091 def test_set_defaults_on_parent_and_subparser(self):
3092 parser = argparse.ArgumentParser()
3093 xparser = parser.add_subparsers().add_parser('X')
3094 parser.set_defaults(foo=1)
3095 xparser.set_defaults(foo=2)
3096 self.assertEqual(NS(foo=2), parser.parse_args(['X']))
3097
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003098 def test_set_defaults_same_as_add_argument(self):
3099 parser = ErrorRaisingArgumentParser()
3100 parser.set_defaults(w='W', x='X', y='Y', z='Z')
3101 parser.add_argument('-w')
3102 parser.add_argument('-x', default='XX')
3103 parser.add_argument('y', nargs='?')
3104 parser.add_argument('z', nargs='?', default='ZZ')
3105
3106 # defaults set previously
3107 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
3108 parser.parse_args([]))
3109
3110 # reset defaults
3111 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
3112 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
3113 parser.parse_args([]))
3114
3115 def test_set_defaults_same_as_add_argument_group(self):
3116 parser = ErrorRaisingArgumentParser()
3117 parser.set_defaults(w='W', x='X', y='Y', z='Z')
3118 group = parser.add_argument_group('foo')
3119 group.add_argument('-w')
3120 group.add_argument('-x', default='XX')
3121 group.add_argument('y', nargs='?')
3122 group.add_argument('z', nargs='?', default='ZZ')
3123
3124
3125 # defaults set previously
3126 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
3127 parser.parse_args([]))
3128
3129 # reset defaults
3130 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
3131 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
3132 parser.parse_args([]))
3133
3134# =================
3135# Get default tests
3136# =================
3137
3138class TestGetDefault(TestCase):
3139
3140 def test_get_default(self):
3141 parser = ErrorRaisingArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003142 self.assertIsNone(parser.get_default("foo"))
3143 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003144
3145 parser.add_argument("--foo")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003146 self.assertIsNone(parser.get_default("foo"))
3147 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003148
3149 parser.add_argument("--bar", type=int, default=42)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003150 self.assertIsNone(parser.get_default("foo"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003151 self.assertEqual(42, parser.get_default("bar"))
3152
3153 parser.set_defaults(foo="badger")
3154 self.assertEqual("badger", parser.get_default("foo"))
3155 self.assertEqual(42, parser.get_default("bar"))
3156
3157# ==========================
3158# Namespace 'contains' tests
3159# ==========================
3160
3161class TestNamespaceContainsSimple(TestCase):
3162
3163 def test_empty(self):
3164 ns = argparse.Namespace()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003165 self.assertNotIn('', ns)
3166 self.assertNotIn('x', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003167
3168 def test_non_empty(self):
3169 ns = argparse.Namespace(x=1, y=2)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003170 self.assertNotIn('', ns)
3171 self.assertIn('x', ns)
3172 self.assertIn('y', ns)
3173 self.assertNotIn('xx', ns)
3174 self.assertNotIn('z', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003175
3176# =====================
3177# Help formatting tests
3178# =====================
3179
3180class TestHelpFormattingMetaclass(type):
3181
3182 def __init__(cls, name, bases, bodydict):
3183 if name == 'HelpTestCase':
3184 return
3185
3186 class AddTests(object):
3187
3188 def __init__(self, test_class, func_suffix, std_name):
3189 self.func_suffix = func_suffix
3190 self.std_name = std_name
3191
3192 for test_func in [self.test_format,
3193 self.test_print,
3194 self.test_print_file]:
3195 test_name = '%s_%s' % (test_func.__name__, func_suffix)
3196
3197 def test_wrapper(self, test_func=test_func):
3198 test_func(self)
3199 try:
3200 test_wrapper.__name__ = test_name
3201 except TypeError:
3202 pass
3203 setattr(test_class, test_name, test_wrapper)
3204
3205 def _get_parser(self, tester):
3206 parser = argparse.ArgumentParser(
3207 *tester.parser_signature.args,
3208 **tester.parser_signature.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003209 for argument_sig in getattr(tester, 'argument_signatures', []):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003210 parser.add_argument(*argument_sig.args,
3211 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003212 group_sigs = getattr(tester, 'argument_group_signatures', [])
3213 for group_sig, argument_sigs in group_sigs:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003214 group = parser.add_argument_group(*group_sig.args,
3215 **group_sig.kwargs)
3216 for argument_sig in argument_sigs:
3217 group.add_argument(*argument_sig.args,
3218 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003219 subparsers_sigs = getattr(tester, 'subparsers_signatures', [])
3220 if subparsers_sigs:
3221 subparsers = parser.add_subparsers()
3222 for subparser_sig in subparsers_sigs:
3223 subparsers.add_parser(*subparser_sig.args,
3224 **subparser_sig.kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003225 return parser
3226
3227 def _test(self, tester, parser_text):
3228 expected_text = getattr(tester, self.func_suffix)
3229 expected_text = textwrap.dedent(expected_text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003230 tester.assertEqual(expected_text, parser_text)
3231
3232 def test_format(self, tester):
3233 parser = self._get_parser(tester)
3234 format = getattr(parser, 'format_%s' % self.func_suffix)
3235 self._test(tester, format())
3236
3237 def test_print(self, tester):
3238 parser = self._get_parser(tester)
3239 print_ = getattr(parser, 'print_%s' % self.func_suffix)
3240 old_stream = getattr(sys, self.std_name)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003241 setattr(sys, self.std_name, StdIOBuffer())
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003242 try:
3243 print_()
3244 parser_text = getattr(sys, self.std_name).getvalue()
3245 finally:
3246 setattr(sys, self.std_name, old_stream)
3247 self._test(tester, parser_text)
3248
3249 def test_print_file(self, tester):
3250 parser = self._get_parser(tester)
3251 print_ = getattr(parser, 'print_%s' % self.func_suffix)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003252 sfile = StdIOBuffer()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003253 print_(sfile)
3254 parser_text = sfile.getvalue()
3255 self._test(tester, parser_text)
3256
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003257 # add tests for {format,print}_{usage,help}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003258 for func_suffix, std_name in [('usage', 'stdout'),
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003259 ('help', 'stdout')]:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003260 AddTests(cls, func_suffix, std_name)
3261
3262bases = TestCase,
3263HelpTestCase = TestHelpFormattingMetaclass('HelpTestCase', bases, {})
3264
3265
3266class TestHelpBiggerOptionals(HelpTestCase):
3267 """Make sure that argument help aligns when options are longer"""
3268
3269 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003270 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003271 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003272 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003273 Sig('-x', action='store_true', help='X HELP'),
3274 Sig('--y', help='Y HELP'),
3275 Sig('foo', help='FOO HELP'),
3276 Sig('bar', help='BAR HELP'),
3277 ]
3278 argument_group_signatures = []
3279 usage = '''\
3280 usage: PROG [-h] [-v] [-x] [--y Y] foo bar
3281 '''
3282 help = usage + '''\
3283
3284 DESCRIPTION
3285
3286 positional arguments:
3287 foo FOO HELP
3288 bar BAR HELP
3289
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003290 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003291 -h, --help show this help message and exit
3292 -v, --version show program's version number and exit
3293 -x X HELP
3294 --y Y Y HELP
3295
3296 EPILOG
3297 '''
3298 version = '''\
3299 0.1
3300 '''
3301
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003302class TestShortColumns(HelpTestCase):
3303 '''Test extremely small number of columns.
3304
3305 TestCase prevents "COLUMNS" from being too small in the tests themselves,
Martin Panter2e4571a2015-11-14 01:07:43 +00003306 but we don't want any exceptions thrown in such cases. Only ugly representation.
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003307 '''
3308 def setUp(self):
Hai Shi46605972020-08-04 00:49:18 +08003309 env = os_helper.EnvironmentVarGuard()
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003310 env.set("COLUMNS", '15')
3311 self.addCleanup(env.__exit__)
3312
3313 parser_signature = TestHelpBiggerOptionals.parser_signature
3314 argument_signatures = TestHelpBiggerOptionals.argument_signatures
3315 argument_group_signatures = TestHelpBiggerOptionals.argument_group_signatures
3316 usage = '''\
3317 usage: PROG
3318 [-h]
3319 [-v]
3320 [-x]
3321 [--y Y]
3322 foo
3323 bar
3324 '''
3325 help = usage + '''\
3326
3327 DESCRIPTION
3328
3329 positional arguments:
3330 foo
3331 FOO HELP
3332 bar
3333 BAR HELP
3334
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003335 options:
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003336 -h, --help
3337 show this
3338 help
3339 message and
3340 exit
3341 -v, --version
3342 show
3343 program's
3344 version
3345 number and
3346 exit
3347 -x
3348 X HELP
3349 --y Y
3350 Y HELP
3351
3352 EPILOG
3353 '''
3354 version = TestHelpBiggerOptionals.version
3355
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003356
3357class TestHelpBiggerOptionalGroups(HelpTestCase):
3358 """Make sure that argument help aligns when options are longer"""
3359
3360 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003361 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003362 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003363 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003364 Sig('-x', action='store_true', help='X HELP'),
3365 Sig('--y', help='Y HELP'),
3366 Sig('foo', help='FOO HELP'),
3367 Sig('bar', help='BAR HELP'),
3368 ]
3369 argument_group_signatures = [
3370 (Sig('GROUP TITLE', description='GROUP DESCRIPTION'), [
3371 Sig('baz', help='BAZ HELP'),
3372 Sig('-z', nargs='+', help='Z HELP')]),
3373 ]
3374 usage = '''\
3375 usage: PROG [-h] [-v] [-x] [--y Y] [-z Z [Z ...]] foo bar baz
3376 '''
3377 help = usage + '''\
3378
3379 DESCRIPTION
3380
3381 positional arguments:
3382 foo FOO HELP
3383 bar BAR HELP
3384
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003385 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003386 -h, --help show this help message and exit
3387 -v, --version show program's version number and exit
3388 -x X HELP
3389 --y Y Y HELP
3390
3391 GROUP TITLE:
3392 GROUP DESCRIPTION
3393
3394 baz BAZ HELP
3395 -z Z [Z ...] Z HELP
3396
3397 EPILOG
3398 '''
3399 version = '''\
3400 0.1
3401 '''
3402
3403
3404class TestHelpBiggerPositionals(HelpTestCase):
3405 """Make sure that help aligns when arguments are longer"""
3406
3407 parser_signature = Sig(usage='USAGE', description='DESCRIPTION')
3408 argument_signatures = [
3409 Sig('-x', action='store_true', help='X HELP'),
3410 Sig('--y', help='Y HELP'),
3411 Sig('ekiekiekifekang', help='EKI HELP'),
3412 Sig('bar', help='BAR HELP'),
3413 ]
3414 argument_group_signatures = []
3415 usage = '''\
3416 usage: USAGE
3417 '''
3418 help = usage + '''\
3419
3420 DESCRIPTION
3421
3422 positional arguments:
3423 ekiekiekifekang EKI HELP
3424 bar BAR HELP
3425
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003426 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003427 -h, --help show this help message and exit
3428 -x X HELP
3429 --y Y Y HELP
3430 '''
3431
3432 version = ''
3433
3434
3435class TestHelpReformatting(HelpTestCase):
3436 """Make sure that text after short names starts on the first line"""
3437
3438 parser_signature = Sig(
3439 prog='PROG',
3440 description=' oddly formatted\n'
3441 'description\n'
3442 '\n'
3443 'that is so long that it should go onto multiple '
3444 'lines when wrapped')
3445 argument_signatures = [
3446 Sig('-x', metavar='XX', help='oddly\n'
3447 ' formatted -x help'),
3448 Sig('y', metavar='yyy', help='normal y help'),
3449 ]
3450 argument_group_signatures = [
3451 (Sig('title', description='\n'
3452 ' oddly formatted group\n'
3453 '\n'
3454 'description'),
3455 [Sig('-a', action='store_true',
3456 help=' oddly \n'
3457 'formatted -a help \n'
3458 ' again, so long that it should be wrapped over '
3459 'multiple lines')]),
3460 ]
3461 usage = '''\
3462 usage: PROG [-h] [-x XX] [-a] yyy
3463 '''
3464 help = usage + '''\
3465
3466 oddly formatted description that is so long that it should go onto \
3467multiple
3468 lines when wrapped
3469
3470 positional arguments:
3471 yyy normal y help
3472
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003473 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003474 -h, --help show this help message and exit
3475 -x XX oddly formatted -x help
3476
3477 title:
3478 oddly formatted group description
3479
3480 -a oddly formatted -a help again, so long that it should \
3481be wrapped
3482 over multiple lines
3483 '''
3484 version = ''
3485
3486
3487class TestHelpWrappingShortNames(HelpTestCase):
3488 """Make sure that text after short names starts on the first line"""
3489
3490 parser_signature = Sig(prog='PROG', description= 'D\nD' * 30)
3491 argument_signatures = [
3492 Sig('-x', metavar='XX', help='XHH HX' * 20),
3493 Sig('y', metavar='yyy', help='YH YH' * 20),
3494 ]
3495 argument_group_signatures = [
3496 (Sig('ALPHAS'), [
3497 Sig('-a', action='store_true', help='AHHH HHA' * 10)]),
3498 ]
3499 usage = '''\
3500 usage: PROG [-h] [-x XX] [-a] yyy
3501 '''
3502 help = usage + '''\
3503
3504 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3505DD DD DD
3506 DD DD DD DD D
3507
3508 positional arguments:
3509 yyy YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3510YHYH YHYH
3511 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3512
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003513 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003514 -h, --help show this help message and exit
3515 -x XX XHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH \
3516HXXHH HXXHH
3517 HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HX
3518
3519 ALPHAS:
3520 -a AHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH \
3521HHAAHHH
3522 HHAAHHH HHAAHHH HHA
3523 '''
3524 version = ''
3525
3526
3527class TestHelpWrappingLongNames(HelpTestCase):
3528 """Make sure that text after long names starts on the next line"""
3529
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003530 parser_signature = Sig(usage='USAGE', description= 'D D' * 30)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003531 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003532 Sig('-v', '--version', action='version', version='V V' * 30),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003533 Sig('-x', metavar='X' * 25, help='XH XH' * 20),
3534 Sig('y', metavar='y' * 25, help='YH YH' * 20),
3535 ]
3536 argument_group_signatures = [
3537 (Sig('ALPHAS'), [
3538 Sig('-a', metavar='A' * 25, help='AH AH' * 20),
3539 Sig('z', metavar='z' * 25, help='ZH ZH' * 20)]),
3540 ]
3541 usage = '''\
3542 usage: USAGE
3543 '''
3544 help = usage + '''\
3545
3546 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3547DD DD DD
3548 DD DD DD DD D
3549
3550 positional arguments:
3551 yyyyyyyyyyyyyyyyyyyyyyyyy
3552 YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3553YHYH YHYH
3554 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3555
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003556 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003557 -h, --help show this help message and exit
3558 -v, --version show program's version number and exit
3559 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3560 XH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH \
3561XHXH XHXH
3562 XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XH
3563
3564 ALPHAS:
3565 -a AAAAAAAAAAAAAAAAAAAAAAAAA
3566 AH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH \
3567AHAH AHAH
3568 AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AH
3569 zzzzzzzzzzzzzzzzzzzzzzzzz
3570 ZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH \
3571ZHZH ZHZH
3572 ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZH
3573 '''
3574 version = '''\
3575 V VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV \
3576VV VV VV
3577 VV VV VV VV V
3578 '''
3579
3580
3581class TestHelpUsage(HelpTestCase):
3582 """Test basic usage messages"""
3583
3584 parser_signature = Sig(prog='PROG')
3585 argument_signatures = [
3586 Sig('-w', nargs='+', help='w'),
3587 Sig('-x', nargs='*', help='x'),
3588 Sig('a', help='a'),
3589 Sig('b', help='b', nargs=2),
3590 Sig('c', help='c', nargs='?'),
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003591 Sig('--foo', help='Whether to foo', action=argparse.BooleanOptionalAction),
3592 Sig('--bar', help='Whether to bar', default=True,
3593 action=argparse.BooleanOptionalAction),
3594 Sig('-f', '--foobar', '--barfoo', action=argparse.BooleanOptionalAction),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003595 ]
3596 argument_group_signatures = [
3597 (Sig('group'), [
3598 Sig('-y', nargs='?', help='y'),
3599 Sig('-z', nargs=3, help='z'),
3600 Sig('d', help='d', nargs='*'),
3601 Sig('e', help='e', nargs='+'),
3602 ])
3603 ]
3604 usage = '''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08003605 usage: PROG [-h] [-w W [W ...]] [-x [X ...]] [--foo | --no-foo]
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003606 [--bar | --no-bar]
3607 [-f | --foobar | --no-foobar | --barfoo | --no-barfoo] [-y [Y]]
3608 [-z Z Z Z]
Brandt Buchera0ed99b2019-11-11 12:47:48 -08003609 a b b [c] [d ...] e [e ...]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003610 '''
3611 help = usage + '''\
3612
3613 positional arguments:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003614 a a
3615 b b
3616 c c
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003617
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003618 options:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003619 -h, --help show this help message and exit
3620 -w W [W ...] w
Brandt Buchera0ed99b2019-11-11 12:47:48 -08003621 -x [X ...] x
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003622 --foo, --no-foo Whether to foo
3623 --bar, --no-bar Whether to bar (default: True)
3624 -f, --foobar, --no-foobar, --barfoo, --no-barfoo
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003625
3626 group:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003627 -y [Y] y
3628 -z Z Z Z z
3629 d d
3630 e e
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003631 '''
3632 version = ''
3633
3634
3635class TestHelpOnlyUserGroups(HelpTestCase):
3636 """Test basic usage messages"""
3637
3638 parser_signature = Sig(prog='PROG', add_help=False)
3639 argument_signatures = []
3640 argument_group_signatures = [
3641 (Sig('xxxx'), [
3642 Sig('-x', help='x'),
3643 Sig('a', help='a'),
3644 ]),
3645 (Sig('yyyy'), [
3646 Sig('b', help='b'),
3647 Sig('-y', help='y'),
3648 ]),
3649 ]
3650 usage = '''\
3651 usage: PROG [-x X] [-y Y] a b
3652 '''
3653 help = usage + '''\
3654
3655 xxxx:
3656 -x X x
3657 a a
3658
3659 yyyy:
3660 b b
3661 -y Y y
3662 '''
3663 version = ''
3664
3665
3666class TestHelpUsageLongProg(HelpTestCase):
3667 """Test usage messages where the prog is long"""
3668
3669 parser_signature = Sig(prog='P' * 60)
3670 argument_signatures = [
3671 Sig('-w', metavar='W'),
3672 Sig('-x', metavar='X'),
3673 Sig('a'),
3674 Sig('b'),
3675 ]
3676 argument_group_signatures = []
3677 usage = '''\
3678 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3679 [-h] [-w W] [-x X] a b
3680 '''
3681 help = usage + '''\
3682
3683 positional arguments:
3684 a
3685 b
3686
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003687 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003688 -h, --help show this help message and exit
3689 -w W
3690 -x X
3691 '''
3692 version = ''
3693
3694
3695class TestHelpUsageLongProgOptionsWrap(HelpTestCase):
3696 """Test usage messages where the prog is long and the optionals wrap"""
3697
3698 parser_signature = Sig(prog='P' * 60)
3699 argument_signatures = [
3700 Sig('-w', metavar='W' * 25),
3701 Sig('-x', metavar='X' * 25),
3702 Sig('-y', metavar='Y' * 25),
3703 Sig('-z', metavar='Z' * 25),
3704 Sig('a'),
3705 Sig('b'),
3706 ]
3707 argument_group_signatures = []
3708 usage = '''\
3709 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3710 [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3711[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3712 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3713 a b
3714 '''
3715 help = usage + '''\
3716
3717 positional arguments:
3718 a
3719 b
3720
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003721 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003722 -h, --help show this help message and exit
3723 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3724 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3725 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3726 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3727 '''
3728 version = ''
3729
3730
3731class TestHelpUsageLongProgPositionalsWrap(HelpTestCase):
3732 """Test usage messages where the prog is long and the positionals wrap"""
3733
3734 parser_signature = Sig(prog='P' * 60, add_help=False)
3735 argument_signatures = [
3736 Sig('a' * 25),
3737 Sig('b' * 25),
3738 Sig('c' * 25),
3739 ]
3740 argument_group_signatures = []
3741 usage = '''\
3742 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3743 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3744 ccccccccccccccccccccccccc
3745 '''
3746 help = usage + '''\
3747
3748 positional arguments:
3749 aaaaaaaaaaaaaaaaaaaaaaaaa
3750 bbbbbbbbbbbbbbbbbbbbbbbbb
3751 ccccccccccccccccccccccccc
3752 '''
3753 version = ''
3754
3755
3756class TestHelpUsageOptionalsWrap(HelpTestCase):
3757 """Test usage messages where the optionals wrap"""
3758
3759 parser_signature = Sig(prog='PROG')
3760 argument_signatures = [
3761 Sig('-w', metavar='W' * 25),
3762 Sig('-x', metavar='X' * 25),
3763 Sig('-y', metavar='Y' * 25),
3764 Sig('-z', metavar='Z' * 25),
3765 Sig('a'),
3766 Sig('b'),
3767 Sig('c'),
3768 ]
3769 argument_group_signatures = []
3770 usage = '''\
3771 usage: PROG [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3772[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3773 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] \
3774[-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3775 a b c
3776 '''
3777 help = usage + '''\
3778
3779 positional arguments:
3780 a
3781 b
3782 c
3783
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003784 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003785 -h, --help show this help message and exit
3786 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3787 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3788 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3789 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3790 '''
3791 version = ''
3792
3793
3794class TestHelpUsagePositionalsWrap(HelpTestCase):
3795 """Test usage messages where the positionals wrap"""
3796
3797 parser_signature = Sig(prog='PROG')
3798 argument_signatures = [
3799 Sig('-x'),
3800 Sig('-y'),
3801 Sig('-z'),
3802 Sig('a' * 25),
3803 Sig('b' * 25),
3804 Sig('c' * 25),
3805 ]
3806 argument_group_signatures = []
3807 usage = '''\
3808 usage: PROG [-h] [-x X] [-y Y] [-z Z]
3809 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3810 ccccccccccccccccccccccccc
3811 '''
3812 help = usage + '''\
3813
3814 positional arguments:
3815 aaaaaaaaaaaaaaaaaaaaaaaaa
3816 bbbbbbbbbbbbbbbbbbbbbbbbb
3817 ccccccccccccccccccccccccc
3818
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003819 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003820 -h, --help show this help message and exit
3821 -x X
3822 -y Y
3823 -z Z
3824 '''
3825 version = ''
3826
3827
3828class TestHelpUsageOptionalsPositionalsWrap(HelpTestCase):
3829 """Test usage messages where the optionals and positionals wrap"""
3830
3831 parser_signature = Sig(prog='PROG')
3832 argument_signatures = [
3833 Sig('-x', metavar='X' * 25),
3834 Sig('-y', metavar='Y' * 25),
3835 Sig('-z', metavar='Z' * 25),
3836 Sig('a' * 25),
3837 Sig('b' * 25),
3838 Sig('c' * 25),
3839 ]
3840 argument_group_signatures = []
3841 usage = '''\
3842 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3843[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3844 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3845 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3846 ccccccccccccccccccccccccc
3847 '''
3848 help = usage + '''\
3849
3850 positional arguments:
3851 aaaaaaaaaaaaaaaaaaaaaaaaa
3852 bbbbbbbbbbbbbbbbbbbbbbbbb
3853 ccccccccccccccccccccccccc
3854
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003855 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003856 -h, --help show this help message and exit
3857 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3858 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3859 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3860 '''
3861 version = ''
3862
3863
3864class TestHelpUsageOptionalsOnlyWrap(HelpTestCase):
3865 """Test usage messages where there are only optionals and they wrap"""
3866
3867 parser_signature = Sig(prog='PROG')
3868 argument_signatures = [
3869 Sig('-x', metavar='X' * 25),
3870 Sig('-y', metavar='Y' * 25),
3871 Sig('-z', metavar='Z' * 25),
3872 ]
3873 argument_group_signatures = []
3874 usage = '''\
3875 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3876[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3877 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3878 '''
3879 help = usage + '''\
3880
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003881 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003882 -h, --help show this help message and exit
3883 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3884 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3885 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3886 '''
3887 version = ''
3888
3889
3890class TestHelpUsagePositionalsOnlyWrap(HelpTestCase):
3891 """Test usage messages where there are only positionals and they wrap"""
3892
3893 parser_signature = Sig(prog='PROG', add_help=False)
3894 argument_signatures = [
3895 Sig('a' * 25),
3896 Sig('b' * 25),
3897 Sig('c' * 25),
3898 ]
3899 argument_group_signatures = []
3900 usage = '''\
3901 usage: PROG aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3902 ccccccccccccccccccccccccc
3903 '''
3904 help = usage + '''\
3905
3906 positional arguments:
3907 aaaaaaaaaaaaaaaaaaaaaaaaa
3908 bbbbbbbbbbbbbbbbbbbbbbbbb
3909 ccccccccccccccccccccccccc
3910 '''
3911 version = ''
3912
3913
3914class TestHelpVariableExpansion(HelpTestCase):
3915 """Test that variables are expanded properly in help messages"""
3916
3917 parser_signature = Sig(prog='PROG')
3918 argument_signatures = [
3919 Sig('-x', type=int,
3920 help='x %(prog)s %(default)s %(type)s %%'),
3921 Sig('-y', action='store_const', default=42, const='XXX',
3922 help='y %(prog)s %(default)s %(const)s'),
3923 Sig('--foo', choices='abc',
3924 help='foo %(prog)s %(default)s %(choices)s'),
3925 Sig('--bar', default='baz', choices=[1, 2], metavar='BBB',
3926 help='bar %(prog)s %(default)s %(dest)s'),
3927 Sig('spam', help='spam %(prog)s %(default)s'),
3928 Sig('badger', default=0.5, help='badger %(prog)s %(default)s'),
3929 ]
3930 argument_group_signatures = [
3931 (Sig('group'), [
3932 Sig('-a', help='a %(prog)s %(default)s'),
3933 Sig('-b', default=-1, help='b %(prog)s %(default)s'),
3934 ])
3935 ]
3936 usage = ('''\
3937 usage: PROG [-h] [-x X] [-y] [--foo {a,b,c}] [--bar BBB] [-a A] [-b B]
3938 spam badger
3939 ''')
3940 help = usage + '''\
3941
3942 positional arguments:
3943 spam spam PROG None
3944 badger badger PROG 0.5
3945
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003946 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003947 -h, --help show this help message and exit
3948 -x X x PROG None int %
3949 -y y PROG 42 XXX
3950 --foo {a,b,c} foo PROG None a, b, c
3951 --bar BBB bar PROG baz bar
3952
3953 group:
3954 -a A a PROG None
3955 -b B b PROG -1
3956 '''
3957 version = ''
3958
3959
3960class TestHelpVariableExpansionUsageSupplied(HelpTestCase):
3961 """Test that variables are expanded properly when usage= is present"""
3962
3963 parser_signature = Sig(prog='PROG', usage='%(prog)s FOO')
3964 argument_signatures = []
3965 argument_group_signatures = []
3966 usage = ('''\
3967 usage: PROG FOO
3968 ''')
3969 help = usage + '''\
3970
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003971 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003972 -h, --help show this help message and exit
3973 '''
3974 version = ''
3975
3976
3977class TestHelpVariableExpansionNoArguments(HelpTestCase):
3978 """Test that variables are expanded properly with no arguments"""
3979
3980 parser_signature = Sig(prog='PROG', add_help=False)
3981 argument_signatures = []
3982 argument_group_signatures = []
3983 usage = ('''\
3984 usage: PROG
3985 ''')
3986 help = usage
3987 version = ''
3988
3989
3990class TestHelpSuppressUsage(HelpTestCase):
3991 """Test that items can be suppressed in usage messages"""
3992
3993 parser_signature = Sig(prog='PROG', usage=argparse.SUPPRESS)
3994 argument_signatures = [
3995 Sig('--foo', help='foo help'),
3996 Sig('spam', help='spam help'),
3997 ]
3998 argument_group_signatures = []
3999 help = '''\
4000 positional arguments:
4001 spam spam help
4002
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004003 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004004 -h, --help show this help message and exit
4005 --foo FOO foo help
4006 '''
4007 usage = ''
4008 version = ''
4009
4010
4011class TestHelpSuppressOptional(HelpTestCase):
4012 """Test that optional arguments can be suppressed in help messages"""
4013
4014 parser_signature = Sig(prog='PROG', add_help=False)
4015 argument_signatures = [
4016 Sig('--foo', help=argparse.SUPPRESS),
4017 Sig('spam', help='spam help'),
4018 ]
4019 argument_group_signatures = []
4020 usage = '''\
4021 usage: PROG spam
4022 '''
4023 help = usage + '''\
4024
4025 positional arguments:
4026 spam spam help
4027 '''
4028 version = ''
4029
4030
4031class TestHelpSuppressOptionalGroup(HelpTestCase):
4032 """Test that optional groups can be suppressed in help messages"""
4033
4034 parser_signature = Sig(prog='PROG')
4035 argument_signatures = [
4036 Sig('--foo', help='foo help'),
4037 Sig('spam', help='spam help'),
4038 ]
4039 argument_group_signatures = [
4040 (Sig('group'), [Sig('--bar', help=argparse.SUPPRESS)]),
4041 ]
4042 usage = '''\
4043 usage: PROG [-h] [--foo FOO] spam
4044 '''
4045 help = usage + '''\
4046
4047 positional arguments:
4048 spam spam help
4049
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004050 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004051 -h, --help show this help message and exit
4052 --foo FOO foo help
4053 '''
4054 version = ''
4055
4056
4057class TestHelpSuppressPositional(HelpTestCase):
4058 """Test that positional arguments can be suppressed in help messages"""
4059
4060 parser_signature = Sig(prog='PROG')
4061 argument_signatures = [
4062 Sig('--foo', help='foo help'),
4063 Sig('spam', help=argparse.SUPPRESS),
4064 ]
4065 argument_group_signatures = []
4066 usage = '''\
4067 usage: PROG [-h] [--foo FOO]
4068 '''
4069 help = usage + '''\
4070
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004071 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004072 -h, --help show this help message and exit
4073 --foo FOO foo help
4074 '''
4075 version = ''
4076
4077
4078class TestHelpRequiredOptional(HelpTestCase):
4079 """Test that required options don't look optional"""
4080
4081 parser_signature = Sig(prog='PROG')
4082 argument_signatures = [
4083 Sig('--foo', required=True, help='foo help'),
4084 ]
4085 argument_group_signatures = []
4086 usage = '''\
4087 usage: PROG [-h] --foo FOO
4088 '''
4089 help = usage + '''\
4090
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004091 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004092 -h, --help show this help message and exit
4093 --foo FOO foo help
4094 '''
4095 version = ''
4096
4097
4098class TestHelpAlternatePrefixChars(HelpTestCase):
4099 """Test that options display with different prefix characters"""
4100
4101 parser_signature = Sig(prog='PROG', prefix_chars='^;', add_help=False)
4102 argument_signatures = [
4103 Sig('^^foo', action='store_true', help='foo help'),
4104 Sig(';b', ';;bar', help='bar help'),
4105 ]
4106 argument_group_signatures = []
4107 usage = '''\
4108 usage: PROG [^^foo] [;b BAR]
4109 '''
4110 help = usage + '''\
4111
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004112 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004113 ^^foo foo help
4114 ;b BAR, ;;bar BAR bar help
4115 '''
4116 version = ''
4117
4118
4119class TestHelpNoHelpOptional(HelpTestCase):
4120 """Test that the --help argument can be suppressed help messages"""
4121
4122 parser_signature = Sig(prog='PROG', add_help=False)
4123 argument_signatures = [
4124 Sig('--foo', help='foo help'),
4125 Sig('spam', help='spam help'),
4126 ]
4127 argument_group_signatures = []
4128 usage = '''\
4129 usage: PROG [--foo FOO] spam
4130 '''
4131 help = usage + '''\
4132
4133 positional arguments:
4134 spam spam help
4135
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004136 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004137 --foo FOO foo help
4138 '''
4139 version = ''
4140
4141
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004142class TestHelpNone(HelpTestCase):
4143 """Test that no errors occur if no help is specified"""
4144
4145 parser_signature = Sig(prog='PROG')
4146 argument_signatures = [
4147 Sig('--foo'),
4148 Sig('spam'),
4149 ]
4150 argument_group_signatures = []
4151 usage = '''\
4152 usage: PROG [-h] [--foo FOO] spam
4153 '''
4154 help = usage + '''\
4155
4156 positional arguments:
4157 spam
4158
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004159 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004160 -h, --help show this help message and exit
4161 --foo FOO
4162 '''
4163 version = ''
4164
4165
4166class TestHelpTupleMetavar(HelpTestCase):
4167 """Test specifying metavar as a tuple"""
4168
4169 parser_signature = Sig(prog='PROG')
4170 argument_signatures = [
4171 Sig('-w', help='w', nargs='+', metavar=('W1', 'W2')),
4172 Sig('-x', help='x', nargs='*', metavar=('X1', 'X2')),
4173 Sig('-y', help='y', nargs=3, metavar=('Y1', 'Y2', 'Y3')),
4174 Sig('-z', help='z', nargs='?', metavar=('Z1', )),
4175 ]
4176 argument_group_signatures = []
4177 usage = '''\
4178 usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] \
4179[-z [Z1]]
4180 '''
4181 help = usage + '''\
4182
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004183 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004184 -h, --help show this help message and exit
4185 -w W1 [W2 ...] w
4186 -x [X1 [X2 ...]] x
4187 -y Y1 Y2 Y3 y
4188 -z [Z1] z
4189 '''
4190 version = ''
4191
4192
4193class TestHelpRawText(HelpTestCase):
4194 """Test the RawTextHelpFormatter"""
4195
4196 parser_signature = Sig(
4197 prog='PROG', formatter_class=argparse.RawTextHelpFormatter,
4198 description='Keep the formatting\n'
4199 ' exactly as it is written\n'
4200 '\n'
4201 'here\n')
4202
4203 argument_signatures = [
4204 Sig('--foo', help=' foo help should also\n'
4205 'appear as given here'),
4206 Sig('spam', help='spam help'),
4207 ]
4208 argument_group_signatures = [
4209 (Sig('title', description=' This text\n'
4210 ' should be indented\n'
4211 ' exactly like it is here\n'),
4212 [Sig('--bar', help='bar help')]),
4213 ]
4214 usage = '''\
4215 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
4216 '''
4217 help = usage + '''\
4218
4219 Keep the formatting
4220 exactly as it is written
4221
4222 here
4223
4224 positional arguments:
4225 spam spam help
4226
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004227 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004228 -h, --help show this help message and exit
4229 --foo FOO foo help should also
4230 appear as given here
4231
4232 title:
4233 This text
4234 should be indented
4235 exactly like it is here
4236
4237 --bar BAR bar help
4238 '''
4239 version = ''
4240
4241
4242class TestHelpRawDescription(HelpTestCase):
4243 """Test the RawTextHelpFormatter"""
4244
4245 parser_signature = Sig(
4246 prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter,
4247 description='Keep the formatting\n'
4248 ' exactly as it is written\n'
4249 '\n'
4250 'here\n')
4251
4252 argument_signatures = [
4253 Sig('--foo', help=' foo help should not\n'
4254 ' retain this odd formatting'),
4255 Sig('spam', help='spam help'),
4256 ]
4257 argument_group_signatures = [
4258 (Sig('title', description=' This text\n'
4259 ' should be indented\n'
4260 ' exactly like it is here\n'),
4261 [Sig('--bar', help='bar help')]),
4262 ]
4263 usage = '''\
4264 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
4265 '''
4266 help = usage + '''\
4267
4268 Keep the formatting
4269 exactly as it is written
4270
4271 here
4272
4273 positional arguments:
4274 spam spam help
4275
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004276 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004277 -h, --help show this help message and exit
4278 --foo FOO foo help should not retain this odd formatting
4279
4280 title:
4281 This text
4282 should be indented
4283 exactly like it is here
4284
4285 --bar BAR bar help
4286 '''
4287 version = ''
4288
4289
4290class TestHelpArgumentDefaults(HelpTestCase):
4291 """Test the ArgumentDefaultsHelpFormatter"""
4292
4293 parser_signature = Sig(
4294 prog='PROG', formatter_class=argparse.ArgumentDefaultsHelpFormatter,
4295 description='description')
4296
4297 argument_signatures = [
4298 Sig('--foo', help='foo help - oh and by the way, %(default)s'),
4299 Sig('--bar', action='store_true', help='bar help'),
Miss Islington (bot)6f6648e2021-08-17 02:40:41 -07004300 Sig('--taz', action=argparse.BooleanOptionalAction,
4301 help='Whether to taz it', default=True),
4302 Sig('--quux', help="Set the quux", default=42),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004303 Sig('spam', help='spam help'),
4304 Sig('badger', nargs='?', default='wooden', help='badger help'),
4305 ]
4306 argument_group_signatures = [
4307 (Sig('title', description='description'),
4308 [Sig('--baz', type=int, default=42, help='baz help')]),
4309 ]
4310 usage = '''\
Miss Islington (bot)6f6648e2021-08-17 02:40:41 -07004311 usage: PROG [-h] [--foo FOO] [--bar] [--taz | --no-taz] [--quux QUUX]
4312 [--baz BAZ]
4313 spam [badger]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004314 '''
4315 help = usage + '''\
4316
4317 description
4318
4319 positional arguments:
Miss Islington (bot)6f6648e2021-08-17 02:40:41 -07004320 spam spam help
4321 badger badger help (default: wooden)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004322
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004323 options:
Miss Islington (bot)6f6648e2021-08-17 02:40:41 -07004324 -h, --help show this help message and exit
4325 --foo FOO foo help - oh and by the way, None
4326 --bar bar help (default: False)
4327 --taz, --no-taz Whether to taz it (default: True)
4328 --quux QUUX Set the quux (default: 42)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004329
4330 title:
4331 description
4332
Miss Islington (bot)6f6648e2021-08-17 02:40:41 -07004333 --baz BAZ baz help (default: 42)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004334 '''
4335 version = ''
4336
Steven Bethard50fe5932010-05-24 03:47:38 +00004337class TestHelpVersionAction(HelpTestCase):
4338 """Test the default help for the version action"""
4339
4340 parser_signature = Sig(prog='PROG', description='description')
4341 argument_signatures = [Sig('-V', '--version', action='version', version='3.6')]
4342 argument_group_signatures = []
4343 usage = '''\
4344 usage: PROG [-h] [-V]
4345 '''
4346 help = usage + '''\
4347
4348 description
4349
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004350 options:
Steven Bethard50fe5932010-05-24 03:47:38 +00004351 -h, --help show this help message and exit
4352 -V, --version show program's version number and exit
4353 '''
4354 version = ''
4355
Berker Peksagecb75e22015-04-10 16:11:12 +03004356
4357class TestHelpVersionActionSuppress(HelpTestCase):
4358 """Test that the --version argument can be suppressed in help messages"""
4359
4360 parser_signature = Sig(prog='PROG')
4361 argument_signatures = [
4362 Sig('-v', '--version', action='version', version='1.0',
4363 help=argparse.SUPPRESS),
4364 Sig('--foo', help='foo help'),
4365 Sig('spam', help='spam help'),
4366 ]
4367 argument_group_signatures = []
4368 usage = '''\
4369 usage: PROG [-h] [--foo FOO] spam
4370 '''
4371 help = usage + '''\
4372
4373 positional arguments:
4374 spam spam help
4375
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004376 options:
Berker Peksagecb75e22015-04-10 16:11:12 +03004377 -h, --help show this help message and exit
4378 --foo FOO foo help
4379 '''
4380
4381
Steven Bethard8a6a1982011-03-27 13:53:53 +02004382class TestHelpSubparsersOrdering(HelpTestCase):
4383 """Test ordering of subcommands in help matches the code"""
4384 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004385 description='display some subcommands')
4386 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004387
4388 subparsers_signatures = [Sig(name=name)
4389 for name in ('a', 'b', 'c', 'd', 'e')]
4390
4391 usage = '''\
4392 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4393 '''
4394
4395 help = usage + '''\
4396
4397 display some subcommands
4398
4399 positional arguments:
4400 {a,b,c,d,e}
4401
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004402 options:
Steven Bethard8a6a1982011-03-27 13:53:53 +02004403 -h, --help show this help message and exit
4404 -v, --version show program's version number and exit
4405 '''
4406
4407 version = '''\
4408 0.1
4409 '''
4410
4411class TestHelpSubparsersWithHelpOrdering(HelpTestCase):
4412 """Test ordering of subcommands in help matches the code"""
4413 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004414 description='display some subcommands')
4415 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004416
4417 subcommand_data = (('a', 'a subcommand help'),
4418 ('b', 'b subcommand help'),
4419 ('c', 'c subcommand help'),
4420 ('d', 'd subcommand help'),
4421 ('e', 'e subcommand help'),
4422 )
4423
4424 subparsers_signatures = [Sig(name=name, help=help)
4425 for name, help in subcommand_data]
4426
4427 usage = '''\
4428 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4429 '''
4430
4431 help = usage + '''\
4432
4433 display some subcommands
4434
4435 positional arguments:
4436 {a,b,c,d,e}
4437 a a subcommand help
4438 b b subcommand help
4439 c c subcommand help
4440 d d subcommand help
4441 e e subcommand help
4442
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004443 options:
Steven Bethard8a6a1982011-03-27 13:53:53 +02004444 -h, --help show this help message and exit
4445 -v, --version show program's version number and exit
4446 '''
4447
4448 version = '''\
4449 0.1
4450 '''
4451
4452
Steven Bethard0331e902011-03-26 14:48:04 +01004453
4454class TestHelpMetavarTypeFormatter(HelpTestCase):
Steven Bethard0331e902011-03-26 14:48:04 +01004455
4456 def custom_type(string):
4457 return string
4458
4459 parser_signature = Sig(prog='PROG', description='description',
4460 formatter_class=argparse.MetavarTypeHelpFormatter)
4461 argument_signatures = [Sig('a', type=int),
4462 Sig('-b', type=custom_type),
4463 Sig('-c', type=float, metavar='SOME FLOAT')]
4464 argument_group_signatures = []
4465 usage = '''\
4466 usage: PROG [-h] [-b custom_type] [-c SOME FLOAT] int
4467 '''
4468 help = usage + '''\
4469
4470 description
4471
4472 positional arguments:
4473 int
4474
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004475 options:
Steven Bethard0331e902011-03-26 14:48:04 +01004476 -h, --help show this help message and exit
4477 -b custom_type
4478 -c SOME FLOAT
4479 '''
4480 version = ''
4481
4482
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004483# =====================================
4484# Optional/Positional constructor tests
4485# =====================================
4486
4487class TestInvalidArgumentConstructors(TestCase):
4488 """Test a bunch of invalid Argument constructors"""
4489
4490 def assertTypeError(self, *args, **kwargs):
4491 parser = argparse.ArgumentParser()
4492 self.assertRaises(TypeError, parser.add_argument,
4493 *args, **kwargs)
4494
4495 def assertValueError(self, *args, **kwargs):
4496 parser = argparse.ArgumentParser()
4497 self.assertRaises(ValueError, parser.add_argument,
4498 *args, **kwargs)
4499
4500 def test_invalid_keyword_arguments(self):
4501 self.assertTypeError('-x', bar=None)
4502 self.assertTypeError('-y', callback='foo')
4503 self.assertTypeError('-y', callback_args=())
4504 self.assertTypeError('-y', callback_kwargs={})
4505
4506 def test_missing_destination(self):
4507 self.assertTypeError()
4508 for action in ['append', 'store']:
4509 self.assertTypeError(action=action)
4510
4511 def test_invalid_option_strings(self):
4512 self.assertValueError('--')
4513 self.assertValueError('---')
4514
4515 def test_invalid_type(self):
4516 self.assertValueError('--foo', type='int')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004517 self.assertValueError('--foo', type=(int, float))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004518
4519 def test_invalid_action(self):
4520 self.assertValueError('-x', action='foo')
4521 self.assertValueError('foo', action='baz')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004522 self.assertValueError('--foo', action=('store', 'append'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004523 parser = argparse.ArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004524 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004525 parser.add_argument("--foo", action="store-true")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004526 self.assertIn('unknown action', str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004527
4528 def test_multiple_dest(self):
4529 parser = argparse.ArgumentParser()
4530 parser.add_argument(dest='foo')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004531 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004532 parser.add_argument('bar', dest='baz')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004533 self.assertIn('dest supplied twice for positional argument',
4534 str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004535
4536 def test_no_argument_actions(self):
4537 for action in ['store_const', 'store_true', 'store_false',
4538 'append_const', 'count']:
4539 for attrs in [dict(type=int), dict(nargs='+'),
4540 dict(choices='ab')]:
4541 self.assertTypeError('-x', action=action, **attrs)
4542
4543 def test_no_argument_no_const_actions(self):
4544 # options with zero arguments
4545 for action in ['store_true', 'store_false', 'count']:
4546
4547 # const is always disallowed
4548 self.assertTypeError('-x', const='foo', action=action)
4549
4550 # nargs is always disallowed
4551 self.assertTypeError('-x', nargs='*', action=action)
4552
4553 def test_more_than_one_argument_actions(self):
4554 for action in ['store', 'append']:
4555
4556 # nargs=0 is disallowed
4557 self.assertValueError('-x', nargs=0, action=action)
4558 self.assertValueError('spam', nargs=0, action=action)
4559
4560 # const is disallowed with non-optional arguments
4561 for nargs in [1, '*', '+']:
4562 self.assertValueError('-x', const='foo',
4563 nargs=nargs, action=action)
4564 self.assertValueError('spam', const='foo',
4565 nargs=nargs, action=action)
4566
4567 def test_required_const_actions(self):
4568 for action in ['store_const', 'append_const']:
4569
4570 # nargs is always disallowed
4571 self.assertTypeError('-x', nargs='+', action=action)
4572
4573 def test_parsers_action_missing_params(self):
4574 self.assertTypeError('command', action='parsers')
4575 self.assertTypeError('command', action='parsers', prog='PROG')
4576 self.assertTypeError('command', action='parsers',
4577 parser_class=argparse.ArgumentParser)
4578
4579 def test_required_positional(self):
4580 self.assertTypeError('foo', required=True)
4581
4582 def test_user_defined_action(self):
4583
4584 class Success(Exception):
4585 pass
4586
4587 class Action(object):
4588
4589 def __init__(self,
4590 option_strings,
4591 dest,
4592 const,
4593 default,
4594 required=False):
4595 if dest == 'spam':
4596 if const is Success:
4597 if default is Success:
4598 raise Success()
4599
4600 def __call__(self, *args, **kwargs):
4601 pass
4602
4603 parser = argparse.ArgumentParser()
4604 self.assertRaises(Success, parser.add_argument, '--spam',
4605 action=Action, default=Success, const=Success)
4606 self.assertRaises(Success, parser.add_argument, 'spam',
4607 action=Action, default=Success, const=Success)
4608
4609# ================================
4610# Actions returned by add_argument
4611# ================================
4612
4613class TestActionsReturned(TestCase):
4614
4615 def test_dest(self):
4616 parser = argparse.ArgumentParser()
4617 action = parser.add_argument('--foo')
4618 self.assertEqual(action.dest, 'foo')
4619 action = parser.add_argument('-b', '--bar')
4620 self.assertEqual(action.dest, 'bar')
4621 action = parser.add_argument('-x', '-y')
4622 self.assertEqual(action.dest, 'x')
4623
4624 def test_misc(self):
4625 parser = argparse.ArgumentParser()
4626 action = parser.add_argument('--foo', nargs='?', const=42,
4627 default=84, type=int, choices=[1, 2],
4628 help='FOO', metavar='BAR', dest='baz')
4629 self.assertEqual(action.nargs, '?')
4630 self.assertEqual(action.const, 42)
4631 self.assertEqual(action.default, 84)
4632 self.assertEqual(action.type, int)
4633 self.assertEqual(action.choices, [1, 2])
4634 self.assertEqual(action.help, 'FOO')
4635 self.assertEqual(action.metavar, 'BAR')
4636 self.assertEqual(action.dest, 'baz')
4637
4638
4639# ================================
4640# Argument conflict handling tests
4641# ================================
4642
4643class TestConflictHandling(TestCase):
4644
4645 def test_bad_type(self):
4646 self.assertRaises(ValueError, argparse.ArgumentParser,
4647 conflict_handler='foo')
4648
4649 def test_conflict_error(self):
4650 parser = argparse.ArgumentParser()
4651 parser.add_argument('-x')
4652 self.assertRaises(argparse.ArgumentError,
4653 parser.add_argument, '-x')
4654 parser.add_argument('--spam')
4655 self.assertRaises(argparse.ArgumentError,
4656 parser.add_argument, '--spam')
4657
4658 def test_resolve_error(self):
4659 get_parser = argparse.ArgumentParser
4660 parser = get_parser(prog='PROG', conflict_handler='resolve')
4661
4662 parser.add_argument('-x', help='OLD X')
4663 parser.add_argument('-x', help='NEW X')
4664 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4665 usage: PROG [-h] [-x X]
4666
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004667 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004668 -h, --help show this help message and exit
4669 -x X NEW X
4670 '''))
4671
4672 parser.add_argument('--spam', metavar='OLD_SPAM')
4673 parser.add_argument('--spam', metavar='NEW_SPAM')
4674 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4675 usage: PROG [-h] [-x X] [--spam NEW_SPAM]
4676
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004677 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004678 -h, --help show this help message and exit
4679 -x X NEW X
4680 --spam NEW_SPAM
4681 '''))
4682
4683
4684# =============================
4685# Help and Version option tests
4686# =============================
4687
4688class TestOptionalsHelpVersionActions(TestCase):
4689 """Test the help and version actions"""
4690
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004691 def assertPrintHelpExit(self, parser, args_str):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004692 with self.assertRaises(ArgumentParserError) as cm:
4693 parser.parse_args(args_str.split())
4694 self.assertEqual(parser.format_help(), cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004695
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004696 def assertArgumentParserError(self, parser, *args):
4697 self.assertRaises(ArgumentParserError, parser.parse_args, args)
4698
4699 def test_version(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004700 parser = ErrorRaisingArgumentParser()
4701 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004702 self.assertPrintHelpExit(parser, '-h')
4703 self.assertPrintHelpExit(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004704 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004705
4706 def test_version_format(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004707 parser = ErrorRaisingArgumentParser(prog='PPP')
4708 parser.add_argument('-v', '--version', action='version', version='%(prog)s 3.5')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004709 with self.assertRaises(ArgumentParserError) as cm:
4710 parser.parse_args(['-v'])
4711 self.assertEqual('PPP 3.5\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004712
4713 def test_version_no_help(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004714 parser = ErrorRaisingArgumentParser(add_help=False)
4715 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004716 self.assertArgumentParserError(parser, '-h')
4717 self.assertArgumentParserError(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004718 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004719
4720 def test_version_action(self):
4721 parser = ErrorRaisingArgumentParser(prog='XXX')
4722 parser.add_argument('-V', action='version', version='%(prog)s 3.7')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004723 with self.assertRaises(ArgumentParserError) as cm:
4724 parser.parse_args(['-V'])
4725 self.assertEqual('XXX 3.7\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004726
4727 def test_no_help(self):
4728 parser = ErrorRaisingArgumentParser(add_help=False)
4729 self.assertArgumentParserError(parser, '-h')
4730 self.assertArgumentParserError(parser, '--help')
4731 self.assertArgumentParserError(parser, '-v')
4732 self.assertArgumentParserError(parser, '--version')
4733
4734 def test_alternate_help_version(self):
4735 parser = ErrorRaisingArgumentParser()
4736 parser.add_argument('-x', action='help')
4737 parser.add_argument('-y', action='version')
4738 self.assertPrintHelpExit(parser, '-x')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004739 self.assertArgumentParserError(parser, '-v')
4740 self.assertArgumentParserError(parser, '--version')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004741 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004742
4743 def test_help_version_extra_arguments(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004744 parser = ErrorRaisingArgumentParser()
4745 parser.add_argument('--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004746 parser.add_argument('-x', action='store_true')
4747 parser.add_argument('y')
4748
4749 # try all combinations of valid prefixes and suffixes
4750 valid_prefixes = ['', '-x', 'foo', '-x bar', 'baz -x']
4751 valid_suffixes = valid_prefixes + ['--bad-option', 'foo bar baz']
4752 for prefix in valid_prefixes:
4753 for suffix in valid_suffixes:
4754 format = '%s %%s %s' % (prefix, suffix)
4755 self.assertPrintHelpExit(parser, format % '-h')
4756 self.assertPrintHelpExit(parser, format % '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004757 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004758
4759
4760# ======================
4761# str() and repr() tests
4762# ======================
4763
4764class TestStrings(TestCase):
4765 """Test str() and repr() on Optionals and Positionals"""
4766
4767 def assertStringEqual(self, obj, result_string):
4768 for func in [str, repr]:
4769 self.assertEqual(func(obj), result_string)
4770
4771 def test_optional(self):
4772 option = argparse.Action(
4773 option_strings=['--foo', '-a', '-b'],
4774 dest='b',
4775 type='int',
4776 nargs='+',
4777 default=42,
4778 choices=[1, 2, 3],
4779 help='HELP',
4780 metavar='METAVAR')
4781 string = (
4782 "Action(option_strings=['--foo', '-a', '-b'], dest='b', "
4783 "nargs='+', const=None, default=42, type='int', "
4784 "choices=[1, 2, 3], help='HELP', metavar='METAVAR')")
4785 self.assertStringEqual(option, string)
4786
4787 def test_argument(self):
4788 argument = argparse.Action(
4789 option_strings=[],
4790 dest='x',
4791 type=float,
4792 nargs='?',
4793 default=2.5,
4794 choices=[0.5, 1.5, 2.5],
4795 help='H HH H',
4796 metavar='MV MV MV')
4797 string = (
4798 "Action(option_strings=[], dest='x', nargs='?', "
4799 "const=None, default=2.5, type=%r, choices=[0.5, 1.5, 2.5], "
4800 "help='H HH H', metavar='MV MV MV')" % float)
4801 self.assertStringEqual(argument, string)
4802
4803 def test_namespace(self):
4804 ns = argparse.Namespace(foo=42, bar='spam')
Raymond Hettinger96819532020-05-17 18:53:01 -07004805 string = "Namespace(foo=42, bar='spam')"
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004806 self.assertStringEqual(ns, string)
4807
Berker Peksag76b17142015-07-29 23:51:47 +03004808 def test_namespace_starkwargs_notidentifier(self):
4809 ns = argparse.Namespace(**{'"': 'quote'})
4810 string = """Namespace(**{'"': 'quote'})"""
4811 self.assertStringEqual(ns, string)
4812
4813 def test_namespace_kwargs_and_starkwargs_notidentifier(self):
4814 ns = argparse.Namespace(a=1, **{'"': 'quote'})
4815 string = """Namespace(a=1, **{'"': 'quote'})"""
4816 self.assertStringEqual(ns, string)
4817
4818 def test_namespace_starkwargs_identifier(self):
4819 ns = argparse.Namespace(**{'valid': True})
4820 string = "Namespace(valid=True)"
4821 self.assertStringEqual(ns, string)
4822
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004823 def test_parser(self):
4824 parser = argparse.ArgumentParser(prog='PROG')
4825 string = (
4826 "ArgumentParser(prog='PROG', usage=None, description=None, "
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004827 "formatter_class=%r, conflict_handler='error', "
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004828 "add_help=True)" % argparse.HelpFormatter)
4829 self.assertStringEqual(parser, string)
4830
4831# ===============
4832# Namespace tests
4833# ===============
4834
4835class TestNamespace(TestCase):
4836
4837 def test_constructor(self):
4838 ns = argparse.Namespace()
4839 self.assertRaises(AttributeError, getattr, ns, 'x')
4840
4841 ns = argparse.Namespace(a=42, b='spam')
4842 self.assertEqual(ns.a, 42)
4843 self.assertEqual(ns.b, 'spam')
4844
4845 def test_equality(self):
4846 ns1 = argparse.Namespace(a=1, b=2)
4847 ns2 = argparse.Namespace(b=2, a=1)
4848 ns3 = argparse.Namespace(a=1)
4849 ns4 = argparse.Namespace(b=2)
4850
4851 self.assertEqual(ns1, ns2)
4852 self.assertNotEqual(ns1, ns3)
4853 self.assertNotEqual(ns1, ns4)
4854 self.assertNotEqual(ns2, ns3)
4855 self.assertNotEqual(ns2, ns4)
4856 self.assertTrue(ns1 != ns3)
4857 self.assertTrue(ns1 != ns4)
4858 self.assertTrue(ns2 != ns3)
4859 self.assertTrue(ns2 != ns4)
4860
Berker Peksagc16387b2016-09-28 17:21:52 +03004861 def test_equality_returns_notimplemented(self):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07004862 # See issue 21481
4863 ns = argparse.Namespace(a=1, b=2)
4864 self.assertIs(ns.__eq__(None), NotImplemented)
4865 self.assertIs(ns.__ne__(None), NotImplemented)
4866
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004867
4868# ===================
4869# File encoding tests
4870# ===================
4871
4872class TestEncoding(TestCase):
4873
4874 def _test_module_encoding(self, path):
4875 path, _ = os.path.splitext(path)
4876 path += ".py"
Victor Stinner272d8882017-06-16 08:59:01 +02004877 with open(path, 'r', encoding='utf-8') as f:
Antoine Pitroub86680e2010-10-14 21:15:17 +00004878 f.read()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004879
4880 def test_argparse_module_encoding(self):
4881 self._test_module_encoding(argparse.__file__)
4882
4883 def test_test_argparse_module_encoding(self):
4884 self._test_module_encoding(__file__)
4885
4886# ===================
4887# ArgumentError tests
4888# ===================
4889
4890class TestArgumentError(TestCase):
4891
4892 def test_argument_error(self):
4893 msg = "my error here"
4894 error = argparse.ArgumentError(None, msg)
4895 self.assertEqual(str(error), msg)
4896
4897# =======================
4898# ArgumentTypeError tests
4899# =======================
4900
R. David Murray722b5fd2010-11-20 03:48:58 +00004901class TestArgumentTypeError(TestCase):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004902
4903 def test_argument_type_error(self):
4904
4905 def spam(string):
4906 raise argparse.ArgumentTypeError('spam!')
4907
4908 parser = ErrorRaisingArgumentParser(prog='PROG', add_help=False)
4909 parser.add_argument('x', type=spam)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004910 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004911 parser.parse_args(['XXX'])
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004912 self.assertEqual('usage: PROG x\nPROG: error: argument x: spam!\n',
4913 cm.exception.stderr)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004914
R David Murrayf97c59a2011-06-09 12:34:07 -04004915# =========================
4916# MessageContentError tests
4917# =========================
4918
4919class TestMessageContentError(TestCase):
4920
4921 def test_missing_argument_name_in_message(self):
4922 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4923 parser.add_argument('req_pos', type=str)
4924 parser.add_argument('-req_opt', type=int, required=True)
4925 parser.add_argument('need_one', type=str, nargs='+')
4926
4927 with self.assertRaises(ArgumentParserError) as cm:
4928 parser.parse_args([])
4929 msg = str(cm.exception)
4930 self.assertRegex(msg, 'req_pos')
4931 self.assertRegex(msg, 'req_opt')
4932 self.assertRegex(msg, 'need_one')
4933 with self.assertRaises(ArgumentParserError) as cm:
4934 parser.parse_args(['myXargument'])
4935 msg = str(cm.exception)
4936 self.assertNotIn(msg, 'req_pos')
4937 self.assertRegex(msg, 'req_opt')
4938 self.assertRegex(msg, 'need_one')
4939 with self.assertRaises(ArgumentParserError) as cm:
4940 parser.parse_args(['myXargument', '-req_opt=1'])
4941 msg = str(cm.exception)
4942 self.assertNotIn(msg, 'req_pos')
4943 self.assertNotIn(msg, 'req_opt')
4944 self.assertRegex(msg, 'need_one')
4945
4946 def test_optional_optional_not_in_message(self):
4947 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4948 parser.add_argument('req_pos', type=str)
4949 parser.add_argument('--req_opt', type=int, required=True)
4950 parser.add_argument('--opt_opt', type=bool, nargs='?',
4951 default=True)
4952 with self.assertRaises(ArgumentParserError) as cm:
4953 parser.parse_args([])
4954 msg = str(cm.exception)
4955 self.assertRegex(msg, 'req_pos')
4956 self.assertRegex(msg, 'req_opt')
4957 self.assertNotIn(msg, 'opt_opt')
4958 with self.assertRaises(ArgumentParserError) as cm:
4959 parser.parse_args(['--req_opt=1'])
4960 msg = str(cm.exception)
4961 self.assertRegex(msg, 'req_pos')
4962 self.assertNotIn(msg, 'req_opt')
4963 self.assertNotIn(msg, 'opt_opt')
4964
4965 def test_optional_positional_not_in_message(self):
4966 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4967 parser.add_argument('req_pos')
4968 parser.add_argument('optional_positional', nargs='?', default='eggs')
4969 with self.assertRaises(ArgumentParserError) as cm:
4970 parser.parse_args([])
4971 msg = str(cm.exception)
4972 self.assertRegex(msg, 'req_pos')
4973 self.assertNotIn(msg, 'optional_positional')
4974
4975
R David Murray6fb8fb12012-08-31 22:45:20 -04004976# ================================================
4977# Check that the type function is called only once
4978# ================================================
4979
4980class TestTypeFunctionCallOnlyOnce(TestCase):
4981
4982 def test_type_function_call_only_once(self):
4983 def spam(string_to_convert):
4984 self.assertEqual(string_to_convert, 'spam!')
4985 return 'foo_converted'
4986
4987 parser = argparse.ArgumentParser()
4988 parser.add_argument('--foo', type=spam, default='bar')
4989 args = parser.parse_args('--foo spam!'.split())
4990 self.assertEqual(NS(foo='foo_converted'), args)
4991
Barry Warsaweaae1b72012-09-12 14:34:50 -04004992# ==================================================================
4993# Check semantics regarding the default argument and type conversion
4994# ==================================================================
R David Murray6fb8fb12012-08-31 22:45:20 -04004995
Barry Warsaweaae1b72012-09-12 14:34:50 -04004996class TestTypeFunctionCalledOnDefault(TestCase):
R David Murray6fb8fb12012-08-31 22:45:20 -04004997
4998 def test_type_function_call_with_non_string_default(self):
4999 def spam(int_to_convert):
5000 self.assertEqual(int_to_convert, 0)
5001 return 'foo_converted'
5002
5003 parser = argparse.ArgumentParser()
5004 parser.add_argument('--foo', type=spam, default=0)
5005 args = parser.parse_args([])
Barry Warsaweaae1b72012-09-12 14:34:50 -04005006 # foo should *not* be converted because its default is not a string.
5007 self.assertEqual(NS(foo=0), args)
5008
5009 def test_type_function_call_with_string_default(self):
5010 def spam(int_to_convert):
5011 return 'foo_converted'
5012
5013 parser = argparse.ArgumentParser()
5014 parser.add_argument('--foo', type=spam, default='0')
5015 args = parser.parse_args([])
5016 # foo is converted because its default is a string.
R David Murray6fb8fb12012-08-31 22:45:20 -04005017 self.assertEqual(NS(foo='foo_converted'), args)
5018
Barry Warsaweaae1b72012-09-12 14:34:50 -04005019 def test_no_double_type_conversion_of_default(self):
5020 def extend(str_to_convert):
5021 return str_to_convert + '*'
5022
5023 parser = argparse.ArgumentParser()
5024 parser.add_argument('--test', type=extend, default='*')
5025 args = parser.parse_args([])
5026 # The test argument will be two stars, one coming from the default
5027 # value and one coming from the type conversion being called exactly
5028 # once.
5029 self.assertEqual(NS(test='**'), args)
5030
Barry Warsaw4b2f9e92012-09-11 22:38:47 -04005031 def test_issue_15906(self):
5032 # Issue #15906: When action='append', type=str, default=[] are
5033 # providing, the dest value was the string representation "[]" when it
5034 # should have been an empty list.
5035 parser = argparse.ArgumentParser()
5036 parser.add_argument('--test', dest='test', type=str,
5037 default=[], action='append')
5038 args = parser.parse_args([])
5039 self.assertEqual(args.test, [])
5040
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005041# ======================
5042# parse_known_args tests
5043# ======================
5044
5045class TestParseKnownArgs(TestCase):
5046
R David Murrayb5228282012-09-08 12:08:01 -04005047 def test_arguments_tuple(self):
5048 parser = argparse.ArgumentParser()
5049 parser.parse_args(())
5050
5051 def test_arguments_list(self):
5052 parser = argparse.ArgumentParser()
5053 parser.parse_args([])
5054
5055 def test_arguments_tuple_positional(self):
5056 parser = argparse.ArgumentParser()
5057 parser.add_argument('x')
5058 parser.parse_args(('x',))
5059
5060 def test_arguments_list_positional(self):
5061 parser = argparse.ArgumentParser()
5062 parser.add_argument('x')
5063 parser.parse_args(['x'])
5064
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005065 def test_optionals(self):
5066 parser = argparse.ArgumentParser()
5067 parser.add_argument('--foo')
5068 args, extras = parser.parse_known_args('--foo F --bar --baz'.split())
5069 self.assertEqual(NS(foo='F'), args)
5070 self.assertEqual(['--bar', '--baz'], extras)
5071
5072 def test_mixed(self):
5073 parser = argparse.ArgumentParser()
5074 parser.add_argument('-v', nargs='?', const=1, type=int)
5075 parser.add_argument('--spam', action='store_false')
5076 parser.add_argument('badger')
5077
5078 argv = ["B", "C", "--foo", "-v", "3", "4"]
5079 args, extras = parser.parse_known_args(argv)
5080 self.assertEqual(NS(v=3, spam=True, badger="B"), args)
5081 self.assertEqual(["C", "--foo", "4"], extras)
5082
R. David Murray0f6b9d22017-09-06 20:25:40 -04005083# ===========================
5084# parse_intermixed_args tests
5085# ===========================
5086
5087class TestIntermixedArgs(TestCase):
5088 def test_basic(self):
5089 # test parsing intermixed optionals and positionals
5090 parser = argparse.ArgumentParser(prog='PROG')
5091 parser.add_argument('--foo', dest='foo')
5092 bar = parser.add_argument('--bar', dest='bar', required=True)
5093 parser.add_argument('cmd')
5094 parser.add_argument('rest', nargs='*', type=int)
5095 argv = 'cmd --foo x 1 --bar y 2 3'.split()
5096 args = parser.parse_intermixed_args(argv)
5097 # rest gets [1,2,3] despite the foo and bar strings
5098 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args)
5099
5100 args, extras = parser.parse_known_args(argv)
5101 # cannot parse the '1,2,3'
5102 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[]), args)
5103 self.assertEqual(["1", "2", "3"], extras)
5104
5105 argv = 'cmd --foo x 1 --error 2 --bar y 3'.split()
5106 args, extras = parser.parse_known_intermixed_args(argv)
5107 # unknown optionals go into extras
5108 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1]), args)
5109 self.assertEqual(['--error', '2', '3'], extras)
5110
5111 # restores attributes that were temporarily changed
5112 self.assertIsNone(parser.usage)
5113 self.assertEqual(bar.required, True)
5114
5115 def test_remainder(self):
5116 # Intermixed and remainder are incompatible
5117 parser = ErrorRaisingArgumentParser(prog='PROG')
5118 parser.add_argument('-z')
5119 parser.add_argument('x')
5120 parser.add_argument('y', nargs='...')
5121 argv = 'X A B -z Z'.split()
5122 # intermixed fails with '...' (also 'A...')
5123 # self.assertRaises(TypeError, parser.parse_intermixed_args, argv)
5124 with self.assertRaises(TypeError) as cm:
5125 parser.parse_intermixed_args(argv)
5126 self.assertRegex(str(cm.exception), r'\.\.\.')
5127
5128 def test_exclusive(self):
5129 # mutually exclusive group; intermixed works fine
5130 parser = ErrorRaisingArgumentParser(prog='PROG')
5131 group = parser.add_mutually_exclusive_group(required=True)
5132 group.add_argument('--foo', action='store_true', help='FOO')
5133 group.add_argument('--spam', help='SPAM')
5134 parser.add_argument('badger', nargs='*', default='X', help='BADGER')
5135 args = parser.parse_intermixed_args('1 --foo 2'.split())
5136 self.assertEqual(NS(badger=['1', '2'], foo=True, spam=None), args)
5137 self.assertRaises(ArgumentParserError, parser.parse_intermixed_args, '1 2'.split())
5138 self.assertEqual(group.required, True)
5139
5140 def test_exclusive_incompatible(self):
5141 # mutually exclusive group including positional - fail
5142 parser = ErrorRaisingArgumentParser(prog='PROG')
5143 group = parser.add_mutually_exclusive_group(required=True)
5144 group.add_argument('--foo', action='store_true', help='FOO')
5145 group.add_argument('--spam', help='SPAM')
5146 group.add_argument('badger', nargs='*', default='X', help='BADGER')
5147 self.assertRaises(TypeError, parser.parse_intermixed_args, [])
5148 self.assertEqual(group.required, True)
5149
5150class TestIntermixedMessageContentError(TestCase):
5151 # case where Intermixed gives different error message
5152 # error is raised by 1st parsing step
5153 def test_missing_argument_name_in_message(self):
5154 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
5155 parser.add_argument('req_pos', type=str)
5156 parser.add_argument('-req_opt', type=int, required=True)
5157
5158 with self.assertRaises(ArgumentParserError) as cm:
5159 parser.parse_args([])
5160 msg = str(cm.exception)
5161 self.assertRegex(msg, 'req_pos')
5162 self.assertRegex(msg, 'req_opt')
5163
5164 with self.assertRaises(ArgumentParserError) as cm:
5165 parser.parse_intermixed_args([])
5166 msg = str(cm.exception)
5167 self.assertNotRegex(msg, 'req_pos')
5168 self.assertRegex(msg, 'req_opt')
5169
Steven Bethard8d9a4622011-03-26 17:33:56 +01005170# ==========================
5171# add_argument metavar tests
5172# ==========================
5173
5174class TestAddArgumentMetavar(TestCase):
5175
5176 EXPECTED_MESSAGE = "length of metavar tuple does not match nargs"
5177
5178 def do_test_no_exception(self, nargs, metavar):
5179 parser = argparse.ArgumentParser()
5180 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
5181
5182 def do_test_exception(self, nargs, metavar):
5183 parser = argparse.ArgumentParser()
5184 with self.assertRaises(ValueError) as cm:
5185 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
5186 self.assertEqual(cm.exception.args[0], self.EXPECTED_MESSAGE)
5187
5188 # Unit tests for different values of metavar when nargs=None
5189
5190 def test_nargs_None_metavar_string(self):
5191 self.do_test_no_exception(nargs=None, metavar="1")
5192
5193 def test_nargs_None_metavar_length0(self):
5194 self.do_test_exception(nargs=None, metavar=tuple())
5195
5196 def test_nargs_None_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005197 self.do_test_no_exception(nargs=None, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005198
5199 def test_nargs_None_metavar_length2(self):
5200 self.do_test_exception(nargs=None, metavar=("1", "2"))
5201
5202 def test_nargs_None_metavar_length3(self):
5203 self.do_test_exception(nargs=None, metavar=("1", "2", "3"))
5204
5205 # Unit tests for different values of metavar when nargs=?
5206
5207 def test_nargs_optional_metavar_string(self):
5208 self.do_test_no_exception(nargs="?", metavar="1")
5209
5210 def test_nargs_optional_metavar_length0(self):
5211 self.do_test_exception(nargs="?", metavar=tuple())
5212
5213 def test_nargs_optional_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005214 self.do_test_no_exception(nargs="?", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005215
5216 def test_nargs_optional_metavar_length2(self):
5217 self.do_test_exception(nargs="?", metavar=("1", "2"))
5218
5219 def test_nargs_optional_metavar_length3(self):
5220 self.do_test_exception(nargs="?", metavar=("1", "2", "3"))
5221
5222 # Unit tests for different values of metavar when nargs=*
5223
5224 def test_nargs_zeroormore_metavar_string(self):
5225 self.do_test_no_exception(nargs="*", metavar="1")
5226
5227 def test_nargs_zeroormore_metavar_length0(self):
5228 self.do_test_exception(nargs="*", metavar=tuple())
5229
5230 def test_nargs_zeroormore_metavar_length1(self):
Brandt Buchera0ed99b2019-11-11 12:47:48 -08005231 self.do_test_no_exception(nargs="*", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005232
5233 def test_nargs_zeroormore_metavar_length2(self):
5234 self.do_test_no_exception(nargs="*", metavar=("1", "2"))
5235
5236 def test_nargs_zeroormore_metavar_length3(self):
5237 self.do_test_exception(nargs="*", metavar=("1", "2", "3"))
5238
5239 # Unit tests for different values of metavar when nargs=+
5240
5241 def test_nargs_oneormore_metavar_string(self):
5242 self.do_test_no_exception(nargs="+", metavar="1")
5243
5244 def test_nargs_oneormore_metavar_length0(self):
5245 self.do_test_exception(nargs="+", metavar=tuple())
5246
5247 def test_nargs_oneormore_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005248 self.do_test_exception(nargs="+", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005249
5250 def test_nargs_oneormore_metavar_length2(self):
5251 self.do_test_no_exception(nargs="+", metavar=("1", "2"))
5252
5253 def test_nargs_oneormore_metavar_length3(self):
5254 self.do_test_exception(nargs="+", metavar=("1", "2", "3"))
5255
5256 # Unit tests for different values of metavar when nargs=...
5257
5258 def test_nargs_remainder_metavar_string(self):
5259 self.do_test_no_exception(nargs="...", metavar="1")
5260
5261 def test_nargs_remainder_metavar_length0(self):
5262 self.do_test_no_exception(nargs="...", metavar=tuple())
5263
5264 def test_nargs_remainder_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005265 self.do_test_no_exception(nargs="...", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005266
5267 def test_nargs_remainder_metavar_length2(self):
5268 self.do_test_no_exception(nargs="...", metavar=("1", "2"))
5269
5270 def test_nargs_remainder_metavar_length3(self):
5271 self.do_test_no_exception(nargs="...", metavar=("1", "2", "3"))
5272
5273 # Unit tests for different values of metavar when nargs=A...
5274
5275 def test_nargs_parser_metavar_string(self):
5276 self.do_test_no_exception(nargs="A...", metavar="1")
5277
5278 def test_nargs_parser_metavar_length0(self):
5279 self.do_test_exception(nargs="A...", metavar=tuple())
5280
5281 def test_nargs_parser_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005282 self.do_test_no_exception(nargs="A...", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005283
5284 def test_nargs_parser_metavar_length2(self):
5285 self.do_test_exception(nargs="A...", metavar=("1", "2"))
5286
5287 def test_nargs_parser_metavar_length3(self):
5288 self.do_test_exception(nargs="A...", metavar=("1", "2", "3"))
5289
5290 # Unit tests for different values of metavar when nargs=1
5291
5292 def test_nargs_1_metavar_string(self):
5293 self.do_test_no_exception(nargs=1, metavar="1")
5294
5295 def test_nargs_1_metavar_length0(self):
5296 self.do_test_exception(nargs=1, metavar=tuple())
5297
5298 def test_nargs_1_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005299 self.do_test_no_exception(nargs=1, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005300
5301 def test_nargs_1_metavar_length2(self):
5302 self.do_test_exception(nargs=1, metavar=("1", "2"))
5303
5304 def test_nargs_1_metavar_length3(self):
5305 self.do_test_exception(nargs=1, metavar=("1", "2", "3"))
5306
5307 # Unit tests for different values of metavar when nargs=2
5308
5309 def test_nargs_2_metavar_string(self):
5310 self.do_test_no_exception(nargs=2, metavar="1")
5311
5312 def test_nargs_2_metavar_length0(self):
5313 self.do_test_exception(nargs=2, metavar=tuple())
5314
5315 def test_nargs_2_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005316 self.do_test_exception(nargs=2, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005317
5318 def test_nargs_2_metavar_length2(self):
5319 self.do_test_no_exception(nargs=2, metavar=("1", "2"))
5320
5321 def test_nargs_2_metavar_length3(self):
5322 self.do_test_exception(nargs=2, metavar=("1", "2", "3"))
5323
5324 # Unit tests for different values of metavar when nargs=3
5325
5326 def test_nargs_3_metavar_string(self):
5327 self.do_test_no_exception(nargs=3, metavar="1")
5328
5329 def test_nargs_3_metavar_length0(self):
5330 self.do_test_exception(nargs=3, metavar=tuple())
5331
5332 def test_nargs_3_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005333 self.do_test_exception(nargs=3, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005334
5335 def test_nargs_3_metavar_length2(self):
5336 self.do_test_exception(nargs=3, metavar=("1", "2"))
5337
5338 def test_nargs_3_metavar_length3(self):
5339 self.do_test_no_exception(nargs=3, metavar=("1", "2", "3"))
5340
tmblweed4b3e9752019-08-01 21:57:13 -07005341
5342class TestInvalidNargs(TestCase):
5343
5344 EXPECTED_INVALID_MESSAGE = "invalid nargs value"
5345 EXPECTED_RANGE_MESSAGE = ("nargs for store actions must be != 0; if you "
5346 "have nothing to store, actions such as store "
5347 "true or store const may be more appropriate")
5348
5349 def do_test_range_exception(self, nargs):
5350 parser = argparse.ArgumentParser()
5351 with self.assertRaises(ValueError) as cm:
5352 parser.add_argument("--foo", nargs=nargs)
5353 self.assertEqual(cm.exception.args[0], self.EXPECTED_RANGE_MESSAGE)
5354
5355 def do_test_invalid_exception(self, nargs):
5356 parser = argparse.ArgumentParser()
5357 with self.assertRaises(ValueError) as cm:
5358 parser.add_argument("--foo", nargs=nargs)
5359 self.assertEqual(cm.exception.args[0], self.EXPECTED_INVALID_MESSAGE)
5360
5361 # Unit tests for different values of nargs
5362
5363 def test_nargs_alphabetic(self):
5364 self.do_test_invalid_exception(nargs='a')
5365 self.do_test_invalid_exception(nargs="abcd")
5366
5367 def test_nargs_zero(self):
5368 self.do_test_range_exception(nargs=0)
5369
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005370# ============================
5371# from argparse import * tests
5372# ============================
5373
5374class TestImportStar(TestCase):
5375
5376 def test(self):
5377 for name in argparse.__all__:
5378 self.assertTrue(hasattr(argparse, name))
5379
Steven Bethard72c55382010-11-01 15:23:12 +00005380 def test_all_exports_everything_but_modules(self):
5381 items = [
5382 name
5383 for name, value in vars(argparse).items()
Éric Araujo12159152010-12-04 17:31:49 +00005384 if not (name.startswith("_") or name == 'ngettext')
Steven Bethard72c55382010-11-01 15:23:12 +00005385 if not inspect.ismodule(value)
5386 ]
5387 self.assertEqual(sorted(items), sorted(argparse.__all__))
5388
wim glenn66f02aa2018-06-08 05:12:49 -05005389
5390class TestWrappingMetavar(TestCase):
5391
5392 def setUp(self):
Berker Peksag74102c92018-07-25 18:23:44 +03005393 super().setUp()
wim glenn66f02aa2018-06-08 05:12:49 -05005394 self.parser = ErrorRaisingArgumentParser(
5395 'this_is_spammy_prog_with_a_long_name_sorry_about_the_name'
5396 )
5397 # this metavar was triggering library assertion errors due to usage
5398 # message formatting incorrectly splitting on the ] chars within
5399 metavar = '<http[s]://example:1234>'
5400 self.parser.add_argument('--proxy', metavar=metavar)
5401
5402 def test_help_with_metavar(self):
5403 help_text = self.parser.format_help()
5404 self.assertEqual(help_text, textwrap.dedent('''\
5405 usage: this_is_spammy_prog_with_a_long_name_sorry_about_the_name
5406 [-h] [--proxy <http[s]://example:1234>]
5407
Raymond Hettinger41b223d2020-12-23 09:40:56 -08005408 options:
wim glenn66f02aa2018-06-08 05:12:49 -05005409 -h, --help show this help message and exit
5410 --proxy <http[s]://example:1234>
5411 '''))
5412
5413
Hai Shif5456382019-09-12 05:56:05 -05005414class TestExitOnError(TestCase):
5415
5416 def setUp(self):
5417 self.parser = argparse.ArgumentParser(exit_on_error=False)
5418 self.parser.add_argument('--integers', metavar='N', type=int)
5419
5420 def test_exit_on_error_with_good_args(self):
5421 ns = self.parser.parse_args('--integers 4'.split())
5422 self.assertEqual(ns, argparse.Namespace(integers=4))
5423
5424 def test_exit_on_error_with_bad_args(self):
5425 with self.assertRaises(argparse.ArgumentError):
5426 self.parser.parse_args('--integers a'.split())
5427
5428
Serhiy Storchakabedce352021-09-19 22:36:03 +03005429def tearDownModule():
Benjamin Peterson4fd181c2010-03-02 23:46:42 +00005430 # Remove global references to avoid looking like we have refleaks.
5431 RFile.seen = {}
5432 WFile.seen = set()
5433
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005434
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005435if __name__ == '__main__':
Serhiy Storchakabedce352021-09-19 22:36:03 +03005436 unittest.main()