blob: 6680feb016a4d86609af49cc42737bb489a8ef46 [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
Miss Islington (bot)6e4101a2021-09-17 23:47:16 -07003098 def test_set_defaults_on_subparser_with_namespace(self):
3099 parser = argparse.ArgumentParser()
3100 xparser = parser.add_subparsers().add_parser('X')
3101 xparser.set_defaults(foo=1)
3102 self.assertEqual(NS(foo=2), parser.parse_args(['X'], NS(foo=2)))
3103
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003104 def test_set_defaults_same_as_add_argument(self):
3105 parser = ErrorRaisingArgumentParser()
3106 parser.set_defaults(w='W', x='X', y='Y', z='Z')
3107 parser.add_argument('-w')
3108 parser.add_argument('-x', default='XX')
3109 parser.add_argument('y', nargs='?')
3110 parser.add_argument('z', nargs='?', default='ZZ')
3111
3112 # defaults set previously
3113 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
3114 parser.parse_args([]))
3115
3116 # reset defaults
3117 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
3118 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
3119 parser.parse_args([]))
3120
3121 def test_set_defaults_same_as_add_argument_group(self):
3122 parser = ErrorRaisingArgumentParser()
3123 parser.set_defaults(w='W', x='X', y='Y', z='Z')
3124 group = parser.add_argument_group('foo')
3125 group.add_argument('-w')
3126 group.add_argument('-x', default='XX')
3127 group.add_argument('y', nargs='?')
3128 group.add_argument('z', nargs='?', default='ZZ')
3129
3130
3131 # defaults set previously
3132 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
3133 parser.parse_args([]))
3134
3135 # reset defaults
3136 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
3137 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
3138 parser.parse_args([]))
3139
3140# =================
3141# Get default tests
3142# =================
3143
3144class TestGetDefault(TestCase):
3145
3146 def test_get_default(self):
3147 parser = ErrorRaisingArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003148 self.assertIsNone(parser.get_default("foo"))
3149 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003150
3151 parser.add_argument("--foo")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003152 self.assertIsNone(parser.get_default("foo"))
3153 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003154
3155 parser.add_argument("--bar", type=int, default=42)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003156 self.assertIsNone(parser.get_default("foo"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003157 self.assertEqual(42, parser.get_default("bar"))
3158
3159 parser.set_defaults(foo="badger")
3160 self.assertEqual("badger", parser.get_default("foo"))
3161 self.assertEqual(42, parser.get_default("bar"))
3162
3163# ==========================
3164# Namespace 'contains' tests
3165# ==========================
3166
3167class TestNamespaceContainsSimple(TestCase):
3168
3169 def test_empty(self):
3170 ns = argparse.Namespace()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003171 self.assertNotIn('', ns)
3172 self.assertNotIn('x', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003173
3174 def test_non_empty(self):
3175 ns = argparse.Namespace(x=1, y=2)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003176 self.assertNotIn('', ns)
3177 self.assertIn('x', ns)
3178 self.assertIn('y', ns)
3179 self.assertNotIn('xx', ns)
3180 self.assertNotIn('z', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003181
3182# =====================
3183# Help formatting tests
3184# =====================
3185
3186class TestHelpFormattingMetaclass(type):
3187
3188 def __init__(cls, name, bases, bodydict):
3189 if name == 'HelpTestCase':
3190 return
3191
3192 class AddTests(object):
3193
3194 def __init__(self, test_class, func_suffix, std_name):
3195 self.func_suffix = func_suffix
3196 self.std_name = std_name
3197
3198 for test_func in [self.test_format,
3199 self.test_print,
3200 self.test_print_file]:
3201 test_name = '%s_%s' % (test_func.__name__, func_suffix)
3202
3203 def test_wrapper(self, test_func=test_func):
3204 test_func(self)
3205 try:
3206 test_wrapper.__name__ = test_name
3207 except TypeError:
3208 pass
3209 setattr(test_class, test_name, test_wrapper)
3210
3211 def _get_parser(self, tester):
3212 parser = argparse.ArgumentParser(
3213 *tester.parser_signature.args,
3214 **tester.parser_signature.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003215 for argument_sig in getattr(tester, 'argument_signatures', []):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003216 parser.add_argument(*argument_sig.args,
3217 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003218 group_sigs = getattr(tester, 'argument_group_signatures', [])
3219 for group_sig, argument_sigs in group_sigs:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003220 group = parser.add_argument_group(*group_sig.args,
3221 **group_sig.kwargs)
3222 for argument_sig in argument_sigs:
3223 group.add_argument(*argument_sig.args,
3224 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003225 subparsers_sigs = getattr(tester, 'subparsers_signatures', [])
3226 if subparsers_sigs:
3227 subparsers = parser.add_subparsers()
3228 for subparser_sig in subparsers_sigs:
3229 subparsers.add_parser(*subparser_sig.args,
3230 **subparser_sig.kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003231 return parser
3232
3233 def _test(self, tester, parser_text):
3234 expected_text = getattr(tester, self.func_suffix)
3235 expected_text = textwrap.dedent(expected_text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003236 tester.assertEqual(expected_text, parser_text)
3237
3238 def test_format(self, tester):
3239 parser = self._get_parser(tester)
3240 format = getattr(parser, 'format_%s' % self.func_suffix)
3241 self._test(tester, format())
3242
3243 def test_print(self, tester):
3244 parser = self._get_parser(tester)
3245 print_ = getattr(parser, 'print_%s' % self.func_suffix)
3246 old_stream = getattr(sys, self.std_name)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003247 setattr(sys, self.std_name, StdIOBuffer())
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003248 try:
3249 print_()
3250 parser_text = getattr(sys, self.std_name).getvalue()
3251 finally:
3252 setattr(sys, self.std_name, old_stream)
3253 self._test(tester, parser_text)
3254
3255 def test_print_file(self, tester):
3256 parser = self._get_parser(tester)
3257 print_ = getattr(parser, 'print_%s' % self.func_suffix)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003258 sfile = StdIOBuffer()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003259 print_(sfile)
3260 parser_text = sfile.getvalue()
3261 self._test(tester, parser_text)
3262
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003263 # add tests for {format,print}_{usage,help}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003264 for func_suffix, std_name in [('usage', 'stdout'),
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003265 ('help', 'stdout')]:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003266 AddTests(cls, func_suffix, std_name)
3267
3268bases = TestCase,
3269HelpTestCase = TestHelpFormattingMetaclass('HelpTestCase', bases, {})
3270
3271
3272class TestHelpBiggerOptionals(HelpTestCase):
3273 """Make sure that argument help aligns when options are longer"""
3274
3275 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003276 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003277 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003278 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003279 Sig('-x', action='store_true', help='X HELP'),
3280 Sig('--y', help='Y HELP'),
3281 Sig('foo', help='FOO HELP'),
3282 Sig('bar', help='BAR HELP'),
3283 ]
3284 argument_group_signatures = []
3285 usage = '''\
3286 usage: PROG [-h] [-v] [-x] [--y Y] foo bar
3287 '''
3288 help = usage + '''\
3289
3290 DESCRIPTION
3291
3292 positional arguments:
3293 foo FOO HELP
3294 bar BAR HELP
3295
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003296 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003297 -h, --help show this help message and exit
3298 -v, --version show program's version number and exit
3299 -x X HELP
3300 --y Y Y HELP
3301
3302 EPILOG
3303 '''
3304 version = '''\
3305 0.1
3306 '''
3307
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003308class TestShortColumns(HelpTestCase):
3309 '''Test extremely small number of columns.
3310
3311 TestCase prevents "COLUMNS" from being too small in the tests themselves,
Martin Panter2e4571a2015-11-14 01:07:43 +00003312 but we don't want any exceptions thrown in such cases. Only ugly representation.
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003313 '''
3314 def setUp(self):
Hai Shi46605972020-08-04 00:49:18 +08003315 env = os_helper.EnvironmentVarGuard()
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003316 env.set("COLUMNS", '15')
3317 self.addCleanup(env.__exit__)
3318
3319 parser_signature = TestHelpBiggerOptionals.parser_signature
3320 argument_signatures = TestHelpBiggerOptionals.argument_signatures
3321 argument_group_signatures = TestHelpBiggerOptionals.argument_group_signatures
3322 usage = '''\
3323 usage: PROG
3324 [-h]
3325 [-v]
3326 [-x]
3327 [--y Y]
3328 foo
3329 bar
3330 '''
3331 help = usage + '''\
3332
3333 DESCRIPTION
3334
3335 positional arguments:
3336 foo
3337 FOO HELP
3338 bar
3339 BAR HELP
3340
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003341 options:
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003342 -h, --help
3343 show this
3344 help
3345 message and
3346 exit
3347 -v, --version
3348 show
3349 program's
3350 version
3351 number and
3352 exit
3353 -x
3354 X HELP
3355 --y Y
3356 Y HELP
3357
3358 EPILOG
3359 '''
3360 version = TestHelpBiggerOptionals.version
3361
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003362
3363class TestHelpBiggerOptionalGroups(HelpTestCase):
3364 """Make sure that argument help aligns when options are longer"""
3365
3366 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003367 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003368 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003369 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003370 Sig('-x', action='store_true', help='X HELP'),
3371 Sig('--y', help='Y HELP'),
3372 Sig('foo', help='FOO HELP'),
3373 Sig('bar', help='BAR HELP'),
3374 ]
3375 argument_group_signatures = [
3376 (Sig('GROUP TITLE', description='GROUP DESCRIPTION'), [
3377 Sig('baz', help='BAZ HELP'),
3378 Sig('-z', nargs='+', help='Z HELP')]),
3379 ]
3380 usage = '''\
3381 usage: PROG [-h] [-v] [-x] [--y Y] [-z Z [Z ...]] foo bar baz
3382 '''
3383 help = usage + '''\
3384
3385 DESCRIPTION
3386
3387 positional arguments:
3388 foo FOO HELP
3389 bar BAR HELP
3390
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003391 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003392 -h, --help show this help message and exit
3393 -v, --version show program's version number and exit
3394 -x X HELP
3395 --y Y Y HELP
3396
3397 GROUP TITLE:
3398 GROUP DESCRIPTION
3399
3400 baz BAZ HELP
3401 -z Z [Z ...] Z HELP
3402
3403 EPILOG
3404 '''
3405 version = '''\
3406 0.1
3407 '''
3408
3409
3410class TestHelpBiggerPositionals(HelpTestCase):
3411 """Make sure that help aligns when arguments are longer"""
3412
3413 parser_signature = Sig(usage='USAGE', description='DESCRIPTION')
3414 argument_signatures = [
3415 Sig('-x', action='store_true', help='X HELP'),
3416 Sig('--y', help='Y HELP'),
3417 Sig('ekiekiekifekang', help='EKI HELP'),
3418 Sig('bar', help='BAR HELP'),
3419 ]
3420 argument_group_signatures = []
3421 usage = '''\
3422 usage: USAGE
3423 '''
3424 help = usage + '''\
3425
3426 DESCRIPTION
3427
3428 positional arguments:
3429 ekiekiekifekang EKI HELP
3430 bar BAR HELP
3431
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003432 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003433 -h, --help show this help message and exit
3434 -x X HELP
3435 --y Y Y HELP
3436 '''
3437
3438 version = ''
3439
3440
3441class TestHelpReformatting(HelpTestCase):
3442 """Make sure that text after short names starts on the first line"""
3443
3444 parser_signature = Sig(
3445 prog='PROG',
3446 description=' oddly formatted\n'
3447 'description\n'
3448 '\n'
3449 'that is so long that it should go onto multiple '
3450 'lines when wrapped')
3451 argument_signatures = [
3452 Sig('-x', metavar='XX', help='oddly\n'
3453 ' formatted -x help'),
3454 Sig('y', metavar='yyy', help='normal y help'),
3455 ]
3456 argument_group_signatures = [
3457 (Sig('title', description='\n'
3458 ' oddly formatted group\n'
3459 '\n'
3460 'description'),
3461 [Sig('-a', action='store_true',
3462 help=' oddly \n'
3463 'formatted -a help \n'
3464 ' again, so long that it should be wrapped over '
3465 'multiple lines')]),
3466 ]
3467 usage = '''\
3468 usage: PROG [-h] [-x XX] [-a] yyy
3469 '''
3470 help = usage + '''\
3471
3472 oddly formatted description that is so long that it should go onto \
3473multiple
3474 lines when wrapped
3475
3476 positional arguments:
3477 yyy normal y help
3478
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003479 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003480 -h, --help show this help message and exit
3481 -x XX oddly formatted -x help
3482
3483 title:
3484 oddly formatted group description
3485
3486 -a oddly formatted -a help again, so long that it should \
3487be wrapped
3488 over multiple lines
3489 '''
3490 version = ''
3491
3492
3493class TestHelpWrappingShortNames(HelpTestCase):
3494 """Make sure that text after short names starts on the first line"""
3495
3496 parser_signature = Sig(prog='PROG', description= 'D\nD' * 30)
3497 argument_signatures = [
3498 Sig('-x', metavar='XX', help='XHH HX' * 20),
3499 Sig('y', metavar='yyy', help='YH YH' * 20),
3500 ]
3501 argument_group_signatures = [
3502 (Sig('ALPHAS'), [
3503 Sig('-a', action='store_true', help='AHHH HHA' * 10)]),
3504 ]
3505 usage = '''\
3506 usage: PROG [-h] [-x XX] [-a] yyy
3507 '''
3508 help = usage + '''\
3509
3510 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3511DD DD DD
3512 DD DD DD DD D
3513
3514 positional arguments:
3515 yyy YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3516YHYH YHYH
3517 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3518
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003519 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003520 -h, --help show this help message and exit
3521 -x XX XHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH \
3522HXXHH HXXHH
3523 HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HX
3524
3525 ALPHAS:
3526 -a AHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH \
3527HHAAHHH
3528 HHAAHHH HHAAHHH HHA
3529 '''
3530 version = ''
3531
3532
3533class TestHelpWrappingLongNames(HelpTestCase):
3534 """Make sure that text after long names starts on the next line"""
3535
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003536 parser_signature = Sig(usage='USAGE', description= 'D D' * 30)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003537 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003538 Sig('-v', '--version', action='version', version='V V' * 30),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003539 Sig('-x', metavar='X' * 25, help='XH XH' * 20),
3540 Sig('y', metavar='y' * 25, help='YH YH' * 20),
3541 ]
3542 argument_group_signatures = [
3543 (Sig('ALPHAS'), [
3544 Sig('-a', metavar='A' * 25, help='AH AH' * 20),
3545 Sig('z', metavar='z' * 25, help='ZH ZH' * 20)]),
3546 ]
3547 usage = '''\
3548 usage: USAGE
3549 '''
3550 help = usage + '''\
3551
3552 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3553DD DD DD
3554 DD DD DD DD D
3555
3556 positional arguments:
3557 yyyyyyyyyyyyyyyyyyyyyyyyy
3558 YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3559YHYH YHYH
3560 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3561
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003562 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003563 -h, --help show this help message and exit
3564 -v, --version show program's version number and exit
3565 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3566 XH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH \
3567XHXH XHXH
3568 XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XH
3569
3570 ALPHAS:
3571 -a AAAAAAAAAAAAAAAAAAAAAAAAA
3572 AH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH \
3573AHAH AHAH
3574 AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AH
3575 zzzzzzzzzzzzzzzzzzzzzzzzz
3576 ZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH \
3577ZHZH ZHZH
3578 ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZH
3579 '''
3580 version = '''\
3581 V VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV \
3582VV VV VV
3583 VV VV VV VV V
3584 '''
3585
3586
3587class TestHelpUsage(HelpTestCase):
3588 """Test basic usage messages"""
3589
3590 parser_signature = Sig(prog='PROG')
3591 argument_signatures = [
3592 Sig('-w', nargs='+', help='w'),
3593 Sig('-x', nargs='*', help='x'),
3594 Sig('a', help='a'),
3595 Sig('b', help='b', nargs=2),
3596 Sig('c', help='c', nargs='?'),
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003597 Sig('--foo', help='Whether to foo', action=argparse.BooleanOptionalAction),
3598 Sig('--bar', help='Whether to bar', default=True,
3599 action=argparse.BooleanOptionalAction),
3600 Sig('-f', '--foobar', '--barfoo', action=argparse.BooleanOptionalAction),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003601 ]
3602 argument_group_signatures = [
3603 (Sig('group'), [
3604 Sig('-y', nargs='?', help='y'),
3605 Sig('-z', nargs=3, help='z'),
3606 Sig('d', help='d', nargs='*'),
3607 Sig('e', help='e', nargs='+'),
3608 ])
3609 ]
3610 usage = '''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08003611 usage: PROG [-h] [-w W [W ...]] [-x [X ...]] [--foo | --no-foo]
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003612 [--bar | --no-bar]
3613 [-f | --foobar | --no-foobar | --barfoo | --no-barfoo] [-y [Y]]
3614 [-z Z Z Z]
Brandt Buchera0ed99b2019-11-11 12:47:48 -08003615 a b b [c] [d ...] e [e ...]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003616 '''
3617 help = usage + '''\
3618
3619 positional arguments:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003620 a a
3621 b b
3622 c c
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003623
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003624 options:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003625 -h, --help show this help message and exit
3626 -w W [W ...] w
Brandt Buchera0ed99b2019-11-11 12:47:48 -08003627 -x [X ...] x
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003628 --foo, --no-foo Whether to foo
3629 --bar, --no-bar Whether to bar (default: True)
3630 -f, --foobar, --no-foobar, --barfoo, --no-barfoo
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003631
3632 group:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003633 -y [Y] y
3634 -z Z Z Z z
3635 d d
3636 e e
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003637 '''
3638 version = ''
3639
3640
3641class TestHelpOnlyUserGroups(HelpTestCase):
3642 """Test basic usage messages"""
3643
3644 parser_signature = Sig(prog='PROG', add_help=False)
3645 argument_signatures = []
3646 argument_group_signatures = [
3647 (Sig('xxxx'), [
3648 Sig('-x', help='x'),
3649 Sig('a', help='a'),
3650 ]),
3651 (Sig('yyyy'), [
3652 Sig('b', help='b'),
3653 Sig('-y', help='y'),
3654 ]),
3655 ]
3656 usage = '''\
3657 usage: PROG [-x X] [-y Y] a b
3658 '''
3659 help = usage + '''\
3660
3661 xxxx:
3662 -x X x
3663 a a
3664
3665 yyyy:
3666 b b
3667 -y Y y
3668 '''
3669 version = ''
3670
3671
3672class TestHelpUsageLongProg(HelpTestCase):
3673 """Test usage messages where the prog is long"""
3674
3675 parser_signature = Sig(prog='P' * 60)
3676 argument_signatures = [
3677 Sig('-w', metavar='W'),
3678 Sig('-x', metavar='X'),
3679 Sig('a'),
3680 Sig('b'),
3681 ]
3682 argument_group_signatures = []
3683 usage = '''\
3684 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3685 [-h] [-w W] [-x X] a b
3686 '''
3687 help = usage + '''\
3688
3689 positional arguments:
3690 a
3691 b
3692
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003693 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003694 -h, --help show this help message and exit
3695 -w W
3696 -x X
3697 '''
3698 version = ''
3699
3700
3701class TestHelpUsageLongProgOptionsWrap(HelpTestCase):
3702 """Test usage messages where the prog is long and the optionals wrap"""
3703
3704 parser_signature = Sig(prog='P' * 60)
3705 argument_signatures = [
3706 Sig('-w', metavar='W' * 25),
3707 Sig('-x', metavar='X' * 25),
3708 Sig('-y', metavar='Y' * 25),
3709 Sig('-z', metavar='Z' * 25),
3710 Sig('a'),
3711 Sig('b'),
3712 ]
3713 argument_group_signatures = []
3714 usage = '''\
3715 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3716 [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3717[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3718 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3719 a b
3720 '''
3721 help = usage + '''\
3722
3723 positional arguments:
3724 a
3725 b
3726
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003727 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003728 -h, --help show this help message and exit
3729 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3730 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3731 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3732 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3733 '''
3734 version = ''
3735
3736
3737class TestHelpUsageLongProgPositionalsWrap(HelpTestCase):
3738 """Test usage messages where the prog is long and the positionals wrap"""
3739
3740 parser_signature = Sig(prog='P' * 60, add_help=False)
3741 argument_signatures = [
3742 Sig('a' * 25),
3743 Sig('b' * 25),
3744 Sig('c' * 25),
3745 ]
3746 argument_group_signatures = []
3747 usage = '''\
3748 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3749 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3750 ccccccccccccccccccccccccc
3751 '''
3752 help = usage + '''\
3753
3754 positional arguments:
3755 aaaaaaaaaaaaaaaaaaaaaaaaa
3756 bbbbbbbbbbbbbbbbbbbbbbbbb
3757 ccccccccccccccccccccccccc
3758 '''
3759 version = ''
3760
3761
3762class TestHelpUsageOptionalsWrap(HelpTestCase):
3763 """Test usage messages where the optionals wrap"""
3764
3765 parser_signature = Sig(prog='PROG')
3766 argument_signatures = [
3767 Sig('-w', metavar='W' * 25),
3768 Sig('-x', metavar='X' * 25),
3769 Sig('-y', metavar='Y' * 25),
3770 Sig('-z', metavar='Z' * 25),
3771 Sig('a'),
3772 Sig('b'),
3773 Sig('c'),
3774 ]
3775 argument_group_signatures = []
3776 usage = '''\
3777 usage: PROG [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3778[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3779 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] \
3780[-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3781 a b c
3782 '''
3783 help = usage + '''\
3784
3785 positional arguments:
3786 a
3787 b
3788 c
3789
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003790 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003791 -h, --help show this help message and exit
3792 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3793 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3794 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3795 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3796 '''
3797 version = ''
3798
3799
3800class TestHelpUsagePositionalsWrap(HelpTestCase):
3801 """Test usage messages where the positionals wrap"""
3802
3803 parser_signature = Sig(prog='PROG')
3804 argument_signatures = [
3805 Sig('-x'),
3806 Sig('-y'),
3807 Sig('-z'),
3808 Sig('a' * 25),
3809 Sig('b' * 25),
3810 Sig('c' * 25),
3811 ]
3812 argument_group_signatures = []
3813 usage = '''\
3814 usage: PROG [-h] [-x X] [-y Y] [-z Z]
3815 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3816 ccccccccccccccccccccccccc
3817 '''
3818 help = usage + '''\
3819
3820 positional arguments:
3821 aaaaaaaaaaaaaaaaaaaaaaaaa
3822 bbbbbbbbbbbbbbbbbbbbbbbbb
3823 ccccccccccccccccccccccccc
3824
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003825 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003826 -h, --help show this help message and exit
3827 -x X
3828 -y Y
3829 -z Z
3830 '''
3831 version = ''
3832
3833
3834class TestHelpUsageOptionalsPositionalsWrap(HelpTestCase):
3835 """Test usage messages where the optionals and positionals wrap"""
3836
3837 parser_signature = Sig(prog='PROG')
3838 argument_signatures = [
3839 Sig('-x', metavar='X' * 25),
3840 Sig('-y', metavar='Y' * 25),
3841 Sig('-z', metavar='Z' * 25),
3842 Sig('a' * 25),
3843 Sig('b' * 25),
3844 Sig('c' * 25),
3845 ]
3846 argument_group_signatures = []
3847 usage = '''\
3848 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3849[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3850 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3851 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3852 ccccccccccccccccccccccccc
3853 '''
3854 help = usage + '''\
3855
3856 positional arguments:
3857 aaaaaaaaaaaaaaaaaaaaaaaaa
3858 bbbbbbbbbbbbbbbbbbbbbbbbb
3859 ccccccccccccccccccccccccc
3860
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003861 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003862 -h, --help show this help message and exit
3863 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3864 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3865 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3866 '''
3867 version = ''
3868
3869
3870class TestHelpUsageOptionalsOnlyWrap(HelpTestCase):
3871 """Test usage messages where there are only optionals and they wrap"""
3872
3873 parser_signature = Sig(prog='PROG')
3874 argument_signatures = [
3875 Sig('-x', metavar='X' * 25),
3876 Sig('-y', metavar='Y' * 25),
3877 Sig('-z', metavar='Z' * 25),
3878 ]
3879 argument_group_signatures = []
3880 usage = '''\
3881 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3882[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3883 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3884 '''
3885 help = usage + '''\
3886
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003887 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003888 -h, --help show this help message and exit
3889 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3890 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3891 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3892 '''
3893 version = ''
3894
3895
3896class TestHelpUsagePositionalsOnlyWrap(HelpTestCase):
3897 """Test usage messages where there are only positionals and they wrap"""
3898
3899 parser_signature = Sig(prog='PROG', add_help=False)
3900 argument_signatures = [
3901 Sig('a' * 25),
3902 Sig('b' * 25),
3903 Sig('c' * 25),
3904 ]
3905 argument_group_signatures = []
3906 usage = '''\
3907 usage: PROG aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3908 ccccccccccccccccccccccccc
3909 '''
3910 help = usage + '''\
3911
3912 positional arguments:
3913 aaaaaaaaaaaaaaaaaaaaaaaaa
3914 bbbbbbbbbbbbbbbbbbbbbbbbb
3915 ccccccccccccccccccccccccc
3916 '''
3917 version = ''
3918
3919
3920class TestHelpVariableExpansion(HelpTestCase):
3921 """Test that variables are expanded properly in help messages"""
3922
3923 parser_signature = Sig(prog='PROG')
3924 argument_signatures = [
3925 Sig('-x', type=int,
3926 help='x %(prog)s %(default)s %(type)s %%'),
3927 Sig('-y', action='store_const', default=42, const='XXX',
3928 help='y %(prog)s %(default)s %(const)s'),
3929 Sig('--foo', choices='abc',
3930 help='foo %(prog)s %(default)s %(choices)s'),
3931 Sig('--bar', default='baz', choices=[1, 2], metavar='BBB',
3932 help='bar %(prog)s %(default)s %(dest)s'),
3933 Sig('spam', help='spam %(prog)s %(default)s'),
3934 Sig('badger', default=0.5, help='badger %(prog)s %(default)s'),
3935 ]
3936 argument_group_signatures = [
3937 (Sig('group'), [
3938 Sig('-a', help='a %(prog)s %(default)s'),
3939 Sig('-b', default=-1, help='b %(prog)s %(default)s'),
3940 ])
3941 ]
3942 usage = ('''\
3943 usage: PROG [-h] [-x X] [-y] [--foo {a,b,c}] [--bar BBB] [-a A] [-b B]
3944 spam badger
3945 ''')
3946 help = usage + '''\
3947
3948 positional arguments:
3949 spam spam PROG None
3950 badger badger PROG 0.5
3951
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003952 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003953 -h, --help show this help message and exit
3954 -x X x PROG None int %
3955 -y y PROG 42 XXX
3956 --foo {a,b,c} foo PROG None a, b, c
3957 --bar BBB bar PROG baz bar
3958
3959 group:
3960 -a A a PROG None
3961 -b B b PROG -1
3962 '''
3963 version = ''
3964
3965
3966class TestHelpVariableExpansionUsageSupplied(HelpTestCase):
3967 """Test that variables are expanded properly when usage= is present"""
3968
3969 parser_signature = Sig(prog='PROG', usage='%(prog)s FOO')
3970 argument_signatures = []
3971 argument_group_signatures = []
3972 usage = ('''\
3973 usage: PROG FOO
3974 ''')
3975 help = usage + '''\
3976
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003977 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003978 -h, --help show this help message and exit
3979 '''
3980 version = ''
3981
3982
3983class TestHelpVariableExpansionNoArguments(HelpTestCase):
3984 """Test that variables are expanded properly with no arguments"""
3985
3986 parser_signature = Sig(prog='PROG', add_help=False)
3987 argument_signatures = []
3988 argument_group_signatures = []
3989 usage = ('''\
3990 usage: PROG
3991 ''')
3992 help = usage
3993 version = ''
3994
3995
3996class TestHelpSuppressUsage(HelpTestCase):
3997 """Test that items can be suppressed in usage messages"""
3998
3999 parser_signature = Sig(prog='PROG', usage=argparse.SUPPRESS)
4000 argument_signatures = [
4001 Sig('--foo', help='foo help'),
4002 Sig('spam', help='spam help'),
4003 ]
4004 argument_group_signatures = []
4005 help = '''\
4006 positional arguments:
4007 spam spam help
4008
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004009 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004010 -h, --help show this help message and exit
4011 --foo FOO foo help
4012 '''
4013 usage = ''
4014 version = ''
4015
4016
4017class TestHelpSuppressOptional(HelpTestCase):
4018 """Test that optional arguments can be suppressed in help messages"""
4019
4020 parser_signature = Sig(prog='PROG', add_help=False)
4021 argument_signatures = [
4022 Sig('--foo', help=argparse.SUPPRESS),
4023 Sig('spam', help='spam help'),
4024 ]
4025 argument_group_signatures = []
4026 usage = '''\
4027 usage: PROG spam
4028 '''
4029 help = usage + '''\
4030
4031 positional arguments:
4032 spam spam help
4033 '''
4034 version = ''
4035
4036
4037class TestHelpSuppressOptionalGroup(HelpTestCase):
4038 """Test that optional groups can be suppressed in help messages"""
4039
4040 parser_signature = Sig(prog='PROG')
4041 argument_signatures = [
4042 Sig('--foo', help='foo help'),
4043 Sig('spam', help='spam help'),
4044 ]
4045 argument_group_signatures = [
4046 (Sig('group'), [Sig('--bar', help=argparse.SUPPRESS)]),
4047 ]
4048 usage = '''\
4049 usage: PROG [-h] [--foo FOO] spam
4050 '''
4051 help = usage + '''\
4052
4053 positional arguments:
4054 spam spam help
4055
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004056 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004057 -h, --help show this help message and exit
4058 --foo FOO foo help
4059 '''
4060 version = ''
4061
4062
4063class TestHelpSuppressPositional(HelpTestCase):
4064 """Test that positional arguments can be suppressed in help messages"""
4065
4066 parser_signature = Sig(prog='PROG')
4067 argument_signatures = [
4068 Sig('--foo', help='foo help'),
4069 Sig('spam', help=argparse.SUPPRESS),
4070 ]
4071 argument_group_signatures = []
4072 usage = '''\
4073 usage: PROG [-h] [--foo FOO]
4074 '''
4075 help = usage + '''\
4076
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004077 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004078 -h, --help show this help message and exit
4079 --foo FOO foo help
4080 '''
4081 version = ''
4082
4083
4084class TestHelpRequiredOptional(HelpTestCase):
4085 """Test that required options don't look optional"""
4086
4087 parser_signature = Sig(prog='PROG')
4088 argument_signatures = [
4089 Sig('--foo', required=True, help='foo help'),
4090 ]
4091 argument_group_signatures = []
4092 usage = '''\
4093 usage: PROG [-h] --foo FOO
4094 '''
4095 help = usage + '''\
4096
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004097 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004098 -h, --help show this help message and exit
4099 --foo FOO foo help
4100 '''
4101 version = ''
4102
4103
4104class TestHelpAlternatePrefixChars(HelpTestCase):
4105 """Test that options display with different prefix characters"""
4106
4107 parser_signature = Sig(prog='PROG', prefix_chars='^;', add_help=False)
4108 argument_signatures = [
4109 Sig('^^foo', action='store_true', help='foo help'),
4110 Sig(';b', ';;bar', help='bar help'),
4111 ]
4112 argument_group_signatures = []
4113 usage = '''\
4114 usage: PROG [^^foo] [;b BAR]
4115 '''
4116 help = usage + '''\
4117
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004118 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004119 ^^foo foo help
4120 ;b BAR, ;;bar BAR bar help
4121 '''
4122 version = ''
4123
4124
4125class TestHelpNoHelpOptional(HelpTestCase):
4126 """Test that the --help argument can be suppressed help messages"""
4127
4128 parser_signature = Sig(prog='PROG', add_help=False)
4129 argument_signatures = [
4130 Sig('--foo', help='foo help'),
4131 Sig('spam', help='spam help'),
4132 ]
4133 argument_group_signatures = []
4134 usage = '''\
4135 usage: PROG [--foo FOO] spam
4136 '''
4137 help = usage + '''\
4138
4139 positional arguments:
4140 spam spam help
4141
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004142 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004143 --foo FOO foo help
4144 '''
4145 version = ''
4146
4147
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004148class TestHelpNone(HelpTestCase):
4149 """Test that no errors occur if no help is specified"""
4150
4151 parser_signature = Sig(prog='PROG')
4152 argument_signatures = [
4153 Sig('--foo'),
4154 Sig('spam'),
4155 ]
4156 argument_group_signatures = []
4157 usage = '''\
4158 usage: PROG [-h] [--foo FOO] spam
4159 '''
4160 help = usage + '''\
4161
4162 positional arguments:
4163 spam
4164
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004165 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004166 -h, --help show this help message and exit
4167 --foo FOO
4168 '''
4169 version = ''
4170
4171
4172class TestHelpTupleMetavar(HelpTestCase):
4173 """Test specifying metavar as a tuple"""
4174
4175 parser_signature = Sig(prog='PROG')
4176 argument_signatures = [
4177 Sig('-w', help='w', nargs='+', metavar=('W1', 'W2')),
4178 Sig('-x', help='x', nargs='*', metavar=('X1', 'X2')),
4179 Sig('-y', help='y', nargs=3, metavar=('Y1', 'Y2', 'Y3')),
4180 Sig('-z', help='z', nargs='?', metavar=('Z1', )),
4181 ]
4182 argument_group_signatures = []
4183 usage = '''\
4184 usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] \
4185[-z [Z1]]
4186 '''
4187 help = usage + '''\
4188
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004189 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004190 -h, --help show this help message and exit
4191 -w W1 [W2 ...] w
4192 -x [X1 [X2 ...]] x
4193 -y Y1 Y2 Y3 y
4194 -z [Z1] z
4195 '''
4196 version = ''
4197
4198
4199class TestHelpRawText(HelpTestCase):
4200 """Test the RawTextHelpFormatter"""
4201
4202 parser_signature = Sig(
4203 prog='PROG', formatter_class=argparse.RawTextHelpFormatter,
4204 description='Keep the formatting\n'
4205 ' exactly as it is written\n'
4206 '\n'
4207 'here\n')
4208
4209 argument_signatures = [
4210 Sig('--foo', help=' foo help should also\n'
4211 'appear as given here'),
4212 Sig('spam', help='spam help'),
4213 ]
4214 argument_group_signatures = [
4215 (Sig('title', description=' This text\n'
4216 ' should be indented\n'
4217 ' exactly like it is here\n'),
4218 [Sig('--bar', help='bar help')]),
4219 ]
4220 usage = '''\
4221 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
4222 '''
4223 help = usage + '''\
4224
4225 Keep the formatting
4226 exactly as it is written
4227
4228 here
4229
4230 positional arguments:
4231 spam spam help
4232
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004233 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004234 -h, --help show this help message and exit
4235 --foo FOO foo help should also
4236 appear as given here
4237
4238 title:
4239 This text
4240 should be indented
4241 exactly like it is here
4242
4243 --bar BAR bar help
4244 '''
4245 version = ''
4246
4247
4248class TestHelpRawDescription(HelpTestCase):
4249 """Test the RawTextHelpFormatter"""
4250
4251 parser_signature = Sig(
4252 prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter,
4253 description='Keep the formatting\n'
4254 ' exactly as it is written\n'
4255 '\n'
4256 'here\n')
4257
4258 argument_signatures = [
4259 Sig('--foo', help=' foo help should not\n'
4260 ' retain this odd formatting'),
4261 Sig('spam', help='spam help'),
4262 ]
4263 argument_group_signatures = [
4264 (Sig('title', description=' This text\n'
4265 ' should be indented\n'
4266 ' exactly like it is here\n'),
4267 [Sig('--bar', help='bar help')]),
4268 ]
4269 usage = '''\
4270 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
4271 '''
4272 help = usage + '''\
4273
4274 Keep the formatting
4275 exactly as it is written
4276
4277 here
4278
4279 positional arguments:
4280 spam spam help
4281
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004282 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004283 -h, --help show this help message and exit
4284 --foo FOO foo help should not retain this odd formatting
4285
4286 title:
4287 This text
4288 should be indented
4289 exactly like it is here
4290
4291 --bar BAR bar help
4292 '''
4293 version = ''
4294
4295
4296class TestHelpArgumentDefaults(HelpTestCase):
4297 """Test the ArgumentDefaultsHelpFormatter"""
4298
4299 parser_signature = Sig(
4300 prog='PROG', formatter_class=argparse.ArgumentDefaultsHelpFormatter,
4301 description='description')
4302
4303 argument_signatures = [
4304 Sig('--foo', help='foo help - oh and by the way, %(default)s'),
4305 Sig('--bar', action='store_true', help='bar help'),
Miss Islington (bot)6f6648e2021-08-17 02:40:41 -07004306 Sig('--taz', action=argparse.BooleanOptionalAction,
4307 help='Whether to taz it', default=True),
4308 Sig('--quux', help="Set the quux", default=42),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004309 Sig('spam', help='spam help'),
4310 Sig('badger', nargs='?', default='wooden', help='badger help'),
4311 ]
4312 argument_group_signatures = [
4313 (Sig('title', description='description'),
4314 [Sig('--baz', type=int, default=42, help='baz help')]),
4315 ]
4316 usage = '''\
Miss Islington (bot)6f6648e2021-08-17 02:40:41 -07004317 usage: PROG [-h] [--foo FOO] [--bar] [--taz | --no-taz] [--quux QUUX]
4318 [--baz BAZ]
4319 spam [badger]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004320 '''
4321 help = usage + '''\
4322
4323 description
4324
4325 positional arguments:
Miss Islington (bot)6f6648e2021-08-17 02:40:41 -07004326 spam spam help
4327 badger badger help (default: wooden)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004328
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004329 options:
Miss Islington (bot)6f6648e2021-08-17 02:40:41 -07004330 -h, --help show this help message and exit
4331 --foo FOO foo help - oh and by the way, None
4332 --bar bar help (default: False)
4333 --taz, --no-taz Whether to taz it (default: True)
4334 --quux QUUX Set the quux (default: 42)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004335
4336 title:
4337 description
4338
Miss Islington (bot)6f6648e2021-08-17 02:40:41 -07004339 --baz BAZ baz help (default: 42)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004340 '''
4341 version = ''
4342
Steven Bethard50fe5932010-05-24 03:47:38 +00004343class TestHelpVersionAction(HelpTestCase):
4344 """Test the default help for the version action"""
4345
4346 parser_signature = Sig(prog='PROG', description='description')
4347 argument_signatures = [Sig('-V', '--version', action='version', version='3.6')]
4348 argument_group_signatures = []
4349 usage = '''\
4350 usage: PROG [-h] [-V]
4351 '''
4352 help = usage + '''\
4353
4354 description
4355
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004356 options:
Steven Bethard50fe5932010-05-24 03:47:38 +00004357 -h, --help show this help message and exit
4358 -V, --version show program's version number and exit
4359 '''
4360 version = ''
4361
Berker Peksagecb75e22015-04-10 16:11:12 +03004362
4363class TestHelpVersionActionSuppress(HelpTestCase):
4364 """Test that the --version argument can be suppressed in help messages"""
4365
4366 parser_signature = Sig(prog='PROG')
4367 argument_signatures = [
4368 Sig('-v', '--version', action='version', version='1.0',
4369 help=argparse.SUPPRESS),
4370 Sig('--foo', help='foo help'),
4371 Sig('spam', help='spam help'),
4372 ]
4373 argument_group_signatures = []
4374 usage = '''\
4375 usage: PROG [-h] [--foo FOO] spam
4376 '''
4377 help = usage + '''\
4378
4379 positional arguments:
4380 spam spam help
4381
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004382 options:
Berker Peksagecb75e22015-04-10 16:11:12 +03004383 -h, --help show this help message and exit
4384 --foo FOO foo help
4385 '''
4386
4387
Steven Bethard8a6a1982011-03-27 13:53:53 +02004388class TestHelpSubparsersOrdering(HelpTestCase):
4389 """Test ordering of subcommands in help matches the code"""
4390 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004391 description='display some subcommands')
4392 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004393
4394 subparsers_signatures = [Sig(name=name)
4395 for name in ('a', 'b', 'c', 'd', 'e')]
4396
4397 usage = '''\
4398 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4399 '''
4400
4401 help = usage + '''\
4402
4403 display some subcommands
4404
4405 positional arguments:
4406 {a,b,c,d,e}
4407
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004408 options:
Steven Bethard8a6a1982011-03-27 13:53:53 +02004409 -h, --help show this help message and exit
4410 -v, --version show program's version number and exit
4411 '''
4412
4413 version = '''\
4414 0.1
4415 '''
4416
4417class TestHelpSubparsersWithHelpOrdering(HelpTestCase):
4418 """Test ordering of subcommands in help matches the code"""
4419 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004420 description='display some subcommands')
4421 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004422
4423 subcommand_data = (('a', 'a subcommand help'),
4424 ('b', 'b subcommand help'),
4425 ('c', 'c subcommand help'),
4426 ('d', 'd subcommand help'),
4427 ('e', 'e subcommand help'),
4428 )
4429
4430 subparsers_signatures = [Sig(name=name, help=help)
4431 for name, help in subcommand_data]
4432
4433 usage = '''\
4434 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4435 '''
4436
4437 help = usage + '''\
4438
4439 display some subcommands
4440
4441 positional arguments:
4442 {a,b,c,d,e}
4443 a a subcommand help
4444 b b subcommand help
4445 c c subcommand help
4446 d d subcommand help
4447 e e subcommand help
4448
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004449 options:
Steven Bethard8a6a1982011-03-27 13:53:53 +02004450 -h, --help show this help message and exit
4451 -v, --version show program's version number and exit
4452 '''
4453
4454 version = '''\
4455 0.1
4456 '''
4457
4458
Steven Bethard0331e902011-03-26 14:48:04 +01004459
4460class TestHelpMetavarTypeFormatter(HelpTestCase):
Steven Bethard0331e902011-03-26 14:48:04 +01004461
4462 def custom_type(string):
4463 return string
4464
4465 parser_signature = Sig(prog='PROG', description='description',
4466 formatter_class=argparse.MetavarTypeHelpFormatter)
4467 argument_signatures = [Sig('a', type=int),
4468 Sig('-b', type=custom_type),
4469 Sig('-c', type=float, metavar='SOME FLOAT')]
4470 argument_group_signatures = []
4471 usage = '''\
4472 usage: PROG [-h] [-b custom_type] [-c SOME FLOAT] int
4473 '''
4474 help = usage + '''\
4475
4476 description
4477
4478 positional arguments:
4479 int
4480
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004481 options:
Steven Bethard0331e902011-03-26 14:48:04 +01004482 -h, --help show this help message and exit
4483 -b custom_type
4484 -c SOME FLOAT
4485 '''
4486 version = ''
4487
4488
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004489# =====================================
4490# Optional/Positional constructor tests
4491# =====================================
4492
4493class TestInvalidArgumentConstructors(TestCase):
4494 """Test a bunch of invalid Argument constructors"""
4495
4496 def assertTypeError(self, *args, **kwargs):
4497 parser = argparse.ArgumentParser()
4498 self.assertRaises(TypeError, parser.add_argument,
4499 *args, **kwargs)
4500
4501 def assertValueError(self, *args, **kwargs):
4502 parser = argparse.ArgumentParser()
4503 self.assertRaises(ValueError, parser.add_argument,
4504 *args, **kwargs)
4505
4506 def test_invalid_keyword_arguments(self):
4507 self.assertTypeError('-x', bar=None)
4508 self.assertTypeError('-y', callback='foo')
4509 self.assertTypeError('-y', callback_args=())
4510 self.assertTypeError('-y', callback_kwargs={})
4511
4512 def test_missing_destination(self):
4513 self.assertTypeError()
4514 for action in ['append', 'store']:
4515 self.assertTypeError(action=action)
4516
4517 def test_invalid_option_strings(self):
4518 self.assertValueError('--')
4519 self.assertValueError('---')
4520
4521 def test_invalid_type(self):
4522 self.assertValueError('--foo', type='int')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004523 self.assertValueError('--foo', type=(int, float))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004524
4525 def test_invalid_action(self):
4526 self.assertValueError('-x', action='foo')
4527 self.assertValueError('foo', action='baz')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004528 self.assertValueError('--foo', action=('store', 'append'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004529 parser = argparse.ArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004530 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004531 parser.add_argument("--foo", action="store-true")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004532 self.assertIn('unknown action', str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004533
4534 def test_multiple_dest(self):
4535 parser = argparse.ArgumentParser()
4536 parser.add_argument(dest='foo')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004537 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004538 parser.add_argument('bar', dest='baz')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004539 self.assertIn('dest supplied twice for positional argument',
4540 str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004541
4542 def test_no_argument_actions(self):
4543 for action in ['store_const', 'store_true', 'store_false',
4544 'append_const', 'count']:
4545 for attrs in [dict(type=int), dict(nargs='+'),
4546 dict(choices='ab')]:
4547 self.assertTypeError('-x', action=action, **attrs)
4548
4549 def test_no_argument_no_const_actions(self):
4550 # options with zero arguments
4551 for action in ['store_true', 'store_false', 'count']:
4552
4553 # const is always disallowed
4554 self.assertTypeError('-x', const='foo', action=action)
4555
4556 # nargs is always disallowed
4557 self.assertTypeError('-x', nargs='*', action=action)
4558
4559 def test_more_than_one_argument_actions(self):
4560 for action in ['store', 'append']:
4561
4562 # nargs=0 is disallowed
4563 self.assertValueError('-x', nargs=0, action=action)
4564 self.assertValueError('spam', nargs=0, action=action)
4565
4566 # const is disallowed with non-optional arguments
4567 for nargs in [1, '*', '+']:
4568 self.assertValueError('-x', const='foo',
4569 nargs=nargs, action=action)
4570 self.assertValueError('spam', const='foo',
4571 nargs=nargs, action=action)
4572
4573 def test_required_const_actions(self):
4574 for action in ['store_const', 'append_const']:
4575
4576 # nargs is always disallowed
4577 self.assertTypeError('-x', nargs='+', action=action)
4578
4579 def test_parsers_action_missing_params(self):
4580 self.assertTypeError('command', action='parsers')
4581 self.assertTypeError('command', action='parsers', prog='PROG')
4582 self.assertTypeError('command', action='parsers',
4583 parser_class=argparse.ArgumentParser)
4584
4585 def test_required_positional(self):
4586 self.assertTypeError('foo', required=True)
4587
4588 def test_user_defined_action(self):
4589
4590 class Success(Exception):
4591 pass
4592
4593 class Action(object):
4594
4595 def __init__(self,
4596 option_strings,
4597 dest,
4598 const,
4599 default,
4600 required=False):
4601 if dest == 'spam':
4602 if const is Success:
4603 if default is Success:
4604 raise Success()
4605
4606 def __call__(self, *args, **kwargs):
4607 pass
4608
4609 parser = argparse.ArgumentParser()
4610 self.assertRaises(Success, parser.add_argument, '--spam',
4611 action=Action, default=Success, const=Success)
4612 self.assertRaises(Success, parser.add_argument, 'spam',
4613 action=Action, default=Success, const=Success)
4614
4615# ================================
4616# Actions returned by add_argument
4617# ================================
4618
4619class TestActionsReturned(TestCase):
4620
4621 def test_dest(self):
4622 parser = argparse.ArgumentParser()
4623 action = parser.add_argument('--foo')
4624 self.assertEqual(action.dest, 'foo')
4625 action = parser.add_argument('-b', '--bar')
4626 self.assertEqual(action.dest, 'bar')
4627 action = parser.add_argument('-x', '-y')
4628 self.assertEqual(action.dest, 'x')
4629
4630 def test_misc(self):
4631 parser = argparse.ArgumentParser()
4632 action = parser.add_argument('--foo', nargs='?', const=42,
4633 default=84, type=int, choices=[1, 2],
4634 help='FOO', metavar='BAR', dest='baz')
4635 self.assertEqual(action.nargs, '?')
4636 self.assertEqual(action.const, 42)
4637 self.assertEqual(action.default, 84)
4638 self.assertEqual(action.type, int)
4639 self.assertEqual(action.choices, [1, 2])
4640 self.assertEqual(action.help, 'FOO')
4641 self.assertEqual(action.metavar, 'BAR')
4642 self.assertEqual(action.dest, 'baz')
4643
4644
4645# ================================
4646# Argument conflict handling tests
4647# ================================
4648
4649class TestConflictHandling(TestCase):
4650
4651 def test_bad_type(self):
4652 self.assertRaises(ValueError, argparse.ArgumentParser,
4653 conflict_handler='foo')
4654
4655 def test_conflict_error(self):
4656 parser = argparse.ArgumentParser()
4657 parser.add_argument('-x')
4658 self.assertRaises(argparse.ArgumentError,
4659 parser.add_argument, '-x')
4660 parser.add_argument('--spam')
4661 self.assertRaises(argparse.ArgumentError,
4662 parser.add_argument, '--spam')
4663
4664 def test_resolve_error(self):
4665 get_parser = argparse.ArgumentParser
4666 parser = get_parser(prog='PROG', conflict_handler='resolve')
4667
4668 parser.add_argument('-x', help='OLD X')
4669 parser.add_argument('-x', help='NEW X')
4670 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4671 usage: PROG [-h] [-x X]
4672
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004673 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004674 -h, --help show this help message and exit
4675 -x X NEW X
4676 '''))
4677
4678 parser.add_argument('--spam', metavar='OLD_SPAM')
4679 parser.add_argument('--spam', metavar='NEW_SPAM')
4680 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4681 usage: PROG [-h] [-x X] [--spam NEW_SPAM]
4682
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004683 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004684 -h, --help show this help message and exit
4685 -x X NEW X
4686 --spam NEW_SPAM
4687 '''))
4688
4689
4690# =============================
4691# Help and Version option tests
4692# =============================
4693
4694class TestOptionalsHelpVersionActions(TestCase):
4695 """Test the help and version actions"""
4696
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004697 def assertPrintHelpExit(self, parser, args_str):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004698 with self.assertRaises(ArgumentParserError) as cm:
4699 parser.parse_args(args_str.split())
4700 self.assertEqual(parser.format_help(), cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004701
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004702 def assertArgumentParserError(self, parser, *args):
4703 self.assertRaises(ArgumentParserError, parser.parse_args, args)
4704
4705 def test_version(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004706 parser = ErrorRaisingArgumentParser()
4707 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004708 self.assertPrintHelpExit(parser, '-h')
4709 self.assertPrintHelpExit(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004710 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004711
4712 def test_version_format(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004713 parser = ErrorRaisingArgumentParser(prog='PPP')
4714 parser.add_argument('-v', '--version', action='version', version='%(prog)s 3.5')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004715 with self.assertRaises(ArgumentParserError) as cm:
4716 parser.parse_args(['-v'])
4717 self.assertEqual('PPP 3.5\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004718
4719 def test_version_no_help(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004720 parser = ErrorRaisingArgumentParser(add_help=False)
4721 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004722 self.assertArgumentParserError(parser, '-h')
4723 self.assertArgumentParserError(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004724 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004725
4726 def test_version_action(self):
4727 parser = ErrorRaisingArgumentParser(prog='XXX')
4728 parser.add_argument('-V', action='version', version='%(prog)s 3.7')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004729 with self.assertRaises(ArgumentParserError) as cm:
4730 parser.parse_args(['-V'])
4731 self.assertEqual('XXX 3.7\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004732
4733 def test_no_help(self):
4734 parser = ErrorRaisingArgumentParser(add_help=False)
4735 self.assertArgumentParserError(parser, '-h')
4736 self.assertArgumentParserError(parser, '--help')
4737 self.assertArgumentParserError(parser, '-v')
4738 self.assertArgumentParserError(parser, '--version')
4739
4740 def test_alternate_help_version(self):
4741 parser = ErrorRaisingArgumentParser()
4742 parser.add_argument('-x', action='help')
4743 parser.add_argument('-y', action='version')
4744 self.assertPrintHelpExit(parser, '-x')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004745 self.assertArgumentParserError(parser, '-v')
4746 self.assertArgumentParserError(parser, '--version')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004747 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004748
4749 def test_help_version_extra_arguments(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004750 parser = ErrorRaisingArgumentParser()
4751 parser.add_argument('--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004752 parser.add_argument('-x', action='store_true')
4753 parser.add_argument('y')
4754
4755 # try all combinations of valid prefixes and suffixes
4756 valid_prefixes = ['', '-x', 'foo', '-x bar', 'baz -x']
4757 valid_suffixes = valid_prefixes + ['--bad-option', 'foo bar baz']
4758 for prefix in valid_prefixes:
4759 for suffix in valid_suffixes:
4760 format = '%s %%s %s' % (prefix, suffix)
4761 self.assertPrintHelpExit(parser, format % '-h')
4762 self.assertPrintHelpExit(parser, format % '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004763 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004764
4765
4766# ======================
4767# str() and repr() tests
4768# ======================
4769
4770class TestStrings(TestCase):
4771 """Test str() and repr() on Optionals and Positionals"""
4772
4773 def assertStringEqual(self, obj, result_string):
4774 for func in [str, repr]:
4775 self.assertEqual(func(obj), result_string)
4776
4777 def test_optional(self):
4778 option = argparse.Action(
4779 option_strings=['--foo', '-a', '-b'],
4780 dest='b',
4781 type='int',
4782 nargs='+',
4783 default=42,
4784 choices=[1, 2, 3],
4785 help='HELP',
4786 metavar='METAVAR')
4787 string = (
4788 "Action(option_strings=['--foo', '-a', '-b'], dest='b', "
4789 "nargs='+', const=None, default=42, type='int', "
4790 "choices=[1, 2, 3], help='HELP', metavar='METAVAR')")
4791 self.assertStringEqual(option, string)
4792
4793 def test_argument(self):
4794 argument = argparse.Action(
4795 option_strings=[],
4796 dest='x',
4797 type=float,
4798 nargs='?',
4799 default=2.5,
4800 choices=[0.5, 1.5, 2.5],
4801 help='H HH H',
4802 metavar='MV MV MV')
4803 string = (
4804 "Action(option_strings=[], dest='x', nargs='?', "
4805 "const=None, default=2.5, type=%r, choices=[0.5, 1.5, 2.5], "
4806 "help='H HH H', metavar='MV MV MV')" % float)
4807 self.assertStringEqual(argument, string)
4808
4809 def test_namespace(self):
4810 ns = argparse.Namespace(foo=42, bar='spam')
Raymond Hettinger96819532020-05-17 18:53:01 -07004811 string = "Namespace(foo=42, bar='spam')"
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004812 self.assertStringEqual(ns, string)
4813
Berker Peksag76b17142015-07-29 23:51:47 +03004814 def test_namespace_starkwargs_notidentifier(self):
4815 ns = argparse.Namespace(**{'"': 'quote'})
4816 string = """Namespace(**{'"': 'quote'})"""
4817 self.assertStringEqual(ns, string)
4818
4819 def test_namespace_kwargs_and_starkwargs_notidentifier(self):
4820 ns = argparse.Namespace(a=1, **{'"': 'quote'})
4821 string = """Namespace(a=1, **{'"': 'quote'})"""
4822 self.assertStringEqual(ns, string)
4823
4824 def test_namespace_starkwargs_identifier(self):
4825 ns = argparse.Namespace(**{'valid': True})
4826 string = "Namespace(valid=True)"
4827 self.assertStringEqual(ns, string)
4828
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004829 def test_parser(self):
4830 parser = argparse.ArgumentParser(prog='PROG')
4831 string = (
4832 "ArgumentParser(prog='PROG', usage=None, description=None, "
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004833 "formatter_class=%r, conflict_handler='error', "
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004834 "add_help=True)" % argparse.HelpFormatter)
4835 self.assertStringEqual(parser, string)
4836
4837# ===============
4838# Namespace tests
4839# ===============
4840
4841class TestNamespace(TestCase):
4842
4843 def test_constructor(self):
4844 ns = argparse.Namespace()
4845 self.assertRaises(AttributeError, getattr, ns, 'x')
4846
4847 ns = argparse.Namespace(a=42, b='spam')
4848 self.assertEqual(ns.a, 42)
4849 self.assertEqual(ns.b, 'spam')
4850
4851 def test_equality(self):
4852 ns1 = argparse.Namespace(a=1, b=2)
4853 ns2 = argparse.Namespace(b=2, a=1)
4854 ns3 = argparse.Namespace(a=1)
4855 ns4 = argparse.Namespace(b=2)
4856
4857 self.assertEqual(ns1, ns2)
4858 self.assertNotEqual(ns1, ns3)
4859 self.assertNotEqual(ns1, ns4)
4860 self.assertNotEqual(ns2, ns3)
4861 self.assertNotEqual(ns2, ns4)
4862 self.assertTrue(ns1 != ns3)
4863 self.assertTrue(ns1 != ns4)
4864 self.assertTrue(ns2 != ns3)
4865 self.assertTrue(ns2 != ns4)
4866
Berker Peksagc16387b2016-09-28 17:21:52 +03004867 def test_equality_returns_notimplemented(self):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07004868 # See issue 21481
4869 ns = argparse.Namespace(a=1, b=2)
4870 self.assertIs(ns.__eq__(None), NotImplemented)
4871 self.assertIs(ns.__ne__(None), NotImplemented)
4872
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004873
4874# ===================
4875# File encoding tests
4876# ===================
4877
4878class TestEncoding(TestCase):
4879
4880 def _test_module_encoding(self, path):
4881 path, _ = os.path.splitext(path)
4882 path += ".py"
Victor Stinner272d8882017-06-16 08:59:01 +02004883 with open(path, 'r', encoding='utf-8') as f:
Antoine Pitroub86680e2010-10-14 21:15:17 +00004884 f.read()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004885
4886 def test_argparse_module_encoding(self):
4887 self._test_module_encoding(argparse.__file__)
4888
4889 def test_test_argparse_module_encoding(self):
4890 self._test_module_encoding(__file__)
4891
4892# ===================
4893# ArgumentError tests
4894# ===================
4895
4896class TestArgumentError(TestCase):
4897
4898 def test_argument_error(self):
4899 msg = "my error here"
4900 error = argparse.ArgumentError(None, msg)
4901 self.assertEqual(str(error), msg)
4902
4903# =======================
4904# ArgumentTypeError tests
4905# =======================
4906
R. David Murray722b5fd2010-11-20 03:48:58 +00004907class TestArgumentTypeError(TestCase):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004908
4909 def test_argument_type_error(self):
4910
4911 def spam(string):
4912 raise argparse.ArgumentTypeError('spam!')
4913
4914 parser = ErrorRaisingArgumentParser(prog='PROG', add_help=False)
4915 parser.add_argument('x', type=spam)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004916 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004917 parser.parse_args(['XXX'])
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004918 self.assertEqual('usage: PROG x\nPROG: error: argument x: spam!\n',
4919 cm.exception.stderr)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004920
R David Murrayf97c59a2011-06-09 12:34:07 -04004921# =========================
4922# MessageContentError tests
4923# =========================
4924
4925class TestMessageContentError(TestCase):
4926
4927 def test_missing_argument_name_in_message(self):
4928 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4929 parser.add_argument('req_pos', type=str)
4930 parser.add_argument('-req_opt', type=int, required=True)
4931 parser.add_argument('need_one', type=str, nargs='+')
4932
4933 with self.assertRaises(ArgumentParserError) as cm:
4934 parser.parse_args([])
4935 msg = str(cm.exception)
4936 self.assertRegex(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'])
4941 msg = str(cm.exception)
4942 self.assertNotIn(msg, 'req_pos')
4943 self.assertRegex(msg, 'req_opt')
4944 self.assertRegex(msg, 'need_one')
4945 with self.assertRaises(ArgumentParserError) as cm:
4946 parser.parse_args(['myXargument', '-req_opt=1'])
4947 msg = str(cm.exception)
4948 self.assertNotIn(msg, 'req_pos')
4949 self.assertNotIn(msg, 'req_opt')
4950 self.assertRegex(msg, 'need_one')
4951
4952 def test_optional_optional_not_in_message(self):
4953 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4954 parser.add_argument('req_pos', type=str)
4955 parser.add_argument('--req_opt', type=int, required=True)
4956 parser.add_argument('--opt_opt', type=bool, nargs='?',
4957 default=True)
4958 with self.assertRaises(ArgumentParserError) as cm:
4959 parser.parse_args([])
4960 msg = str(cm.exception)
4961 self.assertRegex(msg, 'req_pos')
4962 self.assertRegex(msg, 'req_opt')
4963 self.assertNotIn(msg, 'opt_opt')
4964 with self.assertRaises(ArgumentParserError) as cm:
4965 parser.parse_args(['--req_opt=1'])
4966 msg = str(cm.exception)
4967 self.assertRegex(msg, 'req_pos')
4968 self.assertNotIn(msg, 'req_opt')
4969 self.assertNotIn(msg, 'opt_opt')
4970
4971 def test_optional_positional_not_in_message(self):
4972 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4973 parser.add_argument('req_pos')
4974 parser.add_argument('optional_positional', nargs='?', default='eggs')
4975 with self.assertRaises(ArgumentParserError) as cm:
4976 parser.parse_args([])
4977 msg = str(cm.exception)
4978 self.assertRegex(msg, 'req_pos')
4979 self.assertNotIn(msg, 'optional_positional')
4980
4981
R David Murray6fb8fb12012-08-31 22:45:20 -04004982# ================================================
4983# Check that the type function is called only once
4984# ================================================
4985
4986class TestTypeFunctionCallOnlyOnce(TestCase):
4987
4988 def test_type_function_call_only_once(self):
4989 def spam(string_to_convert):
4990 self.assertEqual(string_to_convert, 'spam!')
4991 return 'foo_converted'
4992
4993 parser = argparse.ArgumentParser()
4994 parser.add_argument('--foo', type=spam, default='bar')
4995 args = parser.parse_args('--foo spam!'.split())
4996 self.assertEqual(NS(foo='foo_converted'), args)
4997
Barry Warsaweaae1b72012-09-12 14:34:50 -04004998# ==================================================================
4999# Check semantics regarding the default argument and type conversion
5000# ==================================================================
R David Murray6fb8fb12012-08-31 22:45:20 -04005001
Barry Warsaweaae1b72012-09-12 14:34:50 -04005002class TestTypeFunctionCalledOnDefault(TestCase):
R David Murray6fb8fb12012-08-31 22:45:20 -04005003
5004 def test_type_function_call_with_non_string_default(self):
5005 def spam(int_to_convert):
5006 self.assertEqual(int_to_convert, 0)
5007 return 'foo_converted'
5008
5009 parser = argparse.ArgumentParser()
5010 parser.add_argument('--foo', type=spam, default=0)
5011 args = parser.parse_args([])
Barry Warsaweaae1b72012-09-12 14:34:50 -04005012 # foo should *not* be converted because its default is not a string.
5013 self.assertEqual(NS(foo=0), args)
5014
5015 def test_type_function_call_with_string_default(self):
5016 def spam(int_to_convert):
5017 return 'foo_converted'
5018
5019 parser = argparse.ArgumentParser()
5020 parser.add_argument('--foo', type=spam, default='0')
5021 args = parser.parse_args([])
5022 # foo is converted because its default is a string.
R David Murray6fb8fb12012-08-31 22:45:20 -04005023 self.assertEqual(NS(foo='foo_converted'), args)
5024
Barry Warsaweaae1b72012-09-12 14:34:50 -04005025 def test_no_double_type_conversion_of_default(self):
5026 def extend(str_to_convert):
5027 return str_to_convert + '*'
5028
5029 parser = argparse.ArgumentParser()
5030 parser.add_argument('--test', type=extend, default='*')
5031 args = parser.parse_args([])
5032 # The test argument will be two stars, one coming from the default
5033 # value and one coming from the type conversion being called exactly
5034 # once.
5035 self.assertEqual(NS(test='**'), args)
5036
Barry Warsaw4b2f9e92012-09-11 22:38:47 -04005037 def test_issue_15906(self):
5038 # Issue #15906: When action='append', type=str, default=[] are
5039 # providing, the dest value was the string representation "[]" when it
5040 # should have been an empty list.
5041 parser = argparse.ArgumentParser()
5042 parser.add_argument('--test', dest='test', type=str,
5043 default=[], action='append')
5044 args = parser.parse_args([])
5045 self.assertEqual(args.test, [])
5046
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005047# ======================
5048# parse_known_args tests
5049# ======================
5050
5051class TestParseKnownArgs(TestCase):
5052
R David Murrayb5228282012-09-08 12:08:01 -04005053 def test_arguments_tuple(self):
5054 parser = argparse.ArgumentParser()
5055 parser.parse_args(())
5056
5057 def test_arguments_list(self):
5058 parser = argparse.ArgumentParser()
5059 parser.parse_args([])
5060
5061 def test_arguments_tuple_positional(self):
5062 parser = argparse.ArgumentParser()
5063 parser.add_argument('x')
5064 parser.parse_args(('x',))
5065
5066 def test_arguments_list_positional(self):
5067 parser = argparse.ArgumentParser()
5068 parser.add_argument('x')
5069 parser.parse_args(['x'])
5070
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005071 def test_optionals(self):
5072 parser = argparse.ArgumentParser()
5073 parser.add_argument('--foo')
5074 args, extras = parser.parse_known_args('--foo F --bar --baz'.split())
5075 self.assertEqual(NS(foo='F'), args)
5076 self.assertEqual(['--bar', '--baz'], extras)
5077
5078 def test_mixed(self):
5079 parser = argparse.ArgumentParser()
5080 parser.add_argument('-v', nargs='?', const=1, type=int)
5081 parser.add_argument('--spam', action='store_false')
5082 parser.add_argument('badger')
5083
5084 argv = ["B", "C", "--foo", "-v", "3", "4"]
5085 args, extras = parser.parse_known_args(argv)
5086 self.assertEqual(NS(v=3, spam=True, badger="B"), args)
5087 self.assertEqual(["C", "--foo", "4"], extras)
5088
R. David Murray0f6b9d22017-09-06 20:25:40 -04005089# ===========================
5090# parse_intermixed_args tests
5091# ===========================
5092
5093class TestIntermixedArgs(TestCase):
5094 def test_basic(self):
5095 # test parsing intermixed optionals and positionals
5096 parser = argparse.ArgumentParser(prog='PROG')
5097 parser.add_argument('--foo', dest='foo')
5098 bar = parser.add_argument('--bar', dest='bar', required=True)
5099 parser.add_argument('cmd')
5100 parser.add_argument('rest', nargs='*', type=int)
5101 argv = 'cmd --foo x 1 --bar y 2 3'.split()
5102 args = parser.parse_intermixed_args(argv)
5103 # rest gets [1,2,3] despite the foo and bar strings
5104 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args)
5105
5106 args, extras = parser.parse_known_args(argv)
5107 # cannot parse the '1,2,3'
5108 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[]), args)
5109 self.assertEqual(["1", "2", "3"], extras)
5110
5111 argv = 'cmd --foo x 1 --error 2 --bar y 3'.split()
5112 args, extras = parser.parse_known_intermixed_args(argv)
5113 # unknown optionals go into extras
5114 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1]), args)
5115 self.assertEqual(['--error', '2', '3'], extras)
5116
5117 # restores attributes that were temporarily changed
5118 self.assertIsNone(parser.usage)
5119 self.assertEqual(bar.required, True)
5120
5121 def test_remainder(self):
5122 # Intermixed and remainder are incompatible
5123 parser = ErrorRaisingArgumentParser(prog='PROG')
5124 parser.add_argument('-z')
5125 parser.add_argument('x')
5126 parser.add_argument('y', nargs='...')
5127 argv = 'X A B -z Z'.split()
5128 # intermixed fails with '...' (also 'A...')
5129 # self.assertRaises(TypeError, parser.parse_intermixed_args, argv)
5130 with self.assertRaises(TypeError) as cm:
5131 parser.parse_intermixed_args(argv)
5132 self.assertRegex(str(cm.exception), r'\.\.\.')
5133
5134 def test_exclusive(self):
5135 # mutually exclusive group; intermixed works fine
5136 parser = ErrorRaisingArgumentParser(prog='PROG')
5137 group = parser.add_mutually_exclusive_group(required=True)
5138 group.add_argument('--foo', action='store_true', help='FOO')
5139 group.add_argument('--spam', help='SPAM')
5140 parser.add_argument('badger', nargs='*', default='X', help='BADGER')
5141 args = parser.parse_intermixed_args('1 --foo 2'.split())
5142 self.assertEqual(NS(badger=['1', '2'], foo=True, spam=None), args)
5143 self.assertRaises(ArgumentParserError, parser.parse_intermixed_args, '1 2'.split())
5144 self.assertEqual(group.required, True)
5145
5146 def test_exclusive_incompatible(self):
5147 # mutually exclusive group including positional - fail
5148 parser = ErrorRaisingArgumentParser(prog='PROG')
5149 group = parser.add_mutually_exclusive_group(required=True)
5150 group.add_argument('--foo', action='store_true', help='FOO')
5151 group.add_argument('--spam', help='SPAM')
5152 group.add_argument('badger', nargs='*', default='X', help='BADGER')
5153 self.assertRaises(TypeError, parser.parse_intermixed_args, [])
5154 self.assertEqual(group.required, True)
5155
5156class TestIntermixedMessageContentError(TestCase):
5157 # case where Intermixed gives different error message
5158 # error is raised by 1st parsing step
5159 def test_missing_argument_name_in_message(self):
5160 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
5161 parser.add_argument('req_pos', type=str)
5162 parser.add_argument('-req_opt', type=int, required=True)
5163
5164 with self.assertRaises(ArgumentParserError) as cm:
5165 parser.parse_args([])
5166 msg = str(cm.exception)
5167 self.assertRegex(msg, 'req_pos')
5168 self.assertRegex(msg, 'req_opt')
5169
5170 with self.assertRaises(ArgumentParserError) as cm:
5171 parser.parse_intermixed_args([])
5172 msg = str(cm.exception)
5173 self.assertNotRegex(msg, 'req_pos')
5174 self.assertRegex(msg, 'req_opt')
5175
Steven Bethard8d9a4622011-03-26 17:33:56 +01005176# ==========================
5177# add_argument metavar tests
5178# ==========================
5179
5180class TestAddArgumentMetavar(TestCase):
5181
5182 EXPECTED_MESSAGE = "length of metavar tuple does not match nargs"
5183
5184 def do_test_no_exception(self, nargs, metavar):
5185 parser = argparse.ArgumentParser()
5186 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
5187
5188 def do_test_exception(self, nargs, metavar):
5189 parser = argparse.ArgumentParser()
5190 with self.assertRaises(ValueError) as cm:
5191 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
5192 self.assertEqual(cm.exception.args[0], self.EXPECTED_MESSAGE)
5193
5194 # Unit tests for different values of metavar when nargs=None
5195
5196 def test_nargs_None_metavar_string(self):
5197 self.do_test_no_exception(nargs=None, metavar="1")
5198
5199 def test_nargs_None_metavar_length0(self):
5200 self.do_test_exception(nargs=None, metavar=tuple())
5201
5202 def test_nargs_None_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005203 self.do_test_no_exception(nargs=None, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005204
5205 def test_nargs_None_metavar_length2(self):
5206 self.do_test_exception(nargs=None, metavar=("1", "2"))
5207
5208 def test_nargs_None_metavar_length3(self):
5209 self.do_test_exception(nargs=None, metavar=("1", "2", "3"))
5210
5211 # Unit tests for different values of metavar when nargs=?
5212
5213 def test_nargs_optional_metavar_string(self):
5214 self.do_test_no_exception(nargs="?", metavar="1")
5215
5216 def test_nargs_optional_metavar_length0(self):
5217 self.do_test_exception(nargs="?", metavar=tuple())
5218
5219 def test_nargs_optional_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005220 self.do_test_no_exception(nargs="?", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005221
5222 def test_nargs_optional_metavar_length2(self):
5223 self.do_test_exception(nargs="?", metavar=("1", "2"))
5224
5225 def test_nargs_optional_metavar_length3(self):
5226 self.do_test_exception(nargs="?", metavar=("1", "2", "3"))
5227
5228 # Unit tests for different values of metavar when nargs=*
5229
5230 def test_nargs_zeroormore_metavar_string(self):
5231 self.do_test_no_exception(nargs="*", metavar="1")
5232
5233 def test_nargs_zeroormore_metavar_length0(self):
5234 self.do_test_exception(nargs="*", metavar=tuple())
5235
5236 def test_nargs_zeroormore_metavar_length1(self):
Brandt Buchera0ed99b2019-11-11 12:47:48 -08005237 self.do_test_no_exception(nargs="*", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005238
5239 def test_nargs_zeroormore_metavar_length2(self):
5240 self.do_test_no_exception(nargs="*", metavar=("1", "2"))
5241
5242 def test_nargs_zeroormore_metavar_length3(self):
5243 self.do_test_exception(nargs="*", metavar=("1", "2", "3"))
5244
5245 # Unit tests for different values of metavar when nargs=+
5246
5247 def test_nargs_oneormore_metavar_string(self):
5248 self.do_test_no_exception(nargs="+", metavar="1")
5249
5250 def test_nargs_oneormore_metavar_length0(self):
5251 self.do_test_exception(nargs="+", metavar=tuple())
5252
5253 def test_nargs_oneormore_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005254 self.do_test_exception(nargs="+", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005255
5256 def test_nargs_oneormore_metavar_length2(self):
5257 self.do_test_no_exception(nargs="+", metavar=("1", "2"))
5258
5259 def test_nargs_oneormore_metavar_length3(self):
5260 self.do_test_exception(nargs="+", metavar=("1", "2", "3"))
5261
5262 # Unit tests for different values of metavar when nargs=...
5263
5264 def test_nargs_remainder_metavar_string(self):
5265 self.do_test_no_exception(nargs="...", metavar="1")
5266
5267 def test_nargs_remainder_metavar_length0(self):
5268 self.do_test_no_exception(nargs="...", metavar=tuple())
5269
5270 def test_nargs_remainder_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005271 self.do_test_no_exception(nargs="...", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005272
5273 def test_nargs_remainder_metavar_length2(self):
5274 self.do_test_no_exception(nargs="...", metavar=("1", "2"))
5275
5276 def test_nargs_remainder_metavar_length3(self):
5277 self.do_test_no_exception(nargs="...", metavar=("1", "2", "3"))
5278
5279 # Unit tests for different values of metavar when nargs=A...
5280
5281 def test_nargs_parser_metavar_string(self):
5282 self.do_test_no_exception(nargs="A...", metavar="1")
5283
5284 def test_nargs_parser_metavar_length0(self):
5285 self.do_test_exception(nargs="A...", metavar=tuple())
5286
5287 def test_nargs_parser_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005288 self.do_test_no_exception(nargs="A...", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005289
5290 def test_nargs_parser_metavar_length2(self):
5291 self.do_test_exception(nargs="A...", metavar=("1", "2"))
5292
5293 def test_nargs_parser_metavar_length3(self):
5294 self.do_test_exception(nargs="A...", metavar=("1", "2", "3"))
5295
5296 # Unit tests for different values of metavar when nargs=1
5297
5298 def test_nargs_1_metavar_string(self):
5299 self.do_test_no_exception(nargs=1, metavar="1")
5300
5301 def test_nargs_1_metavar_length0(self):
5302 self.do_test_exception(nargs=1, metavar=tuple())
5303
5304 def test_nargs_1_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005305 self.do_test_no_exception(nargs=1, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005306
5307 def test_nargs_1_metavar_length2(self):
5308 self.do_test_exception(nargs=1, metavar=("1", "2"))
5309
5310 def test_nargs_1_metavar_length3(self):
5311 self.do_test_exception(nargs=1, metavar=("1", "2", "3"))
5312
5313 # Unit tests for different values of metavar when nargs=2
5314
5315 def test_nargs_2_metavar_string(self):
5316 self.do_test_no_exception(nargs=2, metavar="1")
5317
5318 def test_nargs_2_metavar_length0(self):
5319 self.do_test_exception(nargs=2, metavar=tuple())
5320
5321 def test_nargs_2_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005322 self.do_test_exception(nargs=2, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005323
5324 def test_nargs_2_metavar_length2(self):
5325 self.do_test_no_exception(nargs=2, metavar=("1", "2"))
5326
5327 def test_nargs_2_metavar_length3(self):
5328 self.do_test_exception(nargs=2, metavar=("1", "2", "3"))
5329
5330 # Unit tests for different values of metavar when nargs=3
5331
5332 def test_nargs_3_metavar_string(self):
5333 self.do_test_no_exception(nargs=3, metavar="1")
5334
5335 def test_nargs_3_metavar_length0(self):
5336 self.do_test_exception(nargs=3, metavar=tuple())
5337
5338 def test_nargs_3_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005339 self.do_test_exception(nargs=3, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005340
5341 def test_nargs_3_metavar_length2(self):
5342 self.do_test_exception(nargs=3, metavar=("1", "2"))
5343
5344 def test_nargs_3_metavar_length3(self):
5345 self.do_test_no_exception(nargs=3, metavar=("1", "2", "3"))
5346
tmblweed4b3e9752019-08-01 21:57:13 -07005347
5348class TestInvalidNargs(TestCase):
5349
5350 EXPECTED_INVALID_MESSAGE = "invalid nargs value"
5351 EXPECTED_RANGE_MESSAGE = ("nargs for store actions must be != 0; if you "
5352 "have nothing to store, actions such as store "
5353 "true or store const may be more appropriate")
5354
5355 def do_test_range_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_RANGE_MESSAGE)
5360
5361 def do_test_invalid_exception(self, nargs):
5362 parser = argparse.ArgumentParser()
5363 with self.assertRaises(ValueError) as cm:
5364 parser.add_argument("--foo", nargs=nargs)
5365 self.assertEqual(cm.exception.args[0], self.EXPECTED_INVALID_MESSAGE)
5366
5367 # Unit tests for different values of nargs
5368
5369 def test_nargs_alphabetic(self):
5370 self.do_test_invalid_exception(nargs='a')
5371 self.do_test_invalid_exception(nargs="abcd")
5372
5373 def test_nargs_zero(self):
5374 self.do_test_range_exception(nargs=0)
5375
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005376# ============================
5377# from argparse import * tests
5378# ============================
5379
5380class TestImportStar(TestCase):
5381
5382 def test(self):
5383 for name in argparse.__all__:
5384 self.assertTrue(hasattr(argparse, name))
5385
Steven Bethard72c55382010-11-01 15:23:12 +00005386 def test_all_exports_everything_but_modules(self):
5387 items = [
5388 name
5389 for name, value in vars(argparse).items()
Éric Araujo12159152010-12-04 17:31:49 +00005390 if not (name.startswith("_") or name == 'ngettext')
Steven Bethard72c55382010-11-01 15:23:12 +00005391 if not inspect.ismodule(value)
5392 ]
5393 self.assertEqual(sorted(items), sorted(argparse.__all__))
5394
wim glenn66f02aa2018-06-08 05:12:49 -05005395
5396class TestWrappingMetavar(TestCase):
5397
5398 def setUp(self):
Berker Peksag74102c92018-07-25 18:23:44 +03005399 super().setUp()
wim glenn66f02aa2018-06-08 05:12:49 -05005400 self.parser = ErrorRaisingArgumentParser(
5401 'this_is_spammy_prog_with_a_long_name_sorry_about_the_name'
5402 )
5403 # this metavar was triggering library assertion errors due to usage
5404 # message formatting incorrectly splitting on the ] chars within
5405 metavar = '<http[s]://example:1234>'
5406 self.parser.add_argument('--proxy', metavar=metavar)
5407
5408 def test_help_with_metavar(self):
5409 help_text = self.parser.format_help()
5410 self.assertEqual(help_text, textwrap.dedent('''\
5411 usage: this_is_spammy_prog_with_a_long_name_sorry_about_the_name
5412 [-h] [--proxy <http[s]://example:1234>]
5413
Raymond Hettinger41b223d2020-12-23 09:40:56 -08005414 options:
wim glenn66f02aa2018-06-08 05:12:49 -05005415 -h, --help show this help message and exit
5416 --proxy <http[s]://example:1234>
5417 '''))
5418
5419
Hai Shif5456382019-09-12 05:56:05 -05005420class TestExitOnError(TestCase):
5421
5422 def setUp(self):
5423 self.parser = argparse.ArgumentParser(exit_on_error=False)
5424 self.parser.add_argument('--integers', metavar='N', type=int)
5425
5426 def test_exit_on_error_with_good_args(self):
5427 ns = self.parser.parse_args('--integers 4'.split())
5428 self.assertEqual(ns, argparse.Namespace(integers=4))
5429
5430 def test_exit_on_error_with_bad_args(self):
5431 with self.assertRaises(argparse.ArgumentError):
5432 self.parser.parse_args('--integers a'.split())
5433
5434
Serhiy Storchakabedce352021-09-19 22:36:03 +03005435def tearDownModule():
Benjamin Peterson4fd181c2010-03-02 23:46:42 +00005436 # Remove global references to avoid looking like we have refleaks.
5437 RFile.seen = {}
5438 WFile.seen = set()
5439
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005440
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005441if __name__ == '__main__':
Serhiy Storchakabedce352021-09-19 22:36:03 +03005442 unittest.main()