blob: 0994e70e65e1c490d95b741e6273804b4f4d57aa [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
Benjamin Peterson698a18a2010-03-02 22:34:37 +000015from test import support
Hai Shi46605972020-08-04 00:49:18 +080016from test.support import os_helper
Petri Lehtinen74d6c252012-12-15 22:39:32 +020017from unittest import mock
Benjamin Petersonb48af542010-04-11 20:43:16 +000018class StdIOBuffer(StringIO):
19 pass
Benjamin Peterson698a18a2010-03-02 22:34:37 +000020
Benjamin Peterson698a18a2010-03-02 22:34:37 +000021class TestCase(unittest.TestCase):
22
Steven Bethard1f1c2472010-11-01 13:56:09 +000023 def setUp(self):
24 # The tests assume that line wrapping occurs at 80 columns, but this
25 # behaviour can be overridden by setting the COLUMNS environment
Berker Peksag74102c92018-07-25 18:23:44 +030026 # variable. To ensure that this width is used, set COLUMNS to 80.
Hai Shi46605972020-08-04 00:49:18 +080027 env = os_helper.EnvironmentVarGuard()
Berker Peksag74102c92018-07-25 18:23:44 +030028 env['COLUMNS'] = '80'
Steven Bethard1f1c2472010-11-01 13:56:09 +000029 self.addCleanup(env.__exit__)
Benjamin Peterson698a18a2010-03-02 22:34:37 +000030
Benjamin Petersonb48af542010-04-11 20:43:16 +000031
Benjamin Peterson698a18a2010-03-02 22:34:37 +000032class TempDirMixin(object):
33
34 def setUp(self):
35 self.temp_dir = tempfile.mkdtemp()
36 self.old_dir = os.getcwd()
37 os.chdir(self.temp_dir)
38
39 def tearDown(self):
40 os.chdir(self.old_dir)
Benjamin Peterson511e2222014-04-04 13:55:56 -040041 for root, dirs, files in os.walk(self.temp_dir, topdown=False):
42 for name in files:
43 os.chmod(os.path.join(self.temp_dir, name), stat.S_IWRITE)
Steven Bethardb0270112011-01-24 21:02:50 +000044 shutil.rmtree(self.temp_dir, True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +000045
Steven Bethardb0270112011-01-24 21:02:50 +000046 def create_readonly_file(self, filename):
47 file_path = os.path.join(self.temp_dir, filename)
Inada Naoki8bbfeb32021-04-02 12:53:46 +090048 with open(file_path, 'w', encoding="utf-8") as file:
Steven Bethardb0270112011-01-24 21:02:50 +000049 file.write(filename)
50 os.chmod(file_path, stat.S_IREAD)
Benjamin Peterson698a18a2010-03-02 22:34:37 +000051
52class Sig(object):
53
54 def __init__(self, *args, **kwargs):
55 self.args = args
56 self.kwargs = kwargs
57
58
59class NS(object):
60
61 def __init__(self, **kwargs):
62 self.__dict__.update(kwargs)
63
64 def __repr__(self):
65 sorted_items = sorted(self.__dict__.items())
66 kwarg_str = ', '.join(['%s=%r' % tup for tup in sorted_items])
67 return '%s(%s)' % (type(self).__name__, kwarg_str)
68
69 def __eq__(self, other):
70 return vars(self) == vars(other)
71
Benjamin Peterson698a18a2010-03-02 22:34:37 +000072
73class ArgumentParserError(Exception):
74
75 def __init__(self, message, stdout=None, stderr=None, error_code=None):
76 Exception.__init__(self, message, stdout, stderr)
77 self.message = message
78 self.stdout = stdout
79 self.stderr = stderr
80 self.error_code = error_code
81
82
83def stderr_to_parser_error(parse_args, *args, **kwargs):
84 # if this is being called recursively and stderr or stdout is already being
85 # redirected, simply call the function and let the enclosing function
86 # catch the exception
Benjamin Petersonb48af542010-04-11 20:43:16 +000087 if isinstance(sys.stderr, StdIOBuffer) or isinstance(sys.stdout, StdIOBuffer):
Benjamin Peterson698a18a2010-03-02 22:34:37 +000088 return parse_args(*args, **kwargs)
89
90 # if this is not being called recursively, redirect stderr and
91 # use it as the ArgumentParserError message
92 old_stdout = sys.stdout
93 old_stderr = sys.stderr
Benjamin Petersonb48af542010-04-11 20:43:16 +000094 sys.stdout = StdIOBuffer()
95 sys.stderr = StdIOBuffer()
Benjamin Peterson698a18a2010-03-02 22:34:37 +000096 try:
97 try:
98 result = parse_args(*args, **kwargs)
99 for key in list(vars(result)):
100 if getattr(result, key) is sys.stdout:
101 setattr(result, key, old_stdout)
102 if getattr(result, key) is sys.stderr:
103 setattr(result, key, old_stderr)
104 return result
105 except SystemExit:
106 code = sys.exc_info()[1].code
107 stdout = sys.stdout.getvalue()
108 stderr = sys.stderr.getvalue()
alclarksd4331c52020-02-21 08:48:36 +0000109 raise ArgumentParserError(
110 "SystemExit", stdout, stderr, code) from None
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000111 finally:
112 sys.stdout = old_stdout
113 sys.stderr = old_stderr
114
115
116class ErrorRaisingArgumentParser(argparse.ArgumentParser):
117
118 def parse_args(self, *args, **kwargs):
119 parse_args = super(ErrorRaisingArgumentParser, self).parse_args
120 return stderr_to_parser_error(parse_args, *args, **kwargs)
121
122 def exit(self, *args, **kwargs):
123 exit = super(ErrorRaisingArgumentParser, self).exit
124 return stderr_to_parser_error(exit, *args, **kwargs)
125
126 def error(self, *args, **kwargs):
127 error = super(ErrorRaisingArgumentParser, self).error
128 return stderr_to_parser_error(error, *args, **kwargs)
129
130
131class ParserTesterMetaclass(type):
132 """Adds parser tests using the class attributes.
133
134 Classes of this type should specify the following attributes:
135
136 argument_signatures -- a list of Sig objects which specify
137 the signatures of Argument objects to be created
138 failures -- a list of args lists that should cause the parser
139 to fail
140 successes -- a list of (initial_args, options, remaining_args) tuples
141 where initial_args specifies the string args to be parsed,
142 options is a dict that should match the vars() of the options
143 parsed out of initial_args, and remaining_args should be any
144 remaining unparsed arguments
145 """
146
147 def __init__(cls, name, bases, bodydict):
148 if name == 'ParserTestCase':
149 return
150
151 # default parser signature is empty
152 if not hasattr(cls, 'parser_signature'):
153 cls.parser_signature = Sig()
154 if not hasattr(cls, 'parser_class'):
155 cls.parser_class = ErrorRaisingArgumentParser
156
157 # ---------------------------------------
158 # functions for adding optional arguments
159 # ---------------------------------------
160 def no_groups(parser, argument_signatures):
161 """Add all arguments directly to the parser"""
162 for sig in argument_signatures:
163 parser.add_argument(*sig.args, **sig.kwargs)
164
165 def one_group(parser, argument_signatures):
166 """Add all arguments under a single group in the parser"""
167 group = parser.add_argument_group('foo')
168 for sig in argument_signatures:
169 group.add_argument(*sig.args, **sig.kwargs)
170
171 def many_groups(parser, argument_signatures):
172 """Add each argument in its own group to the parser"""
173 for i, sig in enumerate(argument_signatures):
174 group = parser.add_argument_group('foo:%i' % i)
175 group.add_argument(*sig.args, **sig.kwargs)
176
177 # --------------------------
178 # functions for parsing args
179 # --------------------------
180 def listargs(parser, args):
181 """Parse the args by passing in a list"""
182 return parser.parse_args(args)
183
184 def sysargs(parser, args):
185 """Parse the args by defaulting to sys.argv"""
186 old_sys_argv = sys.argv
187 sys.argv = [old_sys_argv[0]] + args
188 try:
189 return parser.parse_args()
190 finally:
191 sys.argv = old_sys_argv
192
193 # class that holds the combination of one optional argument
194 # addition method and one arg parsing method
195 class AddTests(object):
196
197 def __init__(self, tester_cls, add_arguments, parse_args):
198 self._add_arguments = add_arguments
199 self._parse_args = parse_args
200
201 add_arguments_name = self._add_arguments.__name__
202 parse_args_name = self._parse_args.__name__
203 for test_func in [self.test_failures, self.test_successes]:
204 func_name = test_func.__name__
205 names = func_name, add_arguments_name, parse_args_name
206 test_name = '_'.join(names)
207
208 def wrapper(self, test_func=test_func):
209 test_func(self)
210 try:
211 wrapper.__name__ = test_name
212 except TypeError:
213 pass
214 setattr(tester_cls, test_name, wrapper)
215
216 def _get_parser(self, tester):
217 args = tester.parser_signature.args
218 kwargs = tester.parser_signature.kwargs
219 parser = tester.parser_class(*args, **kwargs)
220 self._add_arguments(parser, tester.argument_signatures)
221 return parser
222
223 def test_failures(self, tester):
224 parser = self._get_parser(tester)
225 for args_str in tester.failures:
226 args = args_str.split()
Ezio Melotti12b7f482014-08-05 02:24:03 +0300227 with tester.assertRaises(ArgumentParserError, msg=args):
228 parser.parse_args(args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000229
230 def test_successes(self, tester):
231 parser = self._get_parser(tester)
232 for args, expected_ns in tester.successes:
233 if isinstance(args, str):
234 args = args.split()
235 result_ns = self._parse_args(parser, args)
236 tester.assertEqual(expected_ns, result_ns)
237
238 # add tests for each combination of an optionals adding method
239 # and an arg parsing method
240 for add_arguments in [no_groups, one_group, many_groups]:
241 for parse_args in [listargs, sysargs]:
242 AddTests(cls, add_arguments, parse_args)
243
244bases = TestCase,
245ParserTestCase = ParserTesterMetaclass('ParserTestCase', bases, {})
246
247# ===============
248# Optionals tests
249# ===============
250
251class TestOptionalsSingleDash(ParserTestCase):
252 """Test an Optional with a single-dash option string"""
253
254 argument_signatures = [Sig('-x')]
255 failures = ['-x', 'a', '--foo', '-x --foo', '-x -y']
256 successes = [
257 ('', NS(x=None)),
258 ('-x a', NS(x='a')),
259 ('-xa', NS(x='a')),
260 ('-x -1', NS(x='-1')),
261 ('-x-1', NS(x='-1')),
262 ]
263
264
265class TestOptionalsSingleDashCombined(ParserTestCase):
266 """Test an Optional with a single-dash option string"""
267
268 argument_signatures = [
269 Sig('-x', action='store_true'),
270 Sig('-yyy', action='store_const', const=42),
271 Sig('-z'),
272 ]
273 failures = ['a', '--foo', '-xa', '-x --foo', '-x -z', '-z -x',
274 '-yx', '-yz a', '-yyyx', '-yyyza', '-xyza']
275 successes = [
276 ('', NS(x=False, yyy=None, z=None)),
277 ('-x', NS(x=True, yyy=None, z=None)),
278 ('-za', NS(x=False, yyy=None, z='a')),
279 ('-z a', NS(x=False, yyy=None, z='a')),
280 ('-xza', NS(x=True, yyy=None, z='a')),
281 ('-xz a', NS(x=True, yyy=None, z='a')),
282 ('-x -za', NS(x=True, yyy=None, z='a')),
283 ('-x -z a', NS(x=True, yyy=None, z='a')),
284 ('-y', NS(x=False, yyy=42, z=None)),
285 ('-yyy', NS(x=False, yyy=42, z=None)),
286 ('-x -yyy -za', NS(x=True, yyy=42, z='a')),
287 ('-x -yyy -z a', NS(x=True, yyy=42, z='a')),
288 ]
289
290
291class TestOptionalsSingleDashLong(ParserTestCase):
292 """Test an Optional with a multi-character single-dash option string"""
293
294 argument_signatures = [Sig('-foo')]
295 failures = ['-foo', 'a', '--foo', '-foo --foo', '-foo -y', '-fooa']
296 successes = [
297 ('', NS(foo=None)),
298 ('-foo a', NS(foo='a')),
299 ('-foo -1', NS(foo='-1')),
300 ('-fo a', NS(foo='a')),
301 ('-f a', NS(foo='a')),
302 ]
303
304
305class TestOptionalsSingleDashSubsetAmbiguous(ParserTestCase):
306 """Test Optionals where option strings are subsets of each other"""
307
308 argument_signatures = [Sig('-f'), Sig('-foobar'), Sig('-foorab')]
309 failures = ['-f', '-foo', '-fo', '-foo b', '-foob', '-fooba', '-foora']
310 successes = [
311 ('', NS(f=None, foobar=None, foorab=None)),
312 ('-f a', NS(f='a', foobar=None, foorab=None)),
313 ('-fa', NS(f='a', foobar=None, foorab=None)),
314 ('-foa', NS(f='oa', foobar=None, foorab=None)),
315 ('-fooa', NS(f='ooa', foobar=None, foorab=None)),
316 ('-foobar a', NS(f=None, foobar='a', foorab=None)),
317 ('-foorab a', NS(f=None, foobar=None, foorab='a')),
318 ]
319
320
321class TestOptionalsSingleDashAmbiguous(ParserTestCase):
322 """Test Optionals that partially match but are not subsets"""
323
324 argument_signatures = [Sig('-foobar'), Sig('-foorab')]
325 failures = ['-f', '-f a', '-fa', '-foa', '-foo', '-fo', '-foo b']
326 successes = [
327 ('', NS(foobar=None, foorab=None)),
328 ('-foob a', NS(foobar='a', foorab=None)),
329 ('-foor a', NS(foobar=None, foorab='a')),
330 ('-fooba a', NS(foobar='a', foorab=None)),
331 ('-foora a', NS(foobar=None, foorab='a')),
332 ('-foobar a', NS(foobar='a', foorab=None)),
333 ('-foorab a', NS(foobar=None, foorab='a')),
334 ]
335
336
337class TestOptionalsNumeric(ParserTestCase):
338 """Test an Optional with a short opt string"""
339
340 argument_signatures = [Sig('-1', dest='one')]
341 failures = ['-1', 'a', '-1 --foo', '-1 -y', '-1 -1', '-1 -2']
342 successes = [
343 ('', NS(one=None)),
344 ('-1 a', NS(one='a')),
345 ('-1a', NS(one='a')),
346 ('-1-2', NS(one='-2')),
347 ]
348
349
350class TestOptionalsDoubleDash(ParserTestCase):
351 """Test an Optional with a double-dash option string"""
352
353 argument_signatures = [Sig('--foo')]
354 failures = ['--foo', '-f', '-f a', 'a', '--foo -x', '--foo --bar']
355 successes = [
356 ('', NS(foo=None)),
357 ('--foo a', NS(foo='a')),
358 ('--foo=a', NS(foo='a')),
359 ('--foo -2.5', NS(foo='-2.5')),
360 ('--foo=-2.5', NS(foo='-2.5')),
361 ]
362
363
364class TestOptionalsDoubleDashPartialMatch(ParserTestCase):
365 """Tests partial matching with a double-dash option string"""
366
367 argument_signatures = [
368 Sig('--badger', action='store_true'),
369 Sig('--bat'),
370 ]
371 failures = ['--bar', '--b', '--ba', '--b=2', '--ba=4', '--badge 5']
372 successes = [
373 ('', NS(badger=False, bat=None)),
374 ('--bat X', NS(badger=False, bat='X')),
375 ('--bad', NS(badger=True, bat=None)),
376 ('--badg', NS(badger=True, bat=None)),
377 ('--badge', NS(badger=True, bat=None)),
378 ('--badger', NS(badger=True, bat=None)),
379 ]
380
381
382class TestOptionalsDoubleDashPrefixMatch(ParserTestCase):
383 """Tests when one double-dash option string is a prefix of another"""
384
385 argument_signatures = [
386 Sig('--badger', action='store_true'),
387 Sig('--ba'),
388 ]
389 failures = ['--bar', '--b', '--ba', '--b=2', '--badge 5']
390 successes = [
391 ('', NS(badger=False, ba=None)),
392 ('--ba X', NS(badger=False, ba='X')),
393 ('--ba=X', NS(badger=False, ba='X')),
394 ('--bad', NS(badger=True, ba=None)),
395 ('--badg', NS(badger=True, ba=None)),
396 ('--badge', NS(badger=True, ba=None)),
397 ('--badger', NS(badger=True, ba=None)),
398 ]
399
400
401class TestOptionalsSingleDoubleDash(ParserTestCase):
402 """Test an Optional with single- and double-dash option strings"""
403
404 argument_signatures = [
405 Sig('-f', action='store_true'),
406 Sig('--bar'),
407 Sig('-baz', action='store_const', const=42),
408 ]
409 failures = ['--bar', '-fbar', '-fbaz', '-bazf', '-b B', 'B']
410 successes = [
411 ('', NS(f=False, bar=None, baz=None)),
412 ('-f', NS(f=True, bar=None, baz=None)),
413 ('--ba B', NS(f=False, bar='B', baz=None)),
414 ('-f --bar B', NS(f=True, bar='B', baz=None)),
415 ('-f -b', NS(f=True, bar=None, baz=42)),
416 ('-ba -f', NS(f=True, bar=None, baz=42)),
417 ]
418
419
420class TestOptionalsAlternatePrefixChars(ParserTestCase):
R. David Murray88c49fe2010-08-03 17:56:09 +0000421 """Test an Optional with option strings with custom prefixes"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000422
423 parser_signature = Sig(prefix_chars='+:/', add_help=False)
424 argument_signatures = [
425 Sig('+f', action='store_true'),
426 Sig('::bar'),
427 Sig('/baz', action='store_const', const=42),
428 ]
R. David Murray88c49fe2010-08-03 17:56:09 +0000429 failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz', '-h', '--help', '+h', '::help', '/help']
430 successes = [
431 ('', NS(f=False, bar=None, baz=None)),
432 ('+f', NS(f=True, bar=None, baz=None)),
433 ('::ba B', NS(f=False, bar='B', baz=None)),
434 ('+f ::bar B', NS(f=True, bar='B', baz=None)),
435 ('+f /b', NS(f=True, bar=None, baz=42)),
436 ('/ba +f', NS(f=True, bar=None, baz=42)),
437 ]
438
439
440class TestOptionalsAlternatePrefixCharsAddedHelp(ParserTestCase):
441 """When ``-`` not in prefix_chars, default operators created for help
442 should use the prefix_chars in use rather than - or --
443 http://bugs.python.org/issue9444"""
444
445 parser_signature = Sig(prefix_chars='+:/', add_help=True)
446 argument_signatures = [
447 Sig('+f', action='store_true'),
448 Sig('::bar'),
449 Sig('/baz', action='store_const', const=42),
450 ]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000451 failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz']
452 successes = [
453 ('', NS(f=False, bar=None, baz=None)),
454 ('+f', NS(f=True, bar=None, baz=None)),
455 ('::ba B', NS(f=False, bar='B', baz=None)),
456 ('+f ::bar B', NS(f=True, bar='B', baz=None)),
457 ('+f /b', NS(f=True, bar=None, baz=42)),
R. David Murray88c49fe2010-08-03 17:56:09 +0000458 ('/ba +f', NS(f=True, bar=None, baz=42))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000459 ]
460
Steven Bethard1ca45a52010-11-01 15:57:36 +0000461
462class TestOptionalsAlternatePrefixCharsMultipleShortArgs(ParserTestCase):
463 """Verify that Optionals must be called with their defined prefixes"""
464
465 parser_signature = Sig(prefix_chars='+-', add_help=False)
466 argument_signatures = [
467 Sig('-x', action='store_true'),
468 Sig('+y', action='store_true'),
469 Sig('+z', action='store_true'),
470 ]
471 failures = ['-w',
472 '-xyz',
473 '+x',
474 '-y',
475 '+xyz',
476 ]
477 successes = [
478 ('', NS(x=False, y=False, z=False)),
479 ('-x', NS(x=True, y=False, z=False)),
480 ('+y -x', NS(x=True, y=True, z=False)),
481 ('+yz -x', NS(x=True, y=True, z=True)),
482 ]
483
484
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000485class TestOptionalsShortLong(ParserTestCase):
486 """Test a combination of single- and double-dash option strings"""
487
488 argument_signatures = [
489 Sig('-v', '--verbose', '-n', '--noisy', action='store_true'),
490 ]
491 failures = ['--x --verbose', '-N', 'a', '-v x']
492 successes = [
493 ('', NS(verbose=False)),
494 ('-v', NS(verbose=True)),
495 ('--verbose', NS(verbose=True)),
496 ('-n', NS(verbose=True)),
497 ('--noisy', NS(verbose=True)),
498 ]
499
500
501class TestOptionalsDest(ParserTestCase):
502 """Tests various means of setting destination"""
503
504 argument_signatures = [Sig('--foo-bar'), Sig('--baz', dest='zabbaz')]
505 failures = ['a']
506 successes = [
507 ('--foo-bar f', NS(foo_bar='f', zabbaz=None)),
508 ('--baz g', NS(foo_bar=None, zabbaz='g')),
509 ('--foo-bar h --baz i', NS(foo_bar='h', zabbaz='i')),
510 ('--baz j --foo-bar k', NS(foo_bar='k', zabbaz='j')),
511 ]
512
513
514class TestOptionalsDefault(ParserTestCase):
515 """Tests specifying a default for an Optional"""
516
517 argument_signatures = [Sig('-x'), Sig('-y', default=42)]
518 failures = ['a']
519 successes = [
520 ('', NS(x=None, y=42)),
521 ('-xx', NS(x='x', y=42)),
522 ('-yy', NS(x=None, y='y')),
523 ]
524
525
526class TestOptionalsNargsDefault(ParserTestCase):
527 """Tests not specifying the number of args for an Optional"""
528
529 argument_signatures = [Sig('-x')]
530 failures = ['a', '-x']
531 successes = [
532 ('', NS(x=None)),
533 ('-x a', NS(x='a')),
534 ]
535
536
537class TestOptionalsNargs1(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +0000538 """Tests specifying 1 arg for an Optional"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000539
540 argument_signatures = [Sig('-x', nargs=1)]
541 failures = ['a', '-x']
542 successes = [
543 ('', NS(x=None)),
544 ('-x a', NS(x=['a'])),
545 ]
546
547
548class TestOptionalsNargs3(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +0000549 """Tests specifying 3 args for an Optional"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000550
551 argument_signatures = [Sig('-x', nargs=3)]
552 failures = ['a', '-x', '-x a', '-x a b', 'a -x', 'a -x b']
553 successes = [
554 ('', NS(x=None)),
555 ('-x a b c', NS(x=['a', 'b', 'c'])),
556 ]
557
558
559class TestOptionalsNargsOptional(ParserTestCase):
560 """Tests specifying an Optional arg for an Optional"""
561
562 argument_signatures = [
563 Sig('-w', nargs='?'),
564 Sig('-x', nargs='?', const=42),
565 Sig('-y', nargs='?', default='spam'),
566 Sig('-z', nargs='?', type=int, const='42', default='84'),
567 ]
568 failures = ['2']
569 successes = [
570 ('', NS(w=None, x=None, y='spam', z=84)),
571 ('-w', NS(w=None, x=None, y='spam', z=84)),
572 ('-w 2', NS(w='2', x=None, y='spam', z=84)),
573 ('-x', NS(w=None, x=42, y='spam', z=84)),
574 ('-x 2', NS(w=None, x='2', y='spam', z=84)),
575 ('-y', NS(w=None, x=None, y=None, z=84)),
576 ('-y 2', NS(w=None, x=None, y='2', z=84)),
577 ('-z', NS(w=None, x=None, y='spam', z=42)),
578 ('-z 2', NS(w=None, x=None, y='spam', z=2)),
579 ]
580
581
582class TestOptionalsNargsZeroOrMore(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +0000583 """Tests specifying args for an Optional that accepts zero or more"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000584
585 argument_signatures = [
586 Sig('-x', nargs='*'),
587 Sig('-y', nargs='*', default='spam'),
588 ]
589 failures = ['a']
590 successes = [
591 ('', NS(x=None, y='spam')),
592 ('-x', NS(x=[], y='spam')),
593 ('-x a', NS(x=['a'], y='spam')),
594 ('-x a b', NS(x=['a', 'b'], y='spam')),
595 ('-y', NS(x=None, y=[])),
596 ('-y a', NS(x=None, y=['a'])),
597 ('-y a b', NS(x=None, y=['a', 'b'])),
598 ]
599
600
601class TestOptionalsNargsOneOrMore(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +0000602 """Tests specifying args for an Optional that accepts one or more"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000603
604 argument_signatures = [
605 Sig('-x', nargs='+'),
606 Sig('-y', nargs='+', default='spam'),
607 ]
608 failures = ['a', '-x', '-y', 'a -x', 'a -y b']
609 successes = [
610 ('', NS(x=None, y='spam')),
611 ('-x a', NS(x=['a'], y='spam')),
612 ('-x a b', NS(x=['a', 'b'], y='spam')),
613 ('-y a', NS(x=None, y=['a'])),
614 ('-y a b', NS(x=None, y=['a', 'b'])),
615 ]
616
617
618class TestOptionalsChoices(ParserTestCase):
619 """Tests specifying the choices for an Optional"""
620
621 argument_signatures = [
622 Sig('-f', choices='abc'),
623 Sig('-g', type=int, choices=range(5))]
624 failures = ['a', '-f d', '-fad', '-ga', '-g 6']
625 successes = [
626 ('', NS(f=None, g=None)),
627 ('-f a', NS(f='a', g=None)),
628 ('-f c', NS(f='c', g=None)),
629 ('-g 0', NS(f=None, g=0)),
630 ('-g 03', NS(f=None, g=3)),
631 ('-fb -g4', NS(f='b', g=4)),
632 ]
633
634
635class TestOptionalsRequired(ParserTestCase):
Benjamin Peterson82f34ad2015-01-13 09:17:24 -0500636 """Tests an optional action that is required"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000637
638 argument_signatures = [
639 Sig('-x', type=int, required=True),
640 ]
641 failures = ['a', '']
642 successes = [
643 ('-x 1', NS(x=1)),
644 ('-x42', NS(x=42)),
645 ]
646
647
648class TestOptionalsActionStore(ParserTestCase):
649 """Tests the store action for an Optional"""
650
651 argument_signatures = [Sig('-x', action='store')]
652 failures = ['a', 'a -x']
653 successes = [
654 ('', NS(x=None)),
655 ('-xfoo', NS(x='foo')),
656 ]
657
658
659class TestOptionalsActionStoreConst(ParserTestCase):
660 """Tests the store_const action for an Optional"""
661
662 argument_signatures = [Sig('-y', action='store_const', const=object)]
663 failures = ['a']
664 successes = [
665 ('', NS(y=None)),
666 ('-y', NS(y=object)),
667 ]
668
669
670class TestOptionalsActionStoreFalse(ParserTestCase):
671 """Tests the store_false action for an Optional"""
672
673 argument_signatures = [Sig('-z', action='store_false')]
674 failures = ['a', '-za', '-z a']
675 successes = [
676 ('', NS(z=True)),
677 ('-z', NS(z=False)),
678 ]
679
680
681class TestOptionalsActionStoreTrue(ParserTestCase):
682 """Tests the store_true action for an Optional"""
683
684 argument_signatures = [Sig('--apple', action='store_true')]
685 failures = ['a', '--apple=b', '--apple b']
686 successes = [
687 ('', NS(apple=False)),
688 ('--apple', NS(apple=True)),
689 ]
690
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200691class TestBooleanOptionalAction(ParserTestCase):
692 """Tests BooleanOptionalAction"""
693
694 argument_signatures = [Sig('--foo', action=argparse.BooleanOptionalAction)]
695 failures = ['--foo bar', '--foo=bar']
696 successes = [
697 ('', NS(foo=None)),
698 ('--foo', NS(foo=True)),
699 ('--no-foo', NS(foo=False)),
700 ('--foo --no-foo', NS(foo=False)), # useful for aliases
701 ('--no-foo --foo', NS(foo=True)),
702 ]
703
Rémi Lapeyreb084d1b2020-06-06 00:00:42 +0200704 def test_const(self):
705 # See bpo-40862
706 parser = argparse.ArgumentParser()
707 with self.assertRaises(TypeError) as cm:
708 parser.add_argument('--foo', const=True, action=argparse.BooleanOptionalAction)
709
710 self.assertIn("got an unexpected keyword argument 'const'", str(cm.exception))
711
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200712class TestBooleanOptionalActionRequired(ParserTestCase):
713 """Tests BooleanOptionalAction required"""
714
715 argument_signatures = [
716 Sig('--foo', required=True, action=argparse.BooleanOptionalAction)
717 ]
718 failures = ['']
719 successes = [
720 ('--foo', NS(foo=True)),
721 ('--no-foo', NS(foo=False)),
722 ]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000723
724class TestOptionalsActionAppend(ParserTestCase):
725 """Tests the append action for an Optional"""
726
727 argument_signatures = [Sig('--baz', action='append')]
728 failures = ['a', '--baz', 'a --baz', '--baz a b']
729 successes = [
730 ('', NS(baz=None)),
731 ('--baz a', NS(baz=['a'])),
732 ('--baz a --baz b', NS(baz=['a', 'b'])),
733 ]
734
735
736class TestOptionalsActionAppendWithDefault(ParserTestCase):
737 """Tests the append action for an Optional"""
738
739 argument_signatures = [Sig('--baz', action='append', default=['X'])]
740 failures = ['a', '--baz', 'a --baz', '--baz a b']
741 successes = [
742 ('', NS(baz=['X'])),
743 ('--baz a', NS(baz=['X', 'a'])),
744 ('--baz a --baz b', NS(baz=['X', 'a', 'b'])),
745 ]
746
747
748class TestOptionalsActionAppendConst(ParserTestCase):
749 """Tests the append_const action for an Optional"""
750
751 argument_signatures = [
752 Sig('-b', action='append_const', const=Exception),
753 Sig('-c', action='append', dest='b'),
754 ]
755 failures = ['a', '-c', 'a -c', '-bx', '-b x']
756 successes = [
757 ('', NS(b=None)),
758 ('-b', NS(b=[Exception])),
759 ('-b -cx -b -cyz', NS(b=[Exception, 'x', Exception, 'yz'])),
760 ]
761
762
763class TestOptionalsActionAppendConstWithDefault(ParserTestCase):
764 """Tests the append_const action for an Optional"""
765
766 argument_signatures = [
767 Sig('-b', action='append_const', const=Exception, default=['X']),
768 Sig('-c', action='append', dest='b'),
769 ]
770 failures = ['a', '-c', 'a -c', '-bx', '-b x']
771 successes = [
772 ('', NS(b=['X'])),
773 ('-b', NS(b=['X', Exception])),
774 ('-b -cx -b -cyz', NS(b=['X', Exception, 'x', Exception, 'yz'])),
775 ]
776
777
778class TestOptionalsActionCount(ParserTestCase):
779 """Tests the count action for an Optional"""
780
781 argument_signatures = [Sig('-x', action='count')]
782 failures = ['a', '-x a', '-x b', '-x a -x b']
783 successes = [
784 ('', NS(x=None)),
785 ('-x', NS(x=1)),
786 ]
787
788
Berker Peksag8089cd62015-02-14 01:39:17 +0200789class TestOptionalsAllowLongAbbreviation(ParserTestCase):
790 """Allow long options to be abbreviated unambiguously"""
791
792 argument_signatures = [
793 Sig('--foo'),
794 Sig('--foobaz'),
795 Sig('--fooble', action='store_true'),
796 ]
797 failures = ['--foob 5', '--foob']
798 successes = [
799 ('', NS(foo=None, foobaz=None, fooble=False)),
800 ('--foo 7', NS(foo='7', foobaz=None, fooble=False)),
801 ('--fooba a', NS(foo=None, foobaz='a', fooble=False)),
802 ('--foobl --foo g', NS(foo='g', foobaz=None, fooble=True)),
803 ]
804
805
806class TestOptionalsDisallowLongAbbreviation(ParserTestCase):
807 """Do not allow abbreviations of long options at all"""
808
809 parser_signature = Sig(allow_abbrev=False)
810 argument_signatures = [
811 Sig('--foo'),
812 Sig('--foodle', action='store_true'),
813 Sig('--foonly'),
814 ]
815 failures = ['-foon 3', '--foon 3', '--food', '--food --foo 2']
816 successes = [
817 ('', NS(foo=None, foodle=False, foonly=None)),
818 ('--foo 3', NS(foo='3', foodle=False, foonly=None)),
819 ('--foonly 7 --foodle --foo 2', NS(foo='2', foodle=True, foonly='7')),
820 ]
821
Zac Hatfield-Doddsdffca9e2019-07-14 00:35:58 -0500822
Kyle Meyer8edfc472020-02-18 04:48:57 -0500823class TestOptionalsDisallowLongAbbreviationPrefixChars(ParserTestCase):
824 """Disallowing abbreviations works with alternative prefix characters"""
825
826 parser_signature = Sig(prefix_chars='+', allow_abbrev=False)
827 argument_signatures = [
828 Sig('++foo'),
829 Sig('++foodle', action='store_true'),
830 Sig('++foonly'),
831 ]
832 failures = ['+foon 3', '++foon 3', '++food', '++food ++foo 2']
833 successes = [
834 ('', NS(foo=None, foodle=False, foonly=None)),
835 ('++foo 3', NS(foo='3', foodle=False, foonly=None)),
836 ('++foonly 7 ++foodle ++foo 2', NS(foo='2', foodle=True, foonly='7')),
837 ]
838
839
Zac Hatfield-Doddsdffca9e2019-07-14 00:35:58 -0500840class TestDisallowLongAbbreviationAllowsShortGrouping(ParserTestCase):
841 """Do not allow abbreviations of long options at all"""
842
843 parser_signature = Sig(allow_abbrev=False)
844 argument_signatures = [
845 Sig('-r'),
846 Sig('-c', action='count'),
847 ]
848 failures = ['-r', '-c -r']
849 successes = [
850 ('', NS(r=None, c=None)),
851 ('-ra', NS(r='a', c=None)),
852 ('-rcc', NS(r='cc', c=None)),
853 ('-cc', NS(r=None, c=2)),
854 ('-cc -ra', NS(r='a', c=2)),
855 ('-ccrcc', NS(r='cc', c=2)),
856 ]
857
Kyle Meyer8edfc472020-02-18 04:48:57 -0500858
859class TestDisallowLongAbbreviationAllowsShortGroupingPrefix(ParserTestCase):
860 """Short option grouping works with custom prefix and allow_abbrev=False"""
861
862 parser_signature = Sig(prefix_chars='+', allow_abbrev=False)
863 argument_signatures = [
864 Sig('+r'),
865 Sig('+c', action='count'),
866 ]
867 failures = ['+r', '+c +r']
868 successes = [
869 ('', NS(r=None, c=None)),
870 ('+ra', NS(r='a', c=None)),
871 ('+rcc', NS(r='cc', c=None)),
872 ('+cc', NS(r=None, c=2)),
873 ('+cc +ra', NS(r='a', c=2)),
874 ('+ccrcc', NS(r='cc', c=2)),
875 ]
876
877
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000878# ================
879# Positional tests
880# ================
881
882class TestPositionalsNargsNone(ParserTestCase):
883 """Test a Positional that doesn't specify nargs"""
884
885 argument_signatures = [Sig('foo')]
886 failures = ['', '-x', 'a b']
887 successes = [
888 ('a', NS(foo='a')),
889 ]
890
891
892class TestPositionalsNargs1(ParserTestCase):
893 """Test a Positional that specifies an nargs of 1"""
894
895 argument_signatures = [Sig('foo', nargs=1)]
896 failures = ['', '-x', 'a b']
897 successes = [
898 ('a', NS(foo=['a'])),
899 ]
900
901
902class TestPositionalsNargs2(ParserTestCase):
903 """Test a Positional that specifies an nargs of 2"""
904
905 argument_signatures = [Sig('foo', nargs=2)]
906 failures = ['', 'a', '-x', 'a b c']
907 successes = [
908 ('a b', NS(foo=['a', 'b'])),
909 ]
910
911
912class TestPositionalsNargsZeroOrMore(ParserTestCase):
913 """Test a Positional that specifies unlimited nargs"""
914
915 argument_signatures = [Sig('foo', nargs='*')]
916 failures = ['-x']
917 successes = [
918 ('', NS(foo=[])),
919 ('a', NS(foo=['a'])),
920 ('a b', NS(foo=['a', 'b'])),
921 ]
922
923
924class TestPositionalsNargsZeroOrMoreDefault(ParserTestCase):
925 """Test a Positional that specifies unlimited nargs and a default"""
926
927 argument_signatures = [Sig('foo', nargs='*', default='bar')]
928 failures = ['-x']
929 successes = [
930 ('', NS(foo='bar')),
931 ('a', NS(foo=['a'])),
932 ('a b', NS(foo=['a', 'b'])),
933 ]
934
935
936class TestPositionalsNargsOneOrMore(ParserTestCase):
937 """Test a Positional that specifies one or more nargs"""
938
939 argument_signatures = [Sig('foo', nargs='+')]
940 failures = ['', '-x']
941 successes = [
942 ('a', NS(foo=['a'])),
943 ('a b', NS(foo=['a', 'b'])),
944 ]
945
946
947class TestPositionalsNargsOptional(ParserTestCase):
948 """Tests an Optional Positional"""
949
950 argument_signatures = [Sig('foo', nargs='?')]
951 failures = ['-x', 'a b']
952 successes = [
953 ('', NS(foo=None)),
954 ('a', NS(foo='a')),
955 ]
956
957
958class TestPositionalsNargsOptionalDefault(ParserTestCase):
959 """Tests an Optional Positional with a default value"""
960
961 argument_signatures = [Sig('foo', nargs='?', default=42)]
962 failures = ['-x', 'a b']
963 successes = [
964 ('', NS(foo=42)),
965 ('a', NS(foo='a')),
966 ]
967
968
969class TestPositionalsNargsOptionalConvertedDefault(ParserTestCase):
970 """Tests an Optional Positional with a default value
971 that needs to be converted to the appropriate type.
972 """
973
974 argument_signatures = [
975 Sig('foo', nargs='?', type=int, default='42'),
976 ]
977 failures = ['-x', 'a b', '1 2']
978 successes = [
979 ('', NS(foo=42)),
980 ('1', NS(foo=1)),
981 ]
982
983
984class TestPositionalsNargsNoneNone(ParserTestCase):
985 """Test two Positionals that don't specify nargs"""
986
987 argument_signatures = [Sig('foo'), Sig('bar')]
988 failures = ['', '-x', 'a', 'a b c']
989 successes = [
990 ('a b', NS(foo='a', bar='b')),
991 ]
992
993
994class TestPositionalsNargsNone1(ParserTestCase):
995 """Test a Positional with no nargs followed by one with 1"""
996
997 argument_signatures = [Sig('foo'), Sig('bar', nargs=1)]
998 failures = ['', '--foo', 'a', 'a b c']
999 successes = [
1000 ('a b', NS(foo='a', bar=['b'])),
1001 ]
1002
1003
1004class TestPositionalsNargs2None(ParserTestCase):
1005 """Test a Positional with 2 nargs followed by one with none"""
1006
1007 argument_signatures = [Sig('foo', nargs=2), Sig('bar')]
1008 failures = ['', '--foo', 'a', 'a b', 'a b c d']
1009 successes = [
1010 ('a b c', NS(foo=['a', 'b'], bar='c')),
1011 ]
1012
1013
1014class TestPositionalsNargsNoneZeroOrMore(ParserTestCase):
1015 """Test a Positional with no nargs followed by one with unlimited"""
1016
1017 argument_signatures = [Sig('foo'), Sig('bar', nargs='*')]
1018 failures = ['', '--foo']
1019 successes = [
1020 ('a', NS(foo='a', bar=[])),
1021 ('a b', NS(foo='a', bar=['b'])),
1022 ('a b c', NS(foo='a', bar=['b', 'c'])),
1023 ]
1024
1025
1026class TestPositionalsNargsNoneOneOrMore(ParserTestCase):
1027 """Test a Positional with no nargs followed by one with one or more"""
1028
1029 argument_signatures = [Sig('foo'), Sig('bar', nargs='+')]
1030 failures = ['', '--foo', 'a']
1031 successes = [
1032 ('a b', NS(foo='a', bar=['b'])),
1033 ('a b c', NS(foo='a', bar=['b', 'c'])),
1034 ]
1035
1036
1037class TestPositionalsNargsNoneOptional(ParserTestCase):
1038 """Test a Positional with no nargs followed by one with an Optional"""
1039
1040 argument_signatures = [Sig('foo'), Sig('bar', nargs='?')]
1041 failures = ['', '--foo', 'a b c']
1042 successes = [
1043 ('a', NS(foo='a', bar=None)),
1044 ('a b', NS(foo='a', bar='b')),
1045 ]
1046
1047
1048class TestPositionalsNargsZeroOrMoreNone(ParserTestCase):
1049 """Test a Positional with unlimited nargs followed by one with none"""
1050
1051 argument_signatures = [Sig('foo', nargs='*'), Sig('bar')]
1052 failures = ['', '--foo']
1053 successes = [
1054 ('a', NS(foo=[], bar='a')),
1055 ('a b', NS(foo=['a'], bar='b')),
1056 ('a b c', NS(foo=['a', 'b'], bar='c')),
1057 ]
1058
1059
1060class TestPositionalsNargsOneOrMoreNone(ParserTestCase):
1061 """Test a Positional with one or more nargs followed by one with none"""
1062
1063 argument_signatures = [Sig('foo', nargs='+'), Sig('bar')]
1064 failures = ['', '--foo', 'a']
1065 successes = [
1066 ('a b', NS(foo=['a'], bar='b')),
1067 ('a b c', NS(foo=['a', 'b'], bar='c')),
1068 ]
1069
1070
1071class TestPositionalsNargsOptionalNone(ParserTestCase):
1072 """Test a Positional with an Optional nargs followed by one with none"""
1073
1074 argument_signatures = [Sig('foo', nargs='?', default=42), Sig('bar')]
1075 failures = ['', '--foo', 'a b c']
1076 successes = [
1077 ('a', NS(foo=42, bar='a')),
1078 ('a b', NS(foo='a', bar='b')),
1079 ]
1080
1081
1082class TestPositionalsNargs2ZeroOrMore(ParserTestCase):
1083 """Test a Positional with 2 nargs followed by one with unlimited"""
1084
1085 argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='*')]
1086 failures = ['', '--foo', 'a']
1087 successes = [
1088 ('a b', NS(foo=['a', 'b'], bar=[])),
1089 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1090 ]
1091
1092
1093class TestPositionalsNargs2OneOrMore(ParserTestCase):
1094 """Test a Positional with 2 nargs followed by one with one or more"""
1095
1096 argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='+')]
1097 failures = ['', '--foo', 'a', 'a b']
1098 successes = [
1099 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1100 ]
1101
1102
1103class TestPositionalsNargs2Optional(ParserTestCase):
1104 """Test a Positional with 2 nargs followed by one optional"""
1105
1106 argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='?')]
1107 failures = ['', '--foo', 'a', 'a b c d']
1108 successes = [
1109 ('a b', NS(foo=['a', 'b'], bar=None)),
1110 ('a b c', NS(foo=['a', 'b'], bar='c')),
1111 ]
1112
1113
1114class TestPositionalsNargsZeroOrMore1(ParserTestCase):
1115 """Test a Positional with unlimited nargs followed by one with 1"""
1116
1117 argument_signatures = [Sig('foo', nargs='*'), Sig('bar', nargs=1)]
1118 failures = ['', '--foo', ]
1119 successes = [
1120 ('a', NS(foo=[], bar=['a'])),
1121 ('a b', NS(foo=['a'], bar=['b'])),
1122 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1123 ]
1124
1125
1126class TestPositionalsNargsOneOrMore1(ParserTestCase):
1127 """Test a Positional with one or more nargs followed by one with 1"""
1128
1129 argument_signatures = [Sig('foo', nargs='+'), Sig('bar', nargs=1)]
1130 failures = ['', '--foo', 'a']
1131 successes = [
1132 ('a b', NS(foo=['a'], bar=['b'])),
1133 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1134 ]
1135
1136
1137class TestPositionalsNargsOptional1(ParserTestCase):
1138 """Test a Positional with an Optional nargs followed by one with 1"""
1139
1140 argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs=1)]
1141 failures = ['', '--foo', 'a b c']
1142 successes = [
1143 ('a', NS(foo=None, bar=['a'])),
1144 ('a b', NS(foo='a', bar=['b'])),
1145 ]
1146
1147
1148class TestPositionalsNargsNoneZeroOrMore1(ParserTestCase):
1149 """Test three Positionals: no nargs, unlimited nargs and 1 nargs"""
1150
1151 argument_signatures = [
1152 Sig('foo'),
1153 Sig('bar', nargs='*'),
1154 Sig('baz', nargs=1),
1155 ]
1156 failures = ['', '--foo', 'a']
1157 successes = [
1158 ('a b', NS(foo='a', bar=[], baz=['b'])),
1159 ('a b c', NS(foo='a', bar=['b'], baz=['c'])),
1160 ]
1161
1162
1163class TestPositionalsNargsNoneOneOrMore1(ParserTestCase):
1164 """Test three Positionals: no nargs, one or more nargs and 1 nargs"""
1165
1166 argument_signatures = [
1167 Sig('foo'),
1168 Sig('bar', nargs='+'),
1169 Sig('baz', nargs=1),
1170 ]
1171 failures = ['', '--foo', 'a', 'b']
1172 successes = [
1173 ('a b c', NS(foo='a', bar=['b'], baz=['c'])),
1174 ('a b c d', NS(foo='a', bar=['b', 'c'], baz=['d'])),
1175 ]
1176
1177
1178class TestPositionalsNargsNoneOptional1(ParserTestCase):
1179 """Test three Positionals: no nargs, optional narg and 1 nargs"""
1180
1181 argument_signatures = [
1182 Sig('foo'),
1183 Sig('bar', nargs='?', default=0.625),
1184 Sig('baz', nargs=1),
1185 ]
1186 failures = ['', '--foo', 'a']
1187 successes = [
1188 ('a b', NS(foo='a', bar=0.625, baz=['b'])),
1189 ('a b c', NS(foo='a', bar='b', baz=['c'])),
1190 ]
1191
1192
1193class TestPositionalsNargsOptionalOptional(ParserTestCase):
1194 """Test two optional nargs"""
1195
1196 argument_signatures = [
1197 Sig('foo', nargs='?'),
1198 Sig('bar', nargs='?', default=42),
1199 ]
1200 failures = ['--foo', 'a b c']
1201 successes = [
1202 ('', NS(foo=None, bar=42)),
1203 ('a', NS(foo='a', bar=42)),
1204 ('a b', NS(foo='a', bar='b')),
1205 ]
1206
1207
1208class TestPositionalsNargsOptionalZeroOrMore(ParserTestCase):
1209 """Test an Optional narg followed by unlimited nargs"""
1210
1211 argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs='*')]
1212 failures = ['--foo']
1213 successes = [
1214 ('', NS(foo=None, bar=[])),
1215 ('a', NS(foo='a', bar=[])),
1216 ('a b', NS(foo='a', bar=['b'])),
1217 ('a b c', NS(foo='a', bar=['b', 'c'])),
1218 ]
1219
1220
1221class TestPositionalsNargsOptionalOneOrMore(ParserTestCase):
1222 """Test an Optional narg followed by one or more nargs"""
1223
1224 argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs='+')]
1225 failures = ['', '--foo']
1226 successes = [
1227 ('a', NS(foo=None, bar=['a'])),
1228 ('a b', NS(foo='a', bar=['b'])),
1229 ('a b c', NS(foo='a', bar=['b', 'c'])),
1230 ]
1231
1232
1233class TestPositionalsChoicesString(ParserTestCase):
1234 """Test a set of single-character choices"""
1235
1236 argument_signatures = [Sig('spam', choices=set('abcdefg'))]
1237 failures = ['', '--foo', 'h', '42', 'ef']
1238 successes = [
1239 ('a', NS(spam='a')),
1240 ('g', NS(spam='g')),
1241 ]
1242
1243
1244class TestPositionalsChoicesInt(ParserTestCase):
1245 """Test a set of integer choices"""
1246
1247 argument_signatures = [Sig('spam', type=int, choices=range(20))]
1248 failures = ['', '--foo', 'h', '42', 'ef']
1249 successes = [
1250 ('4', NS(spam=4)),
1251 ('15', NS(spam=15)),
1252 ]
1253
1254
1255class TestPositionalsActionAppend(ParserTestCase):
1256 """Test the 'append' action"""
1257
1258 argument_signatures = [
1259 Sig('spam', action='append'),
1260 Sig('spam', action='append', nargs=2),
1261 ]
1262 failures = ['', '--foo', 'a', 'a b', 'a b c d']
1263 successes = [
1264 ('a b c', NS(spam=['a', ['b', 'c']])),
1265 ]
1266
1267# ========================================
1268# Combined optionals and positionals tests
1269# ========================================
1270
1271class TestOptionalsNumericAndPositionals(ParserTestCase):
1272 """Tests negative number args when numeric options are present"""
1273
1274 argument_signatures = [
1275 Sig('x', nargs='?'),
1276 Sig('-4', dest='y', action='store_true'),
1277 ]
1278 failures = ['-2', '-315']
1279 successes = [
1280 ('', NS(x=None, y=False)),
1281 ('a', NS(x='a', y=False)),
1282 ('-4', NS(x=None, y=True)),
1283 ('-4 a', NS(x='a', y=True)),
1284 ]
1285
1286
1287class TestOptionalsAlmostNumericAndPositionals(ParserTestCase):
1288 """Tests negative number args when almost numeric options are present"""
1289
1290 argument_signatures = [
1291 Sig('x', nargs='?'),
1292 Sig('-k4', dest='y', action='store_true'),
1293 ]
1294 failures = ['-k3']
1295 successes = [
1296 ('', NS(x=None, y=False)),
1297 ('-2', NS(x='-2', y=False)),
1298 ('a', NS(x='a', y=False)),
1299 ('-k4', NS(x=None, y=True)),
1300 ('-k4 a', NS(x='a', y=True)),
1301 ]
1302
1303
1304class TestEmptyAndSpaceContainingArguments(ParserTestCase):
1305
1306 argument_signatures = [
1307 Sig('x', nargs='?'),
1308 Sig('-y', '--yyy', dest='y'),
1309 ]
1310 failures = ['-y']
1311 successes = [
1312 ([''], NS(x='', y=None)),
1313 (['a badger'], NS(x='a badger', y=None)),
1314 (['-a badger'], NS(x='-a badger', y=None)),
1315 (['-y', ''], NS(x=None, y='')),
1316 (['-y', 'a badger'], NS(x=None, y='a badger')),
1317 (['-y', '-a badger'], NS(x=None, y='-a badger')),
1318 (['--yyy=a badger'], NS(x=None, y='a badger')),
1319 (['--yyy=-a badger'], NS(x=None, y='-a badger')),
1320 ]
1321
1322
1323class TestPrefixCharacterOnlyArguments(ParserTestCase):
1324
1325 parser_signature = Sig(prefix_chars='-+')
1326 argument_signatures = [
1327 Sig('-', dest='x', nargs='?', const='badger'),
1328 Sig('+', dest='y', type=int, default=42),
1329 Sig('-+-', dest='z', action='store_true'),
1330 ]
1331 failures = ['-y', '+ -']
1332 successes = [
1333 ('', NS(x=None, y=42, z=False)),
1334 ('-', NS(x='badger', y=42, z=False)),
1335 ('- X', NS(x='X', y=42, z=False)),
1336 ('+ -3', NS(x=None, y=-3, z=False)),
1337 ('-+-', NS(x=None, y=42, z=True)),
1338 ('- ===', NS(x='===', y=42, z=False)),
1339 ]
1340
1341
1342class TestNargsZeroOrMore(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +00001343 """Tests specifying args for an Optional that accepts zero or more"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001344
1345 argument_signatures = [Sig('-x', nargs='*'), Sig('y', nargs='*')]
1346 failures = []
1347 successes = [
1348 ('', NS(x=None, y=[])),
1349 ('-x', NS(x=[], y=[])),
1350 ('-x a', NS(x=['a'], y=[])),
1351 ('-x a -- b', NS(x=['a'], y=['b'])),
1352 ('a', NS(x=None, y=['a'])),
1353 ('a -x', NS(x=[], y=['a'])),
1354 ('a -x b', NS(x=['b'], y=['a'])),
1355 ]
1356
1357
1358class TestNargsRemainder(ParserTestCase):
1359 """Tests specifying a positional with nargs=REMAINDER"""
1360
1361 argument_signatures = [Sig('x'), Sig('y', nargs='...'), Sig('-z')]
1362 failures = ['', '-z', '-z Z']
1363 successes = [
1364 ('X', NS(x='X', y=[], z=None)),
1365 ('-z Z X', NS(x='X', y=[], z='Z')),
1366 ('X A B -z Z', NS(x='X', y=['A', 'B', '-z', 'Z'], z=None)),
1367 ('X Y --foo', NS(x='X', y=['Y', '--foo'], z=None)),
1368 ]
1369
1370
1371class TestOptionLike(ParserTestCase):
1372 """Tests options that may or may not be arguments"""
1373
1374 argument_signatures = [
1375 Sig('-x', type=float),
1376 Sig('-3', type=float, dest='y'),
1377 Sig('z', nargs='*'),
1378 ]
1379 failures = ['-x', '-y2.5', '-xa', '-x -a',
1380 '-x -3', '-x -3.5', '-3 -3.5',
1381 '-x -2.5', '-x -2.5 a', '-3 -.5',
1382 'a x -1', '-x -1 a', '-3 -1 a']
1383 successes = [
1384 ('', NS(x=None, y=None, z=[])),
1385 ('-x 2.5', NS(x=2.5, y=None, z=[])),
1386 ('-x 2.5 a', NS(x=2.5, y=None, z=['a'])),
1387 ('-3.5', NS(x=None, y=0.5, z=[])),
1388 ('-3-.5', NS(x=None, y=-0.5, z=[])),
1389 ('-3 .5', NS(x=None, y=0.5, z=[])),
1390 ('a -3.5', NS(x=None, y=0.5, z=['a'])),
1391 ('a', NS(x=None, y=None, z=['a'])),
1392 ('a -x 1', NS(x=1.0, y=None, z=['a'])),
1393 ('-x 1 a', NS(x=1.0, y=None, z=['a'])),
1394 ('-3 1 a', NS(x=None, y=1.0, z=['a'])),
1395 ]
1396
1397
1398class TestDefaultSuppress(ParserTestCase):
1399 """Test actions with suppressed defaults"""
1400
1401 argument_signatures = [
1402 Sig('foo', nargs='?', default=argparse.SUPPRESS),
1403 Sig('bar', nargs='*', default=argparse.SUPPRESS),
1404 Sig('--baz', action='store_true', default=argparse.SUPPRESS),
1405 ]
1406 failures = ['-x']
1407 successes = [
1408 ('', NS()),
1409 ('a', NS(foo='a')),
1410 ('a b', NS(foo='a', bar=['b'])),
1411 ('--baz', NS(baz=True)),
1412 ('a --baz', NS(foo='a', baz=True)),
1413 ('--baz a b', NS(foo='a', bar=['b'], baz=True)),
1414 ]
1415
1416
1417class TestParserDefaultSuppress(ParserTestCase):
1418 """Test actions with a parser-level default of SUPPRESS"""
1419
1420 parser_signature = Sig(argument_default=argparse.SUPPRESS)
1421 argument_signatures = [
1422 Sig('foo', nargs='?'),
1423 Sig('bar', nargs='*'),
1424 Sig('--baz', action='store_true'),
1425 ]
1426 failures = ['-x']
1427 successes = [
1428 ('', NS()),
1429 ('a', NS(foo='a')),
1430 ('a b', NS(foo='a', bar=['b'])),
1431 ('--baz', NS(baz=True)),
1432 ('a --baz', NS(foo='a', baz=True)),
1433 ('--baz a b', NS(foo='a', bar=['b'], baz=True)),
1434 ]
1435
1436
1437class TestParserDefault42(ParserTestCase):
1438 """Test actions with a parser-level default of 42"""
1439
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001440 parser_signature = Sig(argument_default=42)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001441 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001442 Sig('--version', action='version', version='1.0'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001443 Sig('foo', nargs='?'),
1444 Sig('bar', nargs='*'),
1445 Sig('--baz', action='store_true'),
1446 ]
1447 failures = ['-x']
1448 successes = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001449 ('', NS(foo=42, bar=42, baz=42, version=42)),
1450 ('a', NS(foo='a', bar=42, baz=42, version=42)),
1451 ('a b', NS(foo='a', bar=['b'], baz=42, version=42)),
1452 ('--baz', NS(foo=42, bar=42, baz=True, version=42)),
1453 ('a --baz', NS(foo='a', bar=42, baz=True, version=42)),
1454 ('--baz a b', NS(foo='a', bar=['b'], baz=True, version=42)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001455 ]
1456
1457
1458class TestArgumentsFromFile(TempDirMixin, ParserTestCase):
1459 """Test reading arguments from a file"""
1460
1461 def setUp(self):
1462 super(TestArgumentsFromFile, self).setUp()
1463 file_texts = [
1464 ('hello', 'hello world!\n'),
1465 ('recursive', '-a\n'
1466 'A\n'
1467 '@hello'),
1468 ('invalid', '@no-such-path\n'),
1469 ]
1470 for path, text in file_texts:
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001471 with open(path, 'w', encoding="utf-8") as file:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001472 file.write(text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001473
1474 parser_signature = Sig(fromfile_prefix_chars='@')
1475 argument_signatures = [
1476 Sig('-a'),
1477 Sig('x'),
1478 Sig('y', nargs='+'),
1479 ]
1480 failures = ['', '-b', 'X', '@invalid', '@missing']
1481 successes = [
1482 ('X Y', NS(a=None, x='X', y=['Y'])),
1483 ('X -a A Y Z', NS(a='A', x='X', y=['Y', 'Z'])),
1484 ('@hello X', NS(a=None, x='hello world!', y=['X'])),
1485 ('X @hello', NS(a=None, x='X', y=['hello world!'])),
1486 ('-a B @recursive Y Z', NS(a='A', x='hello world!', y=['Y', 'Z'])),
1487 ('X @recursive Z -a B', NS(a='B', x='X', y=['hello world!', 'Z'])),
R David Murrayb94082a2012-07-21 22:20:11 -04001488 (["-a", "", "X", "Y"], NS(a='', x='X', y=['Y'])),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001489 ]
1490
1491
1492class TestArgumentsFromFileConverter(TempDirMixin, ParserTestCase):
1493 """Test reading arguments from a file"""
1494
1495 def setUp(self):
1496 super(TestArgumentsFromFileConverter, self).setUp()
1497 file_texts = [
1498 ('hello', 'hello world!\n'),
1499 ]
1500 for path, text in file_texts:
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001501 with open(path, 'w', encoding="utf-8") as file:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001502 file.write(text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001503
1504 class FromFileConverterArgumentParser(ErrorRaisingArgumentParser):
1505
1506 def convert_arg_line_to_args(self, arg_line):
1507 for arg in arg_line.split():
1508 if not arg.strip():
1509 continue
1510 yield arg
1511 parser_class = FromFileConverterArgumentParser
1512 parser_signature = Sig(fromfile_prefix_chars='@')
1513 argument_signatures = [
1514 Sig('y', nargs='+'),
1515 ]
1516 failures = []
1517 successes = [
1518 ('@hello X', NS(y=['hello', 'world!', 'X'])),
1519 ]
1520
1521
1522# =====================
1523# Type conversion tests
1524# =====================
1525
1526class TestFileTypeRepr(TestCase):
1527
1528 def test_r(self):
1529 type = argparse.FileType('r')
1530 self.assertEqual("FileType('r')", repr(type))
1531
1532 def test_wb_1(self):
1533 type = argparse.FileType('wb', 1)
1534 self.assertEqual("FileType('wb', 1)", repr(type))
1535
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001536 def test_r_latin(self):
1537 type = argparse.FileType('r', encoding='latin_1')
1538 self.assertEqual("FileType('r', encoding='latin_1')", repr(type))
1539
1540 def test_w_big5_ignore(self):
1541 type = argparse.FileType('w', encoding='big5', errors='ignore')
1542 self.assertEqual("FileType('w', encoding='big5', errors='ignore')",
1543 repr(type))
1544
1545 def test_r_1_replace(self):
1546 type = argparse.FileType('r', 1, errors='replace')
1547 self.assertEqual("FileType('r', 1, errors='replace')", repr(type))
1548
Steve Dowerd0f49d22018-09-18 09:10:26 -07001549class StdStreamComparer:
1550 def __init__(self, attr):
1551 self.attr = attr
1552
1553 def __eq__(self, other):
1554 return other == getattr(sys, self.attr)
1555
1556eq_stdin = StdStreamComparer('stdin')
1557eq_stdout = StdStreamComparer('stdout')
1558eq_stderr = StdStreamComparer('stderr')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001559
1560class RFile(object):
1561 seen = {}
1562
1563 def __init__(self, name):
1564 self.name = name
1565
1566 def __eq__(self, other):
1567 if other in self.seen:
1568 text = self.seen[other]
1569 else:
1570 text = self.seen[other] = other.read()
1571 other.close()
1572 if not isinstance(text, str):
1573 text = text.decode('ascii')
1574 return self.name == other.name == text
1575
1576
1577class TestFileTypeR(TempDirMixin, ParserTestCase):
1578 """Test the FileType option/argument type for reading files"""
1579
1580 def setUp(self):
1581 super(TestFileTypeR, self).setUp()
1582 for file_name in ['foo', 'bar']:
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001583 with open(os.path.join(self.temp_dir, file_name),
1584 'w', encoding="utf-8") as file:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001585 file.write(file_name)
Steven Bethardb0270112011-01-24 21:02:50 +00001586 self.create_readonly_file('readonly')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001587
1588 argument_signatures = [
1589 Sig('-x', type=argparse.FileType()),
1590 Sig('spam', type=argparse.FileType('r')),
1591 ]
Steven Bethardb0270112011-01-24 21:02:50 +00001592 failures = ['-x', '', 'non-existent-file.txt']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001593 successes = [
1594 ('foo', NS(x=None, spam=RFile('foo'))),
1595 ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
1596 ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001597 ('-x - -', NS(x=eq_stdin, spam=eq_stdin)),
Steven Bethardb0270112011-01-24 21:02:50 +00001598 ('readonly', NS(x=None, spam=RFile('readonly'))),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001599 ]
1600
R David Murray6fb8fb12012-08-31 22:45:20 -04001601class TestFileTypeDefaults(TempDirMixin, ParserTestCase):
1602 """Test that a file is not created unless the default is needed"""
1603 def setUp(self):
1604 super(TestFileTypeDefaults, self).setUp()
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001605 file = open(os.path.join(self.temp_dir, 'good'), 'w', encoding="utf-8")
R David Murray6fb8fb12012-08-31 22:45:20 -04001606 file.write('good')
1607 file.close()
1608
1609 argument_signatures = [
1610 Sig('-c', type=argparse.FileType('r'), default='no-file.txt'),
1611 ]
1612 # should provoke no such file error
1613 failures = ['']
1614 # should not provoke error because default file is created
1615 successes = [('-c good', NS(c=RFile('good')))]
1616
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001617
1618class TestFileTypeRB(TempDirMixin, ParserTestCase):
1619 """Test the FileType option/argument type for reading files"""
1620
1621 def setUp(self):
1622 super(TestFileTypeRB, self).setUp()
1623 for file_name in ['foo', 'bar']:
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001624 with open(os.path.join(self.temp_dir, file_name),
1625 'w', encoding="utf-8") as file:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001626 file.write(file_name)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001627
1628 argument_signatures = [
1629 Sig('-x', type=argparse.FileType('rb')),
1630 Sig('spam', type=argparse.FileType('rb')),
1631 ]
1632 failures = ['-x', '']
1633 successes = [
1634 ('foo', NS(x=None, spam=RFile('foo'))),
1635 ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
1636 ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001637 ('-x - -', NS(x=eq_stdin, spam=eq_stdin)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001638 ]
1639
1640
1641class WFile(object):
1642 seen = set()
1643
1644 def __init__(self, name):
1645 self.name = name
1646
1647 def __eq__(self, other):
1648 if other not in self.seen:
1649 text = 'Check that file is writable.'
1650 if 'b' in other.mode:
1651 text = text.encode('ascii')
1652 other.write(text)
1653 other.close()
1654 self.seen.add(other)
1655 return self.name == other.name
1656
1657
Victor Stinnera04b39b2011-11-20 23:09:09 +01001658@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
1659 "non-root user required")
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001660class TestFileTypeW(TempDirMixin, ParserTestCase):
1661 """Test the FileType option/argument type for writing files"""
1662
Steven Bethardb0270112011-01-24 21:02:50 +00001663 def setUp(self):
1664 super(TestFileTypeW, self).setUp()
1665 self.create_readonly_file('readonly')
1666
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001667 argument_signatures = [
1668 Sig('-x', type=argparse.FileType('w')),
1669 Sig('spam', type=argparse.FileType('w')),
1670 ]
Steven Bethardb0270112011-01-24 21:02:50 +00001671 failures = ['-x', '', 'readonly']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001672 successes = [
1673 ('foo', NS(x=None, spam=WFile('foo'))),
1674 ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
1675 ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001676 ('-x - -', NS(x=eq_stdout, spam=eq_stdout)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001677 ]
1678
1679
1680class TestFileTypeWB(TempDirMixin, ParserTestCase):
1681
1682 argument_signatures = [
1683 Sig('-x', type=argparse.FileType('wb')),
1684 Sig('spam', type=argparse.FileType('wb')),
1685 ]
1686 failures = ['-x', '']
1687 successes = [
1688 ('foo', NS(x=None, spam=WFile('foo'))),
1689 ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
1690 ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001691 ('-x - -', NS(x=eq_stdout, spam=eq_stdout)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001692 ]
1693
1694
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001695class TestFileTypeOpenArgs(TestCase):
1696 """Test that open (the builtin) is correctly called"""
1697
1698 def test_open_args(self):
1699 FT = argparse.FileType
1700 cases = [
1701 (FT('rb'), ('rb', -1, None, None)),
1702 (FT('w', 1), ('w', 1, None, None)),
1703 (FT('w', errors='replace'), ('w', -1, None, 'replace')),
1704 (FT('wb', encoding='big5'), ('wb', -1, 'big5', None)),
1705 (FT('w', 0, 'l1', 'strict'), ('w', 0, 'l1', 'strict')),
1706 ]
1707 with mock.patch('builtins.open') as m:
1708 for type, args in cases:
1709 type('foo')
1710 m.assert_called_with('foo', *args)
1711
1712
zygocephalus03d58312019-06-07 23:08:36 +03001713class TestFileTypeMissingInitialization(TestCase):
1714 """
1715 Test that add_argument throws an error if FileType class
1716 object was passed instead of instance of FileType
1717 """
1718
1719 def test(self):
1720 parser = argparse.ArgumentParser()
1721 with self.assertRaises(ValueError) as cm:
1722 parser.add_argument('-x', type=argparse.FileType)
1723
1724 self.assertEqual(
1725 '%r is a FileType class object, instance of it must be passed'
1726 % (argparse.FileType,),
1727 str(cm.exception)
1728 )
1729
1730
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001731class TestTypeCallable(ParserTestCase):
1732 """Test some callables as option/argument types"""
1733
1734 argument_signatures = [
1735 Sig('--eggs', type=complex),
1736 Sig('spam', type=float),
1737 ]
1738 failures = ['a', '42j', '--eggs a', '--eggs 2i']
1739 successes = [
1740 ('--eggs=42 42', NS(eggs=42, spam=42.0)),
1741 ('--eggs 2j -- -1.5', NS(eggs=2j, spam=-1.5)),
1742 ('1024.675', NS(eggs=None, spam=1024.675)),
1743 ]
1744
1745
1746class TestTypeUserDefined(ParserTestCase):
1747 """Test a user-defined option/argument type"""
1748
1749 class MyType(TestCase):
1750
1751 def __init__(self, value):
1752 self.value = value
1753
1754 def __eq__(self, other):
1755 return (type(self), self.value) == (type(other), other.value)
1756
1757 argument_signatures = [
1758 Sig('-x', type=MyType),
1759 Sig('spam', type=MyType),
1760 ]
1761 failures = []
1762 successes = [
1763 ('a -x b', NS(x=MyType('b'), spam=MyType('a'))),
1764 ('-xf g', NS(x=MyType('f'), spam=MyType('g'))),
1765 ]
1766
1767
1768class TestTypeClassicClass(ParserTestCase):
1769 """Test a classic class type"""
1770
1771 class C:
1772
1773 def __init__(self, value):
1774 self.value = value
1775
1776 def __eq__(self, other):
1777 return (type(self), self.value) == (type(other), other.value)
1778
1779 argument_signatures = [
1780 Sig('-x', type=C),
1781 Sig('spam', type=C),
1782 ]
1783 failures = []
1784 successes = [
1785 ('a -x b', NS(x=C('b'), spam=C('a'))),
1786 ('-xf g', NS(x=C('f'), spam=C('g'))),
1787 ]
1788
1789
1790class TestTypeRegistration(TestCase):
1791 """Test a user-defined type by registering it"""
1792
1793 def test(self):
1794
1795 def get_my_type(string):
1796 return 'my_type{%s}' % string
1797
1798 parser = argparse.ArgumentParser()
1799 parser.register('type', 'my_type', get_my_type)
1800 parser.add_argument('-x', type='my_type')
1801 parser.add_argument('y', type='my_type')
1802
1803 self.assertEqual(parser.parse_args('1'.split()),
1804 NS(x=None, y='my_type{1}'))
1805 self.assertEqual(parser.parse_args('-x 1 42'.split()),
1806 NS(x='my_type{1}', y='my_type{42}'))
1807
1808
1809# ============
1810# Action tests
1811# ============
1812
1813class TestActionUserDefined(ParserTestCase):
1814 """Test a user-defined option/argument action"""
1815
1816 class OptionalAction(argparse.Action):
1817
1818 def __call__(self, parser, namespace, value, option_string=None):
1819 try:
1820 # check destination and option string
1821 assert self.dest == 'spam', 'dest: %s' % self.dest
1822 assert option_string == '-s', 'flag: %s' % option_string
1823 # when option is before argument, badger=2, and when
1824 # option is after argument, badger=<whatever was set>
1825 expected_ns = NS(spam=0.25)
1826 if value in [0.125, 0.625]:
1827 expected_ns.badger = 2
1828 elif value in [2.0]:
1829 expected_ns.badger = 84
1830 else:
1831 raise AssertionError('value: %s' % value)
1832 assert expected_ns == namespace, ('expected %s, got %s' %
1833 (expected_ns, namespace))
1834 except AssertionError:
1835 e = sys.exc_info()[1]
1836 raise ArgumentParserError('opt_action failed: %s' % e)
1837 setattr(namespace, 'spam', value)
1838
1839 class PositionalAction(argparse.Action):
1840
1841 def __call__(self, parser, namespace, value, option_string=None):
1842 try:
1843 assert option_string is None, ('option_string: %s' %
1844 option_string)
1845 # check destination
1846 assert self.dest == 'badger', 'dest: %s' % self.dest
1847 # when argument is before option, spam=0.25, and when
1848 # option is after argument, spam=<whatever was set>
1849 expected_ns = NS(badger=2)
1850 if value in [42, 84]:
1851 expected_ns.spam = 0.25
1852 elif value in [1]:
1853 expected_ns.spam = 0.625
1854 elif value in [2]:
1855 expected_ns.spam = 0.125
1856 else:
1857 raise AssertionError('value: %s' % value)
1858 assert expected_ns == namespace, ('expected %s, got %s' %
1859 (expected_ns, namespace))
1860 except AssertionError:
1861 e = sys.exc_info()[1]
1862 raise ArgumentParserError('arg_action failed: %s' % e)
1863 setattr(namespace, 'badger', value)
1864
1865 argument_signatures = [
1866 Sig('-s', dest='spam', action=OptionalAction,
1867 type=float, default=0.25),
1868 Sig('badger', action=PositionalAction,
1869 type=int, nargs='?', default=2),
1870 ]
1871 failures = []
1872 successes = [
1873 ('-s0.125', NS(spam=0.125, badger=2)),
1874 ('42', NS(spam=0.25, badger=42)),
1875 ('-s 0.625 1', NS(spam=0.625, badger=1)),
1876 ('84 -s2', NS(spam=2.0, badger=84)),
1877 ]
1878
1879
1880class TestActionRegistration(TestCase):
1881 """Test a user-defined action supplied by registering it"""
1882
1883 class MyAction(argparse.Action):
1884
1885 def __call__(self, parser, namespace, values, option_string=None):
1886 setattr(namespace, self.dest, 'foo[%s]' % values)
1887
1888 def test(self):
1889
1890 parser = argparse.ArgumentParser()
1891 parser.register('action', 'my_action', self.MyAction)
1892 parser.add_argument('badger', action='my_action')
1893
1894 self.assertEqual(parser.parse_args(['1']), NS(badger='foo[1]'))
1895 self.assertEqual(parser.parse_args(['42']), NS(badger='foo[42]'))
1896
1897
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001898class TestActionExtend(ParserTestCase):
1899 argument_signatures = [
1900 Sig('--foo', action="extend", nargs="+", type=str),
1901 ]
1902 failures = ()
1903 successes = [
1904 ('--foo f1 --foo f2 f3 f4', NS(foo=['f1', 'f2', 'f3', 'f4'])),
1905 ]
1906
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001907# ================
1908# Subparsers tests
1909# ================
1910
1911class TestAddSubparsers(TestCase):
1912 """Test the add_subparsers method"""
1913
1914 def assertArgumentParserError(self, *args, **kwargs):
1915 self.assertRaises(ArgumentParserError, *args, **kwargs)
1916
Steven Bethardfd311a72010-12-18 11:19:23 +00001917 def _get_parser(self, subparser_help=False, prefix_chars=None,
1918 aliases=False):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001919 # create a parser with a subparsers argument
R. David Murray88c49fe2010-08-03 17:56:09 +00001920 if prefix_chars:
1921 parser = ErrorRaisingArgumentParser(
1922 prog='PROG', description='main description', prefix_chars=prefix_chars)
1923 parser.add_argument(
1924 prefix_chars[0] * 2 + 'foo', action='store_true', help='foo help')
1925 else:
1926 parser = ErrorRaisingArgumentParser(
1927 prog='PROG', description='main description')
1928 parser.add_argument(
1929 '--foo', action='store_true', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001930 parser.add_argument(
1931 'bar', type=float, help='bar help')
1932
1933 # check that only one subparsers argument can be added
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001934 subparsers_kwargs = {'required': False}
Steven Bethardfd311a72010-12-18 11:19:23 +00001935 if aliases:
1936 subparsers_kwargs['metavar'] = 'COMMAND'
1937 subparsers_kwargs['title'] = 'commands'
1938 else:
1939 subparsers_kwargs['help'] = 'command help'
1940 subparsers = parser.add_subparsers(**subparsers_kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001941 self.assertArgumentParserError(parser.add_subparsers)
1942
1943 # add first sub-parser
1944 parser1_kwargs = dict(description='1 description')
1945 if subparser_help:
1946 parser1_kwargs['help'] = '1 help'
Steven Bethardfd311a72010-12-18 11:19:23 +00001947 if aliases:
1948 parser1_kwargs['aliases'] = ['1alias1', '1alias2']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001949 parser1 = subparsers.add_parser('1', **parser1_kwargs)
1950 parser1.add_argument('-w', type=int, help='w help')
1951 parser1.add_argument('x', choices='abc', help='x help')
1952
1953 # add second sub-parser
1954 parser2_kwargs = dict(description='2 description')
1955 if subparser_help:
1956 parser2_kwargs['help'] = '2 help'
1957 parser2 = subparsers.add_parser('2', **parser2_kwargs)
1958 parser2.add_argument('-y', choices='123', help='y help')
1959 parser2.add_argument('z', type=complex, nargs='*', help='z help')
1960
R David Murray00528e82012-07-21 22:48:35 -04001961 # add third sub-parser
1962 parser3_kwargs = dict(description='3 description')
1963 if subparser_help:
1964 parser3_kwargs['help'] = '3 help'
1965 parser3 = subparsers.add_parser('3', **parser3_kwargs)
1966 parser3.add_argument('t', type=int, help='t help')
1967 parser3.add_argument('u', nargs='...', help='u help')
1968
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001969 # return the main parser
1970 return parser
1971
1972 def setUp(self):
Steven Bethard1f1c2472010-11-01 13:56:09 +00001973 super().setUp()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001974 self.parser = self._get_parser()
1975 self.command_help_parser = self._get_parser(subparser_help=True)
1976
1977 def test_parse_args_failures(self):
1978 # check some failure cases:
1979 for args_str in ['', 'a', 'a a', '0.5 a', '0.5 1',
1980 '0.5 1 -y', '0.5 2 -w']:
1981 args = args_str.split()
1982 self.assertArgumentParserError(self.parser.parse_args, args)
1983
1984 def test_parse_args(self):
1985 # check some non-failure cases:
1986 self.assertEqual(
1987 self.parser.parse_args('0.5 1 b -w 7'.split()),
1988 NS(foo=False, bar=0.5, w=7, x='b'),
1989 )
1990 self.assertEqual(
1991 self.parser.parse_args('0.25 --foo 2 -y 2 3j -- -1j'.split()),
1992 NS(foo=True, bar=0.25, y='2', z=[3j, -1j]),
1993 )
1994 self.assertEqual(
1995 self.parser.parse_args('--foo 0.125 1 c'.split()),
1996 NS(foo=True, bar=0.125, w=None, x='c'),
1997 )
R David Murray00528e82012-07-21 22:48:35 -04001998 self.assertEqual(
1999 self.parser.parse_args('-1.5 3 11 -- a --foo 7 -- b'.split()),
2000 NS(foo=False, bar=-1.5, t=11, u=['a', '--foo', '7', '--', 'b']),
2001 )
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002002
Steven Bethardfca2e8a2010-11-02 12:47:22 +00002003 def test_parse_known_args(self):
2004 self.assertEqual(
2005 self.parser.parse_known_args('0.5 1 b -w 7'.split()),
2006 (NS(foo=False, bar=0.5, w=7, x='b'), []),
2007 )
2008 self.assertEqual(
2009 self.parser.parse_known_args('0.5 -p 1 b -w 7'.split()),
2010 (NS(foo=False, bar=0.5, w=7, x='b'), ['-p']),
2011 )
2012 self.assertEqual(
2013 self.parser.parse_known_args('0.5 1 b -w 7 -p'.split()),
2014 (NS(foo=False, bar=0.5, w=7, x='b'), ['-p']),
2015 )
2016 self.assertEqual(
2017 self.parser.parse_known_args('0.5 1 b -q -rs -w 7'.split()),
2018 (NS(foo=False, bar=0.5, w=7, x='b'), ['-q', '-rs']),
2019 )
2020 self.assertEqual(
2021 self.parser.parse_known_args('0.5 -W 1 b -X Y -w 7 Z'.split()),
2022 (NS(foo=False, bar=0.5, w=7, x='b'), ['-W', '-X', 'Y', 'Z']),
2023 )
2024
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002025 def test_dest(self):
2026 parser = ErrorRaisingArgumentParser()
2027 parser.add_argument('--foo', action='store_true')
2028 subparsers = parser.add_subparsers(dest='bar')
2029 parser1 = subparsers.add_parser('1')
2030 parser1.add_argument('baz')
2031 self.assertEqual(NS(foo=False, bar='1', baz='2'),
2032 parser.parse_args('1 2'.split()))
2033
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07002034 def _test_required_subparsers(self, parser):
2035 # Should parse the sub command
2036 ret = parser.parse_args(['run'])
2037 self.assertEqual(ret.command, 'run')
2038
2039 # Error when the command is missing
2040 self.assertArgumentParserError(parser.parse_args, ())
2041
2042 def test_required_subparsers_via_attribute(self):
2043 parser = ErrorRaisingArgumentParser()
2044 subparsers = parser.add_subparsers(dest='command')
2045 subparsers.required = True
2046 subparsers.add_parser('run')
2047 self._test_required_subparsers(parser)
2048
2049 def test_required_subparsers_via_kwarg(self):
2050 parser = ErrorRaisingArgumentParser()
2051 subparsers = parser.add_subparsers(dest='command', required=True)
2052 subparsers.add_parser('run')
2053 self._test_required_subparsers(parser)
2054
2055 def test_required_subparsers_default(self):
2056 parser = ErrorRaisingArgumentParser()
2057 subparsers = parser.add_subparsers(dest='command')
2058 subparsers.add_parser('run')
Ned Deily8ebf5ce2018-05-23 21:55:15 -04002059 # No error here
2060 ret = parser.parse_args(())
2061 self.assertIsNone(ret.command)
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07002062
Miss Islington (bot)c5899922021-07-23 06:27:05 -07002063 def test_required_subparsers_no_destination_error(self):
2064 parser = ErrorRaisingArgumentParser()
2065 subparsers = parser.add_subparsers(required=True)
2066 subparsers.add_parser('foo')
2067 subparsers.add_parser('bar')
2068 with self.assertRaises(ArgumentParserError) as excinfo:
2069 parser.parse_args(())
2070 self.assertRegex(
2071 excinfo.exception.stderr,
2072 'error: the following arguments are required: {foo,bar}\n$'
2073 )
2074
2075 def test_wrong_argument_subparsers_no_destination_error(self):
2076 parser = ErrorRaisingArgumentParser()
2077 subparsers = parser.add_subparsers(required=True)
2078 subparsers.add_parser('foo')
2079 subparsers.add_parser('bar')
2080 with self.assertRaises(ArgumentParserError) as excinfo:
2081 parser.parse_args(('baz',))
2082 self.assertRegex(
2083 excinfo.exception.stderr,
2084 r"error: argument {foo,bar}: invalid choice: 'baz' \(choose from 'foo', 'bar'\)\n$"
2085 )
2086
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07002087 def test_optional_subparsers(self):
2088 parser = ErrorRaisingArgumentParser()
2089 subparsers = parser.add_subparsers(dest='command', required=False)
2090 subparsers.add_parser('run')
2091 # No error here
2092 ret = parser.parse_args(())
2093 self.assertIsNone(ret.command)
2094
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002095 def test_help(self):
2096 self.assertEqual(self.parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002097 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002098 self.assertEqual(self.parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002099 usage: PROG [-h] [--foo] bar {1,2,3} ...
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002100
2101 main description
2102
2103 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002104 bar bar help
2105 {1,2,3} command help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002106
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002107 options:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002108 -h, --help show this help message and exit
2109 --foo foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002110 '''))
2111
R. David Murray88c49fe2010-08-03 17:56:09 +00002112 def test_help_extra_prefix_chars(self):
2113 # Make sure - is still used for help if it is a non-first prefix char
2114 parser = self._get_parser(prefix_chars='+:-')
2115 self.assertEqual(parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002116 'usage: PROG [-h] [++foo] bar {1,2,3} ...\n')
R. David Murray88c49fe2010-08-03 17:56:09 +00002117 self.assertEqual(parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002118 usage: PROG [-h] [++foo] bar {1,2,3} ...
R. David Murray88c49fe2010-08-03 17:56:09 +00002119
2120 main description
2121
2122 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002123 bar bar help
2124 {1,2,3} command help
R. David Murray88c49fe2010-08-03 17:56:09 +00002125
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002126 options:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002127 -h, --help show this help message and exit
2128 ++foo foo help
R. David Murray88c49fe2010-08-03 17:56:09 +00002129 '''))
2130
Xiang Zhang7fe28ad2017-01-22 14:37:22 +08002131 def test_help_non_breaking_spaces(self):
2132 parser = ErrorRaisingArgumentParser(
2133 prog='PROG', description='main description')
2134 parser.add_argument(
2135 "--non-breaking", action='store_false',
2136 help='help message containing non-breaking spaces shall not '
2137 'wrap\N{NO-BREAK SPACE}at non-breaking spaces')
2138 self.assertEqual(parser.format_help(), textwrap.dedent('''\
2139 usage: PROG [-h] [--non-breaking]
2140
2141 main description
2142
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002143 options:
Xiang Zhang7fe28ad2017-01-22 14:37:22 +08002144 -h, --help show this help message and exit
2145 --non-breaking help message containing non-breaking spaces shall not
2146 wrap\N{NO-BREAK SPACE}at non-breaking spaces
2147 '''))
R. David Murray88c49fe2010-08-03 17:56:09 +00002148
2149 def test_help_alternate_prefix_chars(self):
2150 parser = self._get_parser(prefix_chars='+:/')
2151 self.assertEqual(parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002152 'usage: PROG [+h] [++foo] bar {1,2,3} ...\n')
R. David Murray88c49fe2010-08-03 17:56:09 +00002153 self.assertEqual(parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002154 usage: PROG [+h] [++foo] bar {1,2,3} ...
R. David Murray88c49fe2010-08-03 17:56:09 +00002155
2156 main description
2157
2158 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002159 bar bar help
2160 {1,2,3} command help
R. David Murray88c49fe2010-08-03 17:56:09 +00002161
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002162 options:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002163 +h, ++help show this help message and exit
2164 ++foo foo help
R. David Murray88c49fe2010-08-03 17:56:09 +00002165 '''))
2166
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002167 def test_parser_command_help(self):
2168 self.assertEqual(self.command_help_parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002169 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002170 self.assertEqual(self.command_help_parser.format_help(),
2171 textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002172 usage: PROG [-h] [--foo] bar {1,2,3} ...
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002173
2174 main description
2175
2176 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002177 bar bar help
2178 {1,2,3} command help
2179 1 1 help
2180 2 2 help
2181 3 3 help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002182
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002183 options:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002184 -h, --help show this help message and exit
2185 --foo foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002186 '''))
2187
2188 def test_subparser_title_help(self):
2189 parser = ErrorRaisingArgumentParser(prog='PROG',
2190 description='main description')
2191 parser.add_argument('--foo', action='store_true', help='foo help')
2192 parser.add_argument('bar', help='bar help')
2193 subparsers = parser.add_subparsers(title='subcommands',
2194 description='command help',
2195 help='additional text')
2196 parser1 = subparsers.add_parser('1')
2197 parser2 = subparsers.add_parser('2')
2198 self.assertEqual(parser.format_usage(),
2199 'usage: PROG [-h] [--foo] bar {1,2} ...\n')
2200 self.assertEqual(parser.format_help(), textwrap.dedent('''\
2201 usage: PROG [-h] [--foo] bar {1,2} ...
2202
2203 main description
2204
2205 positional arguments:
2206 bar bar help
2207
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002208 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002209 -h, --help show this help message and exit
2210 --foo foo help
2211
2212 subcommands:
2213 command help
2214
2215 {1,2} additional text
2216 '''))
2217
2218 def _test_subparser_help(self, args_str, expected_help):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002219 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002220 self.parser.parse_args(args_str.split())
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002221 self.assertEqual(expected_help, cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002222
2223 def test_subparser1_help(self):
2224 self._test_subparser_help('5.0 1 -h', textwrap.dedent('''\
2225 usage: PROG bar 1 [-h] [-w W] {a,b,c}
2226
2227 1 description
2228
2229 positional arguments:
2230 {a,b,c} x help
2231
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002232 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002233 -h, --help show this help message and exit
2234 -w W w help
2235 '''))
2236
2237 def test_subparser2_help(self):
2238 self._test_subparser_help('5.0 2 -h', textwrap.dedent('''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08002239 usage: PROG bar 2 [-h] [-y {1,2,3}] [z ...]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002240
2241 2 description
2242
2243 positional arguments:
2244 z z help
2245
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002246 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002247 -h, --help show this help message and exit
2248 -y {1,2,3} y help
2249 '''))
2250
Steven Bethardfd311a72010-12-18 11:19:23 +00002251 def test_alias_invocation(self):
2252 parser = self._get_parser(aliases=True)
2253 self.assertEqual(
2254 parser.parse_known_args('0.5 1alias1 b'.split()),
2255 (NS(foo=False, bar=0.5, w=None, x='b'), []),
2256 )
2257 self.assertEqual(
2258 parser.parse_known_args('0.5 1alias2 b'.split()),
2259 (NS(foo=False, bar=0.5, w=None, x='b'), []),
2260 )
2261
2262 def test_error_alias_invocation(self):
2263 parser = self._get_parser(aliases=True)
2264 self.assertArgumentParserError(parser.parse_args,
2265 '0.5 1alias3 b'.split())
2266
2267 def test_alias_help(self):
2268 parser = self._get_parser(aliases=True, subparser_help=True)
2269 self.maxDiff = None
2270 self.assertEqual(parser.format_help(), textwrap.dedent("""\
2271 usage: PROG [-h] [--foo] bar COMMAND ...
2272
2273 main description
2274
2275 positional arguments:
2276 bar bar help
2277
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002278 options:
Steven Bethardfd311a72010-12-18 11:19:23 +00002279 -h, --help show this help message and exit
2280 --foo foo help
2281
2282 commands:
2283 COMMAND
2284 1 (1alias1, 1alias2)
2285 1 help
2286 2 2 help
R David Murray00528e82012-07-21 22:48:35 -04002287 3 3 help
Steven Bethardfd311a72010-12-18 11:19:23 +00002288 """))
2289
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002290# ============
2291# Groups tests
2292# ============
2293
2294class TestPositionalsGroups(TestCase):
2295 """Tests that order of group positionals matches construction order"""
2296
2297 def test_nongroup_first(self):
2298 parser = ErrorRaisingArgumentParser()
2299 parser.add_argument('foo')
2300 group = parser.add_argument_group('g')
2301 group.add_argument('bar')
2302 parser.add_argument('baz')
2303 expected = NS(foo='1', bar='2', baz='3')
2304 result = parser.parse_args('1 2 3'.split())
2305 self.assertEqual(expected, result)
2306
2307 def test_group_first(self):
2308 parser = ErrorRaisingArgumentParser()
2309 group = parser.add_argument_group('xxx')
2310 group.add_argument('foo')
2311 parser.add_argument('bar')
2312 parser.add_argument('baz')
2313 expected = NS(foo='1', bar='2', baz='3')
2314 result = parser.parse_args('1 2 3'.split())
2315 self.assertEqual(expected, result)
2316
2317 def test_interleaved_groups(self):
2318 parser = ErrorRaisingArgumentParser()
2319 group = parser.add_argument_group('xxx')
2320 parser.add_argument('foo')
2321 group.add_argument('bar')
2322 parser.add_argument('baz')
2323 group = parser.add_argument_group('yyy')
2324 group.add_argument('frell')
2325 expected = NS(foo='1', bar='2', baz='3', frell='4')
2326 result = parser.parse_args('1 2 3 4'.split())
2327 self.assertEqual(expected, result)
2328
2329# ===================
2330# Parent parser tests
2331# ===================
2332
2333class TestParentParsers(TestCase):
2334 """Tests that parsers can be created with parent parsers"""
2335
2336 def assertArgumentParserError(self, *args, **kwargs):
2337 self.assertRaises(ArgumentParserError, *args, **kwargs)
2338
2339 def setUp(self):
Steven Bethard1f1c2472010-11-01 13:56:09 +00002340 super().setUp()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002341 self.wxyz_parent = ErrorRaisingArgumentParser(add_help=False)
2342 self.wxyz_parent.add_argument('--w')
2343 x_group = self.wxyz_parent.add_argument_group('x')
2344 x_group.add_argument('-y')
2345 self.wxyz_parent.add_argument('z')
2346
2347 self.abcd_parent = ErrorRaisingArgumentParser(add_help=False)
2348 self.abcd_parent.add_argument('a')
2349 self.abcd_parent.add_argument('-b')
2350 c_group = self.abcd_parent.add_argument_group('c')
2351 c_group.add_argument('--d')
2352
2353 self.w_parent = ErrorRaisingArgumentParser(add_help=False)
2354 self.w_parent.add_argument('--w')
2355
2356 self.z_parent = ErrorRaisingArgumentParser(add_help=False)
2357 self.z_parent.add_argument('z')
2358
2359 # parents with mutually exclusive groups
2360 self.ab_mutex_parent = ErrorRaisingArgumentParser(add_help=False)
2361 group = self.ab_mutex_parent.add_mutually_exclusive_group()
2362 group.add_argument('-a', action='store_true')
2363 group.add_argument('-b', action='store_true')
2364
2365 self.main_program = os.path.basename(sys.argv[0])
2366
2367 def test_single_parent(self):
2368 parser = ErrorRaisingArgumentParser(parents=[self.wxyz_parent])
2369 self.assertEqual(parser.parse_args('-y 1 2 --w 3'.split()),
2370 NS(w='3', y='1', z='2'))
2371
2372 def test_single_parent_mutex(self):
2373 self._test_mutex_ab(self.ab_mutex_parent.parse_args)
2374 parser = ErrorRaisingArgumentParser(parents=[self.ab_mutex_parent])
2375 self._test_mutex_ab(parser.parse_args)
2376
2377 def test_single_granparent_mutex(self):
2378 parents = [self.ab_mutex_parent]
2379 parser = ErrorRaisingArgumentParser(add_help=False, parents=parents)
2380 parser = ErrorRaisingArgumentParser(parents=[parser])
2381 self._test_mutex_ab(parser.parse_args)
2382
2383 def _test_mutex_ab(self, parse_args):
2384 self.assertEqual(parse_args([]), NS(a=False, b=False))
2385 self.assertEqual(parse_args(['-a']), NS(a=True, b=False))
2386 self.assertEqual(parse_args(['-b']), NS(a=False, b=True))
2387 self.assertArgumentParserError(parse_args, ['-a', '-b'])
2388 self.assertArgumentParserError(parse_args, ['-b', '-a'])
2389 self.assertArgumentParserError(parse_args, ['-c'])
2390 self.assertArgumentParserError(parse_args, ['-a', '-c'])
2391 self.assertArgumentParserError(parse_args, ['-b', '-c'])
2392
2393 def test_multiple_parents(self):
2394 parents = [self.abcd_parent, self.wxyz_parent]
2395 parser = ErrorRaisingArgumentParser(parents=parents)
2396 self.assertEqual(parser.parse_args('--d 1 --w 2 3 4'.split()),
2397 NS(a='3', b=None, d='1', w='2', y=None, z='4'))
2398
2399 def test_multiple_parents_mutex(self):
2400 parents = [self.ab_mutex_parent, self.wxyz_parent]
2401 parser = ErrorRaisingArgumentParser(parents=parents)
2402 self.assertEqual(parser.parse_args('-a --w 2 3'.split()),
2403 NS(a=True, b=False, w='2', y=None, z='3'))
2404 self.assertArgumentParserError(
2405 parser.parse_args, '-a --w 2 3 -b'.split())
2406 self.assertArgumentParserError(
2407 parser.parse_args, '-a -b --w 2 3'.split())
2408
2409 def test_conflicting_parents(self):
2410 self.assertRaises(
2411 argparse.ArgumentError,
2412 argparse.ArgumentParser,
2413 parents=[self.w_parent, self.wxyz_parent])
2414
2415 def test_conflicting_parents_mutex(self):
2416 self.assertRaises(
2417 argparse.ArgumentError,
2418 argparse.ArgumentParser,
2419 parents=[self.abcd_parent, self.ab_mutex_parent])
2420
2421 def test_same_argument_name_parents(self):
2422 parents = [self.wxyz_parent, self.z_parent]
2423 parser = ErrorRaisingArgumentParser(parents=parents)
2424 self.assertEqual(parser.parse_args('1 2'.split()),
2425 NS(w=None, y=None, z='2'))
2426
2427 def test_subparser_parents(self):
2428 parser = ErrorRaisingArgumentParser()
2429 subparsers = parser.add_subparsers()
2430 abcde_parser = subparsers.add_parser('bar', parents=[self.abcd_parent])
2431 abcde_parser.add_argument('e')
2432 self.assertEqual(parser.parse_args('bar -b 1 --d 2 3 4'.split()),
2433 NS(a='3', b='1', d='2', e='4'))
2434
2435 def test_subparser_parents_mutex(self):
2436 parser = ErrorRaisingArgumentParser()
2437 subparsers = parser.add_subparsers()
2438 parents = [self.ab_mutex_parent]
2439 abc_parser = subparsers.add_parser('foo', parents=parents)
2440 c_group = abc_parser.add_argument_group('c_group')
2441 c_group.add_argument('c')
2442 parents = [self.wxyz_parent, self.ab_mutex_parent]
2443 wxyzabe_parser = subparsers.add_parser('bar', parents=parents)
2444 wxyzabe_parser.add_argument('e')
2445 self.assertEqual(parser.parse_args('foo -a 4'.split()),
2446 NS(a=True, b=False, c='4'))
2447 self.assertEqual(parser.parse_args('bar -b --w 2 3 4'.split()),
2448 NS(a=False, b=True, w='2', y=None, z='3', e='4'))
2449 self.assertArgumentParserError(
2450 parser.parse_args, 'foo -a -b 4'.split())
2451 self.assertArgumentParserError(
2452 parser.parse_args, 'bar -b -a 4'.split())
2453
2454 def test_parent_help(self):
2455 parents = [self.abcd_parent, self.wxyz_parent]
2456 parser = ErrorRaisingArgumentParser(parents=parents)
2457 parser_help = parser.format_help()
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002458 progname = self.main_program
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002459 self.assertEqual(parser_help, textwrap.dedent('''\
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002460 usage: {}{}[-h] [-b B] [--d D] [--w W] [-y Y] a z
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002461
2462 positional arguments:
2463 a
2464 z
2465
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002466 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002467 -h, --help show this help message and exit
2468 -b B
2469 --w W
2470
2471 c:
2472 --d D
2473
2474 x:
2475 -y Y
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002476 '''.format(progname, ' ' if progname else '' )))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002477
2478 def test_groups_parents(self):
2479 parent = ErrorRaisingArgumentParser(add_help=False)
2480 g = parent.add_argument_group(title='g', description='gd')
2481 g.add_argument('-w')
2482 g.add_argument('-x')
2483 m = parent.add_mutually_exclusive_group()
2484 m.add_argument('-y')
2485 m.add_argument('-z')
2486 parser = ErrorRaisingArgumentParser(parents=[parent])
2487
2488 self.assertRaises(ArgumentParserError, parser.parse_args,
2489 ['-y', 'Y', '-z', 'Z'])
2490
2491 parser_help = parser.format_help()
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002492 progname = self.main_program
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002493 self.assertEqual(parser_help, textwrap.dedent('''\
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002494 usage: {}{}[-h] [-w W] [-x X] [-y Y | -z Z]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002495
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002496 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002497 -h, --help show this help message and exit
2498 -y Y
2499 -z Z
2500
2501 g:
2502 gd
2503
2504 -w W
2505 -x X
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002506 '''.format(progname, ' ' if progname else '' )))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002507
2508# ==============================
2509# Mutually exclusive group tests
2510# ==============================
2511
2512class TestMutuallyExclusiveGroupErrors(TestCase):
2513
2514 def test_invalid_add_argument_group(self):
2515 parser = ErrorRaisingArgumentParser()
2516 raises = self.assertRaises
2517 raises(TypeError, parser.add_mutually_exclusive_group, title='foo')
2518
2519 def test_invalid_add_argument(self):
2520 parser = ErrorRaisingArgumentParser()
2521 group = parser.add_mutually_exclusive_group()
2522 add_argument = group.add_argument
2523 raises = self.assertRaises
2524 raises(ValueError, add_argument, '--foo', required=True)
2525 raises(ValueError, add_argument, 'bar')
2526 raises(ValueError, add_argument, 'bar', nargs='+')
2527 raises(ValueError, add_argument, 'bar', nargs=1)
2528 raises(ValueError, add_argument, 'bar', nargs=argparse.PARSER)
2529
Steven Bethard49998ee2010-11-01 16:29:26 +00002530 def test_help(self):
2531 parser = ErrorRaisingArgumentParser(prog='PROG')
2532 group1 = parser.add_mutually_exclusive_group()
2533 group1.add_argument('--foo', action='store_true')
2534 group1.add_argument('--bar', action='store_false')
2535 group2 = parser.add_mutually_exclusive_group()
2536 group2.add_argument('--soup', action='store_true')
2537 group2.add_argument('--nuts', action='store_false')
2538 expected = '''\
2539 usage: PROG [-h] [--foo | --bar] [--soup | --nuts]
2540
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002541 options:
Steven Bethard49998ee2010-11-01 16:29:26 +00002542 -h, --help show this help message and exit
2543 --foo
2544 --bar
2545 --soup
2546 --nuts
2547 '''
2548 self.assertEqual(parser.format_help(), textwrap.dedent(expected))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002549
2550class MEMixin(object):
2551
2552 def test_failures_when_not_required(self):
2553 parse_args = self.get_parser(required=False).parse_args
2554 error = ArgumentParserError
2555 for args_string in self.failures:
2556 self.assertRaises(error, parse_args, args_string.split())
2557
2558 def test_failures_when_required(self):
2559 parse_args = self.get_parser(required=True).parse_args
2560 error = ArgumentParserError
2561 for args_string in self.failures + ['']:
2562 self.assertRaises(error, parse_args, args_string.split())
2563
2564 def test_successes_when_not_required(self):
2565 parse_args = self.get_parser(required=False).parse_args
2566 successes = self.successes + self.successes_when_not_required
2567 for args_string, expected_ns in successes:
2568 actual_ns = parse_args(args_string.split())
2569 self.assertEqual(actual_ns, expected_ns)
2570
2571 def test_successes_when_required(self):
2572 parse_args = self.get_parser(required=True).parse_args
2573 for args_string, expected_ns in self.successes:
2574 actual_ns = parse_args(args_string.split())
2575 self.assertEqual(actual_ns, expected_ns)
2576
2577 def test_usage_when_not_required(self):
2578 format_usage = self.get_parser(required=False).format_usage
2579 expected_usage = self.usage_when_not_required
2580 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))
2581
2582 def test_usage_when_required(self):
2583 format_usage = self.get_parser(required=True).format_usage
2584 expected_usage = self.usage_when_required
2585 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))
2586
2587 def test_help_when_not_required(self):
2588 format_help = self.get_parser(required=False).format_help
2589 help = self.usage_when_not_required + self.help
2590 self.assertEqual(format_help(), textwrap.dedent(help))
2591
2592 def test_help_when_required(self):
2593 format_help = self.get_parser(required=True).format_help
2594 help = self.usage_when_required + self.help
2595 self.assertEqual(format_help(), textwrap.dedent(help))
2596
2597
2598class TestMutuallyExclusiveSimple(MEMixin, TestCase):
2599
2600 def get_parser(self, required=None):
2601 parser = ErrorRaisingArgumentParser(prog='PROG')
2602 group = parser.add_mutually_exclusive_group(required=required)
2603 group.add_argument('--bar', help='bar help')
2604 group.add_argument('--baz', nargs='?', const='Z', help='baz help')
2605 return parser
2606
2607 failures = ['--bar X --baz Y', '--bar X --baz']
2608 successes = [
2609 ('--bar X', NS(bar='X', baz=None)),
2610 ('--bar X --bar Z', NS(bar='Z', baz=None)),
2611 ('--baz Y', NS(bar=None, baz='Y')),
2612 ('--baz', NS(bar=None, baz='Z')),
2613 ]
2614 successes_when_not_required = [
2615 ('', NS(bar=None, baz=None)),
2616 ]
2617
2618 usage_when_not_required = '''\
2619 usage: PROG [-h] [--bar BAR | --baz [BAZ]]
2620 '''
2621 usage_when_required = '''\
2622 usage: PROG [-h] (--bar BAR | --baz [BAZ])
2623 '''
2624 help = '''\
2625
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002626 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002627 -h, --help show this help message and exit
2628 --bar BAR bar help
2629 --baz [BAZ] baz help
2630 '''
2631
2632
2633class TestMutuallyExclusiveLong(MEMixin, TestCase):
2634
2635 def get_parser(self, required=None):
2636 parser = ErrorRaisingArgumentParser(prog='PROG')
2637 parser.add_argument('--abcde', help='abcde help')
2638 parser.add_argument('--fghij', help='fghij help')
2639 group = parser.add_mutually_exclusive_group(required=required)
2640 group.add_argument('--klmno', help='klmno help')
2641 group.add_argument('--pqrst', help='pqrst help')
2642 return parser
2643
2644 failures = ['--klmno X --pqrst Y']
2645 successes = [
2646 ('--klmno X', NS(abcde=None, fghij=None, klmno='X', pqrst=None)),
2647 ('--abcde Y --klmno X',
2648 NS(abcde='Y', fghij=None, klmno='X', pqrst=None)),
2649 ('--pqrst X', NS(abcde=None, fghij=None, klmno=None, pqrst='X')),
2650 ('--pqrst X --fghij Y',
2651 NS(abcde=None, fghij='Y', klmno=None, pqrst='X')),
2652 ]
2653 successes_when_not_required = [
2654 ('', NS(abcde=None, fghij=None, klmno=None, pqrst=None)),
2655 ]
2656
2657 usage_when_not_required = '''\
2658 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]
2659 [--klmno KLMNO | --pqrst PQRST]
2660 '''
2661 usage_when_required = '''\
2662 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]
2663 (--klmno KLMNO | --pqrst PQRST)
2664 '''
2665 help = '''\
2666
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002667 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002668 -h, --help show this help message and exit
2669 --abcde ABCDE abcde help
2670 --fghij FGHIJ fghij help
2671 --klmno KLMNO klmno help
2672 --pqrst PQRST pqrst help
2673 '''
2674
2675
2676class TestMutuallyExclusiveFirstSuppressed(MEMixin, TestCase):
2677
2678 def get_parser(self, required):
2679 parser = ErrorRaisingArgumentParser(prog='PROG')
2680 group = parser.add_mutually_exclusive_group(required=required)
2681 group.add_argument('-x', help=argparse.SUPPRESS)
2682 group.add_argument('-y', action='store_false', help='y help')
2683 return parser
2684
2685 failures = ['-x X -y']
2686 successes = [
2687 ('-x X', NS(x='X', y=True)),
2688 ('-x X -x Y', NS(x='Y', y=True)),
2689 ('-y', NS(x=None, y=False)),
2690 ]
2691 successes_when_not_required = [
2692 ('', NS(x=None, y=True)),
2693 ]
2694
2695 usage_when_not_required = '''\
2696 usage: PROG [-h] [-y]
2697 '''
2698 usage_when_required = '''\
2699 usage: PROG [-h] -y
2700 '''
2701 help = '''\
2702
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002703 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002704 -h, --help show this help message and exit
2705 -y y help
2706 '''
2707
2708
2709class TestMutuallyExclusiveManySuppressed(MEMixin, TestCase):
2710
2711 def get_parser(self, required):
2712 parser = ErrorRaisingArgumentParser(prog='PROG')
2713 group = parser.add_mutually_exclusive_group(required=required)
2714 add = group.add_argument
2715 add('--spam', action='store_true', help=argparse.SUPPRESS)
2716 add('--badger', action='store_false', help=argparse.SUPPRESS)
2717 add('--bladder', help=argparse.SUPPRESS)
2718 return parser
2719
2720 failures = [
2721 '--spam --badger',
2722 '--badger --bladder B',
2723 '--bladder B --spam',
2724 ]
2725 successes = [
2726 ('--spam', NS(spam=True, badger=True, bladder=None)),
2727 ('--badger', NS(spam=False, badger=False, bladder=None)),
2728 ('--bladder B', NS(spam=False, badger=True, bladder='B')),
2729 ('--spam --spam', NS(spam=True, badger=True, bladder=None)),
2730 ]
2731 successes_when_not_required = [
2732 ('', NS(spam=False, badger=True, bladder=None)),
2733 ]
2734
2735 usage_when_required = usage_when_not_required = '''\
2736 usage: PROG [-h]
2737 '''
2738 help = '''\
2739
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002740 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002741 -h, --help show this help message and exit
2742 '''
2743
2744
2745class TestMutuallyExclusiveOptionalAndPositional(MEMixin, TestCase):
2746
2747 def get_parser(self, required):
2748 parser = ErrorRaisingArgumentParser(prog='PROG')
2749 group = parser.add_mutually_exclusive_group(required=required)
2750 group.add_argument('--foo', action='store_true', help='FOO')
2751 group.add_argument('--spam', help='SPAM')
2752 group.add_argument('badger', nargs='*', default='X', help='BADGER')
2753 return parser
2754
2755 failures = [
2756 '--foo --spam S',
2757 '--spam S X',
2758 'X --foo',
2759 'X Y Z --spam S',
2760 '--foo X Y',
2761 ]
2762 successes = [
2763 ('--foo', NS(foo=True, spam=None, badger='X')),
2764 ('--spam S', NS(foo=False, spam='S', badger='X')),
2765 ('X', NS(foo=False, spam=None, badger=['X'])),
2766 ('X Y Z', NS(foo=False, spam=None, badger=['X', 'Y', 'Z'])),
2767 ]
2768 successes_when_not_required = [
2769 ('', NS(foo=False, spam=None, badger='X')),
2770 ]
2771
2772 usage_when_not_required = '''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08002773 usage: PROG [-h] [--foo | --spam SPAM | badger ...]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002774 '''
2775 usage_when_required = '''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08002776 usage: PROG [-h] (--foo | --spam SPAM | badger ...)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002777 '''
2778 help = '''\
2779
2780 positional arguments:
2781 badger BADGER
2782
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002783 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002784 -h, --help show this help message and exit
2785 --foo FOO
2786 --spam SPAM SPAM
2787 '''
2788
2789
2790class TestMutuallyExclusiveOptionalsMixed(MEMixin, TestCase):
2791
2792 def get_parser(self, required):
2793 parser = ErrorRaisingArgumentParser(prog='PROG')
2794 parser.add_argument('-x', action='store_true', help='x help')
2795 group = parser.add_mutually_exclusive_group(required=required)
2796 group.add_argument('-a', action='store_true', help='a help')
2797 group.add_argument('-b', action='store_true', help='b help')
2798 parser.add_argument('-y', action='store_true', help='y help')
2799 group.add_argument('-c', action='store_true', help='c help')
2800 return parser
2801
2802 failures = ['-a -b', '-b -c', '-a -c', '-a -b -c']
2803 successes = [
2804 ('-a', NS(a=True, b=False, c=False, x=False, y=False)),
2805 ('-b', NS(a=False, b=True, c=False, x=False, y=False)),
2806 ('-c', NS(a=False, b=False, c=True, x=False, y=False)),
2807 ('-a -x', NS(a=True, b=False, c=False, x=True, y=False)),
2808 ('-y -b', NS(a=False, b=True, c=False, x=False, y=True)),
2809 ('-x -y -c', NS(a=False, b=False, c=True, x=True, y=True)),
2810 ]
2811 successes_when_not_required = [
2812 ('', NS(a=False, b=False, c=False, x=False, y=False)),
2813 ('-x', NS(a=False, b=False, c=False, x=True, y=False)),
2814 ('-y', NS(a=False, b=False, c=False, x=False, y=True)),
2815 ]
2816
2817 usage_when_required = usage_when_not_required = '''\
2818 usage: PROG [-h] [-x] [-a] [-b] [-y] [-c]
2819 '''
2820 help = '''\
2821
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002822 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002823 -h, --help show this help message and exit
2824 -x x help
2825 -a a help
2826 -b b help
2827 -y y help
2828 -c c help
2829 '''
2830
2831
Georg Brandl0f6b47a2011-01-30 12:19:35 +00002832class TestMutuallyExclusiveInGroup(MEMixin, TestCase):
2833
2834 def get_parser(self, required=None):
2835 parser = ErrorRaisingArgumentParser(prog='PROG')
2836 titled_group = parser.add_argument_group(
2837 title='Titled group', description='Group description')
2838 mutex_group = \
2839 titled_group.add_mutually_exclusive_group(required=required)
2840 mutex_group.add_argument('--bar', help='bar help')
2841 mutex_group.add_argument('--baz', help='baz help')
2842 return parser
2843
2844 failures = ['--bar X --baz Y', '--baz X --bar Y']
2845 successes = [
2846 ('--bar X', NS(bar='X', baz=None)),
2847 ('--baz Y', NS(bar=None, baz='Y')),
2848 ]
2849 successes_when_not_required = [
2850 ('', NS(bar=None, baz=None)),
2851 ]
2852
2853 usage_when_not_required = '''\
2854 usage: PROG [-h] [--bar BAR | --baz BAZ]
2855 '''
2856 usage_when_required = '''\
2857 usage: PROG [-h] (--bar BAR | --baz BAZ)
2858 '''
2859 help = '''\
2860
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002861 options:
Georg Brandl0f6b47a2011-01-30 12:19:35 +00002862 -h, --help show this help message and exit
2863
2864 Titled group:
2865 Group description
2866
2867 --bar BAR bar help
2868 --baz BAZ baz help
2869 '''
2870
2871
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002872class TestMutuallyExclusiveOptionalsAndPositionalsMixed(MEMixin, TestCase):
2873
2874 def get_parser(self, required):
2875 parser = ErrorRaisingArgumentParser(prog='PROG')
2876 parser.add_argument('x', help='x help')
2877 parser.add_argument('-y', action='store_true', help='y help')
2878 group = parser.add_mutually_exclusive_group(required=required)
2879 group.add_argument('a', nargs='?', help='a help')
2880 group.add_argument('-b', action='store_true', help='b help')
2881 group.add_argument('-c', action='store_true', help='c help')
2882 return parser
2883
2884 failures = ['X A -b', '-b -c', '-c X A']
2885 successes = [
2886 ('X A', NS(a='A', b=False, c=False, x='X', y=False)),
2887 ('X -b', NS(a=None, b=True, c=False, x='X', y=False)),
2888 ('X -c', NS(a=None, b=False, c=True, x='X', y=False)),
2889 ('X A -y', NS(a='A', b=False, c=False, x='X', y=True)),
2890 ('X -y -b', NS(a=None, b=True, c=False, x='X', y=True)),
2891 ]
2892 successes_when_not_required = [
2893 ('X', NS(a=None, b=False, c=False, x='X', y=False)),
2894 ('X -y', NS(a=None, b=False, c=False, x='X', y=True)),
2895 ]
2896
2897 usage_when_required = usage_when_not_required = '''\
2898 usage: PROG [-h] [-y] [-b] [-c] x [a]
2899 '''
2900 help = '''\
2901
2902 positional arguments:
2903 x x help
2904 a a help
2905
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002906 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002907 -h, --help show this help message and exit
2908 -y y help
2909 -b b help
2910 -c c help
2911 '''
2912
Flavian Hautboisda27d9b2019-08-25 21:06:45 +02002913class TestMutuallyExclusiveNested(MEMixin, TestCase):
2914
2915 def get_parser(self, required):
2916 parser = ErrorRaisingArgumentParser(prog='PROG')
2917 group = parser.add_mutually_exclusive_group(required=required)
2918 group.add_argument('-a')
2919 group.add_argument('-b')
2920 group2 = group.add_mutually_exclusive_group(required=required)
2921 group2.add_argument('-c')
2922 group2.add_argument('-d')
2923 group3 = group2.add_mutually_exclusive_group(required=required)
2924 group3.add_argument('-e')
2925 group3.add_argument('-f')
2926 return parser
2927
2928 usage_when_not_required = '''\
2929 usage: PROG [-h] [-a A | -b B | [-c C | -d D | [-e E | -f F]]]
2930 '''
2931 usage_when_required = '''\
2932 usage: PROG [-h] (-a A | -b B | (-c C | -d D | (-e E | -f F)))
2933 '''
2934
2935 help = '''\
2936
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002937 options:
Flavian Hautboisda27d9b2019-08-25 21:06:45 +02002938 -h, --help show this help message and exit
2939 -a A
2940 -b B
2941 -c C
2942 -d D
2943 -e E
2944 -f F
2945 '''
2946
2947 # We are only interested in testing the behavior of format_usage().
2948 test_failures_when_not_required = None
2949 test_failures_when_required = None
2950 test_successes_when_not_required = None
2951 test_successes_when_required = None
2952
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002953# =================================================
2954# Mutually exclusive group in parent parser tests
2955# =================================================
2956
2957class MEPBase(object):
2958
2959 def get_parser(self, required=None):
2960 parent = super(MEPBase, self).get_parser(required=required)
2961 parser = ErrorRaisingArgumentParser(
2962 prog=parent.prog, add_help=False, parents=[parent])
2963 return parser
2964
2965
2966class TestMutuallyExclusiveGroupErrorsParent(
2967 MEPBase, TestMutuallyExclusiveGroupErrors):
2968 pass
2969
2970
2971class TestMutuallyExclusiveSimpleParent(
2972 MEPBase, TestMutuallyExclusiveSimple):
2973 pass
2974
2975
2976class TestMutuallyExclusiveLongParent(
2977 MEPBase, TestMutuallyExclusiveLong):
2978 pass
2979
2980
2981class TestMutuallyExclusiveFirstSuppressedParent(
2982 MEPBase, TestMutuallyExclusiveFirstSuppressed):
2983 pass
2984
2985
2986class TestMutuallyExclusiveManySuppressedParent(
2987 MEPBase, TestMutuallyExclusiveManySuppressed):
2988 pass
2989
2990
2991class TestMutuallyExclusiveOptionalAndPositionalParent(
2992 MEPBase, TestMutuallyExclusiveOptionalAndPositional):
2993 pass
2994
2995
2996class TestMutuallyExclusiveOptionalsMixedParent(
2997 MEPBase, TestMutuallyExclusiveOptionalsMixed):
2998 pass
2999
3000
3001class TestMutuallyExclusiveOptionalsAndPositionalsMixedParent(
3002 MEPBase, TestMutuallyExclusiveOptionalsAndPositionalsMixed):
3003 pass
3004
3005# =================
3006# Set default tests
3007# =================
3008
3009class TestSetDefaults(TestCase):
3010
3011 def test_set_defaults_no_args(self):
3012 parser = ErrorRaisingArgumentParser()
3013 parser.set_defaults(x='foo')
3014 parser.set_defaults(y='bar', z=1)
3015 self.assertEqual(NS(x='foo', y='bar', z=1),
3016 parser.parse_args([]))
3017 self.assertEqual(NS(x='foo', y='bar', z=1),
3018 parser.parse_args([], NS()))
3019 self.assertEqual(NS(x='baz', y='bar', z=1),
3020 parser.parse_args([], NS(x='baz')))
3021 self.assertEqual(NS(x='baz', y='bar', z=2),
3022 parser.parse_args([], NS(x='baz', z=2)))
3023
3024 def test_set_defaults_with_args(self):
3025 parser = ErrorRaisingArgumentParser()
3026 parser.set_defaults(x='foo', y='bar')
3027 parser.add_argument('-x', default='xfoox')
3028 self.assertEqual(NS(x='xfoox', y='bar'),
3029 parser.parse_args([]))
3030 self.assertEqual(NS(x='xfoox', y='bar'),
3031 parser.parse_args([], NS()))
3032 self.assertEqual(NS(x='baz', y='bar'),
3033 parser.parse_args([], NS(x='baz')))
3034 self.assertEqual(NS(x='1', y='bar'),
3035 parser.parse_args('-x 1'.split()))
3036 self.assertEqual(NS(x='1', y='bar'),
3037 parser.parse_args('-x 1'.split(), NS()))
3038 self.assertEqual(NS(x='1', y='bar'),
3039 parser.parse_args('-x 1'.split(), NS(x='baz')))
3040
3041 def test_set_defaults_subparsers(self):
3042 parser = ErrorRaisingArgumentParser()
3043 parser.set_defaults(x='foo')
3044 subparsers = parser.add_subparsers()
3045 parser_a = subparsers.add_parser('a')
3046 parser_a.set_defaults(y='bar')
3047 self.assertEqual(NS(x='foo', y='bar'),
3048 parser.parse_args('a'.split()))
3049
3050 def test_set_defaults_parents(self):
3051 parent = ErrorRaisingArgumentParser(add_help=False)
3052 parent.set_defaults(x='foo')
3053 parser = ErrorRaisingArgumentParser(parents=[parent])
3054 self.assertEqual(NS(x='foo'), parser.parse_args([]))
3055
R David Murray7570cbd2014-10-17 19:55:11 -04003056 def test_set_defaults_on_parent_and_subparser(self):
3057 parser = argparse.ArgumentParser()
3058 xparser = parser.add_subparsers().add_parser('X')
3059 parser.set_defaults(foo=1)
3060 xparser.set_defaults(foo=2)
3061 self.assertEqual(NS(foo=2), parser.parse_args(['X']))
3062
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003063 def test_set_defaults_same_as_add_argument(self):
3064 parser = ErrorRaisingArgumentParser()
3065 parser.set_defaults(w='W', x='X', y='Y', z='Z')
3066 parser.add_argument('-w')
3067 parser.add_argument('-x', default='XX')
3068 parser.add_argument('y', nargs='?')
3069 parser.add_argument('z', nargs='?', default='ZZ')
3070
3071 # defaults set previously
3072 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
3073 parser.parse_args([]))
3074
3075 # reset defaults
3076 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
3077 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
3078 parser.parse_args([]))
3079
3080 def test_set_defaults_same_as_add_argument_group(self):
3081 parser = ErrorRaisingArgumentParser()
3082 parser.set_defaults(w='W', x='X', y='Y', z='Z')
3083 group = parser.add_argument_group('foo')
3084 group.add_argument('-w')
3085 group.add_argument('-x', default='XX')
3086 group.add_argument('y', nargs='?')
3087 group.add_argument('z', nargs='?', default='ZZ')
3088
3089
3090 # defaults set previously
3091 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
3092 parser.parse_args([]))
3093
3094 # reset defaults
3095 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
3096 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
3097 parser.parse_args([]))
3098
3099# =================
3100# Get default tests
3101# =================
3102
3103class TestGetDefault(TestCase):
3104
3105 def test_get_default(self):
3106 parser = ErrorRaisingArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003107 self.assertIsNone(parser.get_default("foo"))
3108 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003109
3110 parser.add_argument("--foo")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003111 self.assertIsNone(parser.get_default("foo"))
3112 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003113
3114 parser.add_argument("--bar", type=int, default=42)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003115 self.assertIsNone(parser.get_default("foo"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003116 self.assertEqual(42, parser.get_default("bar"))
3117
3118 parser.set_defaults(foo="badger")
3119 self.assertEqual("badger", parser.get_default("foo"))
3120 self.assertEqual(42, parser.get_default("bar"))
3121
3122# ==========================
3123# Namespace 'contains' tests
3124# ==========================
3125
3126class TestNamespaceContainsSimple(TestCase):
3127
3128 def test_empty(self):
3129 ns = argparse.Namespace()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003130 self.assertNotIn('', ns)
3131 self.assertNotIn('x', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003132
3133 def test_non_empty(self):
3134 ns = argparse.Namespace(x=1, y=2)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003135 self.assertNotIn('', ns)
3136 self.assertIn('x', ns)
3137 self.assertIn('y', ns)
3138 self.assertNotIn('xx', ns)
3139 self.assertNotIn('z', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003140
3141# =====================
3142# Help formatting tests
3143# =====================
3144
3145class TestHelpFormattingMetaclass(type):
3146
3147 def __init__(cls, name, bases, bodydict):
3148 if name == 'HelpTestCase':
3149 return
3150
3151 class AddTests(object):
3152
3153 def __init__(self, test_class, func_suffix, std_name):
3154 self.func_suffix = func_suffix
3155 self.std_name = std_name
3156
3157 for test_func in [self.test_format,
3158 self.test_print,
3159 self.test_print_file]:
3160 test_name = '%s_%s' % (test_func.__name__, func_suffix)
3161
3162 def test_wrapper(self, test_func=test_func):
3163 test_func(self)
3164 try:
3165 test_wrapper.__name__ = test_name
3166 except TypeError:
3167 pass
3168 setattr(test_class, test_name, test_wrapper)
3169
3170 def _get_parser(self, tester):
3171 parser = argparse.ArgumentParser(
3172 *tester.parser_signature.args,
3173 **tester.parser_signature.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003174 for argument_sig in getattr(tester, 'argument_signatures', []):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003175 parser.add_argument(*argument_sig.args,
3176 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003177 group_sigs = getattr(tester, 'argument_group_signatures', [])
3178 for group_sig, argument_sigs in group_sigs:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003179 group = parser.add_argument_group(*group_sig.args,
3180 **group_sig.kwargs)
3181 for argument_sig in argument_sigs:
3182 group.add_argument(*argument_sig.args,
3183 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003184 subparsers_sigs = getattr(tester, 'subparsers_signatures', [])
3185 if subparsers_sigs:
3186 subparsers = parser.add_subparsers()
3187 for subparser_sig in subparsers_sigs:
3188 subparsers.add_parser(*subparser_sig.args,
3189 **subparser_sig.kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003190 return parser
3191
3192 def _test(self, tester, parser_text):
3193 expected_text = getattr(tester, self.func_suffix)
3194 expected_text = textwrap.dedent(expected_text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003195 tester.assertEqual(expected_text, parser_text)
3196
3197 def test_format(self, tester):
3198 parser = self._get_parser(tester)
3199 format = getattr(parser, 'format_%s' % self.func_suffix)
3200 self._test(tester, format())
3201
3202 def test_print(self, tester):
3203 parser = self._get_parser(tester)
3204 print_ = getattr(parser, 'print_%s' % self.func_suffix)
3205 old_stream = getattr(sys, self.std_name)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003206 setattr(sys, self.std_name, StdIOBuffer())
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003207 try:
3208 print_()
3209 parser_text = getattr(sys, self.std_name).getvalue()
3210 finally:
3211 setattr(sys, self.std_name, old_stream)
3212 self._test(tester, parser_text)
3213
3214 def test_print_file(self, tester):
3215 parser = self._get_parser(tester)
3216 print_ = getattr(parser, 'print_%s' % self.func_suffix)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003217 sfile = StdIOBuffer()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003218 print_(sfile)
3219 parser_text = sfile.getvalue()
3220 self._test(tester, parser_text)
3221
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003222 # add tests for {format,print}_{usage,help}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003223 for func_suffix, std_name in [('usage', 'stdout'),
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003224 ('help', 'stdout')]:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003225 AddTests(cls, func_suffix, std_name)
3226
3227bases = TestCase,
3228HelpTestCase = TestHelpFormattingMetaclass('HelpTestCase', bases, {})
3229
3230
3231class TestHelpBiggerOptionals(HelpTestCase):
3232 """Make sure that argument help aligns when options are longer"""
3233
3234 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003235 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003236 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003237 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003238 Sig('-x', action='store_true', help='X HELP'),
3239 Sig('--y', help='Y HELP'),
3240 Sig('foo', help='FOO HELP'),
3241 Sig('bar', help='BAR HELP'),
3242 ]
3243 argument_group_signatures = []
3244 usage = '''\
3245 usage: PROG [-h] [-v] [-x] [--y Y] foo bar
3246 '''
3247 help = usage + '''\
3248
3249 DESCRIPTION
3250
3251 positional arguments:
3252 foo FOO HELP
3253 bar BAR HELP
3254
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003255 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003256 -h, --help show this help message and exit
3257 -v, --version show program's version number and exit
3258 -x X HELP
3259 --y Y Y HELP
3260
3261 EPILOG
3262 '''
3263 version = '''\
3264 0.1
3265 '''
3266
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003267class TestShortColumns(HelpTestCase):
3268 '''Test extremely small number of columns.
3269
3270 TestCase prevents "COLUMNS" from being too small in the tests themselves,
Martin Panter2e4571a2015-11-14 01:07:43 +00003271 but we don't want any exceptions thrown in such cases. Only ugly representation.
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003272 '''
3273 def setUp(self):
Hai Shi46605972020-08-04 00:49:18 +08003274 env = os_helper.EnvironmentVarGuard()
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003275 env.set("COLUMNS", '15')
3276 self.addCleanup(env.__exit__)
3277
3278 parser_signature = TestHelpBiggerOptionals.parser_signature
3279 argument_signatures = TestHelpBiggerOptionals.argument_signatures
3280 argument_group_signatures = TestHelpBiggerOptionals.argument_group_signatures
3281 usage = '''\
3282 usage: PROG
3283 [-h]
3284 [-v]
3285 [-x]
3286 [--y Y]
3287 foo
3288 bar
3289 '''
3290 help = usage + '''\
3291
3292 DESCRIPTION
3293
3294 positional arguments:
3295 foo
3296 FOO HELP
3297 bar
3298 BAR HELP
3299
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003300 options:
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003301 -h, --help
3302 show this
3303 help
3304 message and
3305 exit
3306 -v, --version
3307 show
3308 program's
3309 version
3310 number and
3311 exit
3312 -x
3313 X HELP
3314 --y Y
3315 Y HELP
3316
3317 EPILOG
3318 '''
3319 version = TestHelpBiggerOptionals.version
3320
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003321
3322class TestHelpBiggerOptionalGroups(HelpTestCase):
3323 """Make sure that argument help aligns when options are longer"""
3324
3325 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003326 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003327 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003328 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003329 Sig('-x', action='store_true', help='X HELP'),
3330 Sig('--y', help='Y HELP'),
3331 Sig('foo', help='FOO HELP'),
3332 Sig('bar', help='BAR HELP'),
3333 ]
3334 argument_group_signatures = [
3335 (Sig('GROUP TITLE', description='GROUP DESCRIPTION'), [
3336 Sig('baz', help='BAZ HELP'),
3337 Sig('-z', nargs='+', help='Z HELP')]),
3338 ]
3339 usage = '''\
3340 usage: PROG [-h] [-v] [-x] [--y Y] [-z Z [Z ...]] foo bar baz
3341 '''
3342 help = usage + '''\
3343
3344 DESCRIPTION
3345
3346 positional arguments:
3347 foo FOO HELP
3348 bar BAR HELP
3349
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003350 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003351 -h, --help show this help message and exit
3352 -v, --version show program's version number and exit
3353 -x X HELP
3354 --y Y Y HELP
3355
3356 GROUP TITLE:
3357 GROUP DESCRIPTION
3358
3359 baz BAZ HELP
3360 -z Z [Z ...] Z HELP
3361
3362 EPILOG
3363 '''
3364 version = '''\
3365 0.1
3366 '''
3367
3368
3369class TestHelpBiggerPositionals(HelpTestCase):
3370 """Make sure that help aligns when arguments are longer"""
3371
3372 parser_signature = Sig(usage='USAGE', description='DESCRIPTION')
3373 argument_signatures = [
3374 Sig('-x', action='store_true', help='X HELP'),
3375 Sig('--y', help='Y HELP'),
3376 Sig('ekiekiekifekang', help='EKI HELP'),
3377 Sig('bar', help='BAR HELP'),
3378 ]
3379 argument_group_signatures = []
3380 usage = '''\
3381 usage: USAGE
3382 '''
3383 help = usage + '''\
3384
3385 DESCRIPTION
3386
3387 positional arguments:
3388 ekiekiekifekang EKI 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 -x X HELP
3394 --y Y Y HELP
3395 '''
3396
3397 version = ''
3398
3399
3400class TestHelpReformatting(HelpTestCase):
3401 """Make sure that text after short names starts on the first line"""
3402
3403 parser_signature = Sig(
3404 prog='PROG',
3405 description=' oddly formatted\n'
3406 'description\n'
3407 '\n'
3408 'that is so long that it should go onto multiple '
3409 'lines when wrapped')
3410 argument_signatures = [
3411 Sig('-x', metavar='XX', help='oddly\n'
3412 ' formatted -x help'),
3413 Sig('y', metavar='yyy', help='normal y help'),
3414 ]
3415 argument_group_signatures = [
3416 (Sig('title', description='\n'
3417 ' oddly formatted group\n'
3418 '\n'
3419 'description'),
3420 [Sig('-a', action='store_true',
3421 help=' oddly \n'
3422 'formatted -a help \n'
3423 ' again, so long that it should be wrapped over '
3424 'multiple lines')]),
3425 ]
3426 usage = '''\
3427 usage: PROG [-h] [-x XX] [-a] yyy
3428 '''
3429 help = usage + '''\
3430
3431 oddly formatted description that is so long that it should go onto \
3432multiple
3433 lines when wrapped
3434
3435 positional arguments:
3436 yyy normal y help
3437
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003438 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003439 -h, --help show this help message and exit
3440 -x XX oddly formatted -x help
3441
3442 title:
3443 oddly formatted group description
3444
3445 -a oddly formatted -a help again, so long that it should \
3446be wrapped
3447 over multiple lines
3448 '''
3449 version = ''
3450
3451
3452class TestHelpWrappingShortNames(HelpTestCase):
3453 """Make sure that text after short names starts on the first line"""
3454
3455 parser_signature = Sig(prog='PROG', description= 'D\nD' * 30)
3456 argument_signatures = [
3457 Sig('-x', metavar='XX', help='XHH HX' * 20),
3458 Sig('y', metavar='yyy', help='YH YH' * 20),
3459 ]
3460 argument_group_signatures = [
3461 (Sig('ALPHAS'), [
3462 Sig('-a', action='store_true', help='AHHH HHA' * 10)]),
3463 ]
3464 usage = '''\
3465 usage: PROG [-h] [-x XX] [-a] yyy
3466 '''
3467 help = usage + '''\
3468
3469 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3470DD DD DD
3471 DD DD DD DD D
3472
3473 positional arguments:
3474 yyy YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3475YHYH YHYH
3476 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3477
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003478 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003479 -h, --help show this help message and exit
3480 -x XX XHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH \
3481HXXHH HXXHH
3482 HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HX
3483
3484 ALPHAS:
3485 -a AHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH \
3486HHAAHHH
3487 HHAAHHH HHAAHHH HHA
3488 '''
3489 version = ''
3490
3491
3492class TestHelpWrappingLongNames(HelpTestCase):
3493 """Make sure that text after long names starts on the next line"""
3494
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003495 parser_signature = Sig(usage='USAGE', description= 'D D' * 30)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003496 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003497 Sig('-v', '--version', action='version', version='V V' * 30),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003498 Sig('-x', metavar='X' * 25, help='XH XH' * 20),
3499 Sig('y', metavar='y' * 25, help='YH YH' * 20),
3500 ]
3501 argument_group_signatures = [
3502 (Sig('ALPHAS'), [
3503 Sig('-a', metavar='A' * 25, help='AH AH' * 20),
3504 Sig('z', metavar='z' * 25, help='ZH ZH' * 20)]),
3505 ]
3506 usage = '''\
3507 usage: USAGE
3508 '''
3509 help = usage + '''\
3510
3511 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3512DD DD DD
3513 DD DD DD DD D
3514
3515 positional arguments:
3516 yyyyyyyyyyyyyyyyyyyyyyyyy
3517 YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3518YHYH YHYH
3519 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3520
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003521 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003522 -h, --help show this help message and exit
3523 -v, --version show program's version number and exit
3524 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3525 XH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH \
3526XHXH XHXH
3527 XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XH
3528
3529 ALPHAS:
3530 -a AAAAAAAAAAAAAAAAAAAAAAAAA
3531 AH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH \
3532AHAH AHAH
3533 AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AH
3534 zzzzzzzzzzzzzzzzzzzzzzzzz
3535 ZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH \
3536ZHZH ZHZH
3537 ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZH
3538 '''
3539 version = '''\
3540 V VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV \
3541VV VV VV
3542 VV VV VV VV V
3543 '''
3544
3545
3546class TestHelpUsage(HelpTestCase):
3547 """Test basic usage messages"""
3548
3549 parser_signature = Sig(prog='PROG')
3550 argument_signatures = [
3551 Sig('-w', nargs='+', help='w'),
3552 Sig('-x', nargs='*', help='x'),
3553 Sig('a', help='a'),
3554 Sig('b', help='b', nargs=2),
3555 Sig('c', help='c', nargs='?'),
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003556 Sig('--foo', help='Whether to foo', action=argparse.BooleanOptionalAction),
3557 Sig('--bar', help='Whether to bar', default=True,
3558 action=argparse.BooleanOptionalAction),
3559 Sig('-f', '--foobar', '--barfoo', action=argparse.BooleanOptionalAction),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003560 ]
3561 argument_group_signatures = [
3562 (Sig('group'), [
3563 Sig('-y', nargs='?', help='y'),
3564 Sig('-z', nargs=3, help='z'),
3565 Sig('d', help='d', nargs='*'),
3566 Sig('e', help='e', nargs='+'),
3567 ])
3568 ]
3569 usage = '''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08003570 usage: PROG [-h] [-w W [W ...]] [-x [X ...]] [--foo | --no-foo]
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003571 [--bar | --no-bar]
3572 [-f | --foobar | --no-foobar | --barfoo | --no-barfoo] [-y [Y]]
3573 [-z Z Z Z]
Brandt Buchera0ed99b2019-11-11 12:47:48 -08003574 a b b [c] [d ...] e [e ...]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003575 '''
3576 help = usage + '''\
3577
3578 positional arguments:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003579 a a
3580 b b
3581 c c
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003582
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003583 options:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003584 -h, --help show this help message and exit
3585 -w W [W ...] w
Brandt Buchera0ed99b2019-11-11 12:47:48 -08003586 -x [X ...] x
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003587 --foo, --no-foo Whether to foo
3588 --bar, --no-bar Whether to bar (default: True)
3589 -f, --foobar, --no-foobar, --barfoo, --no-barfoo
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003590
3591 group:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003592 -y [Y] y
3593 -z Z Z Z z
3594 d d
3595 e e
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003596 '''
3597 version = ''
3598
3599
3600class TestHelpOnlyUserGroups(HelpTestCase):
3601 """Test basic usage messages"""
3602
3603 parser_signature = Sig(prog='PROG', add_help=False)
3604 argument_signatures = []
3605 argument_group_signatures = [
3606 (Sig('xxxx'), [
3607 Sig('-x', help='x'),
3608 Sig('a', help='a'),
3609 ]),
3610 (Sig('yyyy'), [
3611 Sig('b', help='b'),
3612 Sig('-y', help='y'),
3613 ]),
3614 ]
3615 usage = '''\
3616 usage: PROG [-x X] [-y Y] a b
3617 '''
3618 help = usage + '''\
3619
3620 xxxx:
3621 -x X x
3622 a a
3623
3624 yyyy:
3625 b b
3626 -y Y y
3627 '''
3628 version = ''
3629
3630
3631class TestHelpUsageLongProg(HelpTestCase):
3632 """Test usage messages where the prog is long"""
3633
3634 parser_signature = Sig(prog='P' * 60)
3635 argument_signatures = [
3636 Sig('-w', metavar='W'),
3637 Sig('-x', metavar='X'),
3638 Sig('a'),
3639 Sig('b'),
3640 ]
3641 argument_group_signatures = []
3642 usage = '''\
3643 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3644 [-h] [-w W] [-x X] a b
3645 '''
3646 help = usage + '''\
3647
3648 positional arguments:
3649 a
3650 b
3651
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003652 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003653 -h, --help show this help message and exit
3654 -w W
3655 -x X
3656 '''
3657 version = ''
3658
3659
3660class TestHelpUsageLongProgOptionsWrap(HelpTestCase):
3661 """Test usage messages where the prog is long and the optionals wrap"""
3662
3663 parser_signature = Sig(prog='P' * 60)
3664 argument_signatures = [
3665 Sig('-w', metavar='W' * 25),
3666 Sig('-x', metavar='X' * 25),
3667 Sig('-y', metavar='Y' * 25),
3668 Sig('-z', metavar='Z' * 25),
3669 Sig('a'),
3670 Sig('b'),
3671 ]
3672 argument_group_signatures = []
3673 usage = '''\
3674 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3675 [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3676[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3677 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3678 a b
3679 '''
3680 help = usage + '''\
3681
3682 positional arguments:
3683 a
3684 b
3685
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003686 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003687 -h, --help show this help message and exit
3688 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3689 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3690 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3691 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3692 '''
3693 version = ''
3694
3695
3696class TestHelpUsageLongProgPositionalsWrap(HelpTestCase):
3697 """Test usage messages where the prog is long and the positionals wrap"""
3698
3699 parser_signature = Sig(prog='P' * 60, add_help=False)
3700 argument_signatures = [
3701 Sig('a' * 25),
3702 Sig('b' * 25),
3703 Sig('c' * 25),
3704 ]
3705 argument_group_signatures = []
3706 usage = '''\
3707 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3708 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3709 ccccccccccccccccccccccccc
3710 '''
3711 help = usage + '''\
3712
3713 positional arguments:
3714 aaaaaaaaaaaaaaaaaaaaaaaaa
3715 bbbbbbbbbbbbbbbbbbbbbbbbb
3716 ccccccccccccccccccccccccc
3717 '''
3718 version = ''
3719
3720
3721class TestHelpUsageOptionalsWrap(HelpTestCase):
3722 """Test usage messages where the optionals wrap"""
3723
3724 parser_signature = Sig(prog='PROG')
3725 argument_signatures = [
3726 Sig('-w', metavar='W' * 25),
3727 Sig('-x', metavar='X' * 25),
3728 Sig('-y', metavar='Y' * 25),
3729 Sig('-z', metavar='Z' * 25),
3730 Sig('a'),
3731 Sig('b'),
3732 Sig('c'),
3733 ]
3734 argument_group_signatures = []
3735 usage = '''\
3736 usage: PROG [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3737[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3738 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] \
3739[-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3740 a b c
3741 '''
3742 help = usage + '''\
3743
3744 positional arguments:
3745 a
3746 b
3747 c
3748
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003749 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003750 -h, --help show this help message and exit
3751 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3752 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3753 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3754 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3755 '''
3756 version = ''
3757
3758
3759class TestHelpUsagePositionalsWrap(HelpTestCase):
3760 """Test usage messages where the positionals wrap"""
3761
3762 parser_signature = Sig(prog='PROG')
3763 argument_signatures = [
3764 Sig('-x'),
3765 Sig('-y'),
3766 Sig('-z'),
3767 Sig('a' * 25),
3768 Sig('b' * 25),
3769 Sig('c' * 25),
3770 ]
3771 argument_group_signatures = []
3772 usage = '''\
3773 usage: PROG [-h] [-x X] [-y Y] [-z Z]
3774 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3775 ccccccccccccccccccccccccc
3776 '''
3777 help = usage + '''\
3778
3779 positional arguments:
3780 aaaaaaaaaaaaaaaaaaaaaaaaa
3781 bbbbbbbbbbbbbbbbbbbbbbbbb
3782 ccccccccccccccccccccccccc
3783
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003784 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003785 -h, --help show this help message and exit
3786 -x X
3787 -y Y
3788 -z Z
3789 '''
3790 version = ''
3791
3792
3793class TestHelpUsageOptionalsPositionalsWrap(HelpTestCase):
3794 """Test usage messages where the optionals and positionals wrap"""
3795
3796 parser_signature = Sig(prog='PROG')
3797 argument_signatures = [
3798 Sig('-x', metavar='X' * 25),
3799 Sig('-y', metavar='Y' * 25),
3800 Sig('-z', metavar='Z' * 25),
3801 Sig('a' * 25),
3802 Sig('b' * 25),
3803 Sig('c' * 25),
3804 ]
3805 argument_group_signatures = []
3806 usage = '''\
3807 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3808[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3809 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3810 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3811 ccccccccccccccccccccccccc
3812 '''
3813 help = usage + '''\
3814
3815 positional arguments:
3816 aaaaaaaaaaaaaaaaaaaaaaaaa
3817 bbbbbbbbbbbbbbbbbbbbbbbbb
3818 ccccccccccccccccccccccccc
3819
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003820 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003821 -h, --help show this help message and exit
3822 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3823 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3824 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3825 '''
3826 version = ''
3827
3828
3829class TestHelpUsageOptionalsOnlyWrap(HelpTestCase):
3830 """Test usage messages where there are only optionals and they wrap"""
3831
3832 parser_signature = Sig(prog='PROG')
3833 argument_signatures = [
3834 Sig('-x', metavar='X' * 25),
3835 Sig('-y', metavar='Y' * 25),
3836 Sig('-z', metavar='Z' * 25),
3837 ]
3838 argument_group_signatures = []
3839 usage = '''\
3840 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3841[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3842 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3843 '''
3844 help = usage + '''\
3845
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003846 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003847 -h, --help show this help message and exit
3848 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3849 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3850 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3851 '''
3852 version = ''
3853
3854
3855class TestHelpUsagePositionalsOnlyWrap(HelpTestCase):
3856 """Test usage messages where there are only positionals and they wrap"""
3857
3858 parser_signature = Sig(prog='PROG', add_help=False)
3859 argument_signatures = [
3860 Sig('a' * 25),
3861 Sig('b' * 25),
3862 Sig('c' * 25),
3863 ]
3864 argument_group_signatures = []
3865 usage = '''\
3866 usage: PROG aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3867 ccccccccccccccccccccccccc
3868 '''
3869 help = usage + '''\
3870
3871 positional arguments:
3872 aaaaaaaaaaaaaaaaaaaaaaaaa
3873 bbbbbbbbbbbbbbbbbbbbbbbbb
3874 ccccccccccccccccccccccccc
3875 '''
3876 version = ''
3877
3878
3879class TestHelpVariableExpansion(HelpTestCase):
3880 """Test that variables are expanded properly in help messages"""
3881
3882 parser_signature = Sig(prog='PROG')
3883 argument_signatures = [
3884 Sig('-x', type=int,
3885 help='x %(prog)s %(default)s %(type)s %%'),
3886 Sig('-y', action='store_const', default=42, const='XXX',
3887 help='y %(prog)s %(default)s %(const)s'),
3888 Sig('--foo', choices='abc',
3889 help='foo %(prog)s %(default)s %(choices)s'),
3890 Sig('--bar', default='baz', choices=[1, 2], metavar='BBB',
3891 help='bar %(prog)s %(default)s %(dest)s'),
3892 Sig('spam', help='spam %(prog)s %(default)s'),
3893 Sig('badger', default=0.5, help='badger %(prog)s %(default)s'),
3894 ]
3895 argument_group_signatures = [
3896 (Sig('group'), [
3897 Sig('-a', help='a %(prog)s %(default)s'),
3898 Sig('-b', default=-1, help='b %(prog)s %(default)s'),
3899 ])
3900 ]
3901 usage = ('''\
3902 usage: PROG [-h] [-x X] [-y] [--foo {a,b,c}] [--bar BBB] [-a A] [-b B]
3903 spam badger
3904 ''')
3905 help = usage + '''\
3906
3907 positional arguments:
3908 spam spam PROG None
3909 badger badger PROG 0.5
3910
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003911 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003912 -h, --help show this help message and exit
3913 -x X x PROG None int %
3914 -y y PROG 42 XXX
3915 --foo {a,b,c} foo PROG None a, b, c
3916 --bar BBB bar PROG baz bar
3917
3918 group:
3919 -a A a PROG None
3920 -b B b PROG -1
3921 '''
3922 version = ''
3923
3924
3925class TestHelpVariableExpansionUsageSupplied(HelpTestCase):
3926 """Test that variables are expanded properly when usage= is present"""
3927
3928 parser_signature = Sig(prog='PROG', usage='%(prog)s FOO')
3929 argument_signatures = []
3930 argument_group_signatures = []
3931 usage = ('''\
3932 usage: PROG FOO
3933 ''')
3934 help = usage + '''\
3935
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003936 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003937 -h, --help show this help message and exit
3938 '''
3939 version = ''
3940
3941
3942class TestHelpVariableExpansionNoArguments(HelpTestCase):
3943 """Test that variables are expanded properly with no arguments"""
3944
3945 parser_signature = Sig(prog='PROG', add_help=False)
3946 argument_signatures = []
3947 argument_group_signatures = []
3948 usage = ('''\
3949 usage: PROG
3950 ''')
3951 help = usage
3952 version = ''
3953
3954
3955class TestHelpSuppressUsage(HelpTestCase):
3956 """Test that items can be suppressed in usage messages"""
3957
3958 parser_signature = Sig(prog='PROG', usage=argparse.SUPPRESS)
3959 argument_signatures = [
3960 Sig('--foo', help='foo help'),
3961 Sig('spam', help='spam help'),
3962 ]
3963 argument_group_signatures = []
3964 help = '''\
3965 positional arguments:
3966 spam spam help
3967
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003968 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003969 -h, --help show this help message and exit
3970 --foo FOO foo help
3971 '''
3972 usage = ''
3973 version = ''
3974
3975
3976class TestHelpSuppressOptional(HelpTestCase):
3977 """Test that optional arguments can be suppressed in help messages"""
3978
3979 parser_signature = Sig(prog='PROG', add_help=False)
3980 argument_signatures = [
3981 Sig('--foo', help=argparse.SUPPRESS),
3982 Sig('spam', help='spam help'),
3983 ]
3984 argument_group_signatures = []
3985 usage = '''\
3986 usage: PROG spam
3987 '''
3988 help = usage + '''\
3989
3990 positional arguments:
3991 spam spam help
3992 '''
3993 version = ''
3994
3995
3996class TestHelpSuppressOptionalGroup(HelpTestCase):
3997 """Test that optional groups can be suppressed in help messages"""
3998
3999 parser_signature = Sig(prog='PROG')
4000 argument_signatures = [
4001 Sig('--foo', help='foo help'),
4002 Sig('spam', help='spam help'),
4003 ]
4004 argument_group_signatures = [
4005 (Sig('group'), [Sig('--bar', help=argparse.SUPPRESS)]),
4006 ]
4007 usage = '''\
4008 usage: PROG [-h] [--foo FOO] spam
4009 '''
4010 help = usage + '''\
4011
4012 positional arguments:
4013 spam spam help
4014
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004015 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004016 -h, --help show this help message and exit
4017 --foo FOO foo help
4018 '''
4019 version = ''
4020
4021
4022class TestHelpSuppressPositional(HelpTestCase):
4023 """Test that positional arguments can be suppressed in help messages"""
4024
4025 parser_signature = Sig(prog='PROG')
4026 argument_signatures = [
4027 Sig('--foo', help='foo help'),
4028 Sig('spam', help=argparse.SUPPRESS),
4029 ]
4030 argument_group_signatures = []
4031 usage = '''\
4032 usage: PROG [-h] [--foo FOO]
4033 '''
4034 help = usage + '''\
4035
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004036 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004037 -h, --help show this help message and exit
4038 --foo FOO foo help
4039 '''
4040 version = ''
4041
4042
4043class TestHelpRequiredOptional(HelpTestCase):
4044 """Test that required options don't look optional"""
4045
4046 parser_signature = Sig(prog='PROG')
4047 argument_signatures = [
4048 Sig('--foo', required=True, help='foo help'),
4049 ]
4050 argument_group_signatures = []
4051 usage = '''\
4052 usage: PROG [-h] --foo FOO
4053 '''
4054 help = usage + '''\
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 TestHelpAlternatePrefixChars(HelpTestCase):
4064 """Test that options display with different prefix characters"""
4065
4066 parser_signature = Sig(prog='PROG', prefix_chars='^;', add_help=False)
4067 argument_signatures = [
4068 Sig('^^foo', action='store_true', help='foo help'),
4069 Sig(';b', ';;bar', help='bar help'),
4070 ]
4071 argument_group_signatures = []
4072 usage = '''\
4073 usage: PROG [^^foo] [;b BAR]
4074 '''
4075 help = usage + '''\
4076
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004077 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004078 ^^foo foo help
4079 ;b BAR, ;;bar BAR bar help
4080 '''
4081 version = ''
4082
4083
4084class TestHelpNoHelpOptional(HelpTestCase):
4085 """Test that the --help argument can be suppressed help messages"""
4086
4087 parser_signature = Sig(prog='PROG', add_help=False)
4088 argument_signatures = [
4089 Sig('--foo', help='foo help'),
4090 Sig('spam', help='spam help'),
4091 ]
4092 argument_group_signatures = []
4093 usage = '''\
4094 usage: PROG [--foo FOO] spam
4095 '''
4096 help = usage + '''\
4097
4098 positional arguments:
4099 spam spam help
4100
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004101 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004102 --foo FOO foo help
4103 '''
4104 version = ''
4105
4106
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004107class TestHelpNone(HelpTestCase):
4108 """Test that no errors occur if no help is specified"""
4109
4110 parser_signature = Sig(prog='PROG')
4111 argument_signatures = [
4112 Sig('--foo'),
4113 Sig('spam'),
4114 ]
4115 argument_group_signatures = []
4116 usage = '''\
4117 usage: PROG [-h] [--foo FOO] spam
4118 '''
4119 help = usage + '''\
4120
4121 positional arguments:
4122 spam
4123
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004124 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004125 -h, --help show this help message and exit
4126 --foo FOO
4127 '''
4128 version = ''
4129
4130
4131class TestHelpTupleMetavar(HelpTestCase):
4132 """Test specifying metavar as a tuple"""
4133
4134 parser_signature = Sig(prog='PROG')
4135 argument_signatures = [
4136 Sig('-w', help='w', nargs='+', metavar=('W1', 'W2')),
4137 Sig('-x', help='x', nargs='*', metavar=('X1', 'X2')),
4138 Sig('-y', help='y', nargs=3, metavar=('Y1', 'Y2', 'Y3')),
4139 Sig('-z', help='z', nargs='?', metavar=('Z1', )),
4140 ]
4141 argument_group_signatures = []
4142 usage = '''\
4143 usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] \
4144[-z [Z1]]
4145 '''
4146 help = usage + '''\
4147
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004148 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004149 -h, --help show this help message and exit
4150 -w W1 [W2 ...] w
4151 -x [X1 [X2 ...]] x
4152 -y Y1 Y2 Y3 y
4153 -z [Z1] z
4154 '''
4155 version = ''
4156
4157
4158class TestHelpRawText(HelpTestCase):
4159 """Test the RawTextHelpFormatter"""
4160
4161 parser_signature = Sig(
4162 prog='PROG', formatter_class=argparse.RawTextHelpFormatter,
4163 description='Keep the formatting\n'
4164 ' exactly as it is written\n'
4165 '\n'
4166 'here\n')
4167
4168 argument_signatures = [
4169 Sig('--foo', help=' foo help should also\n'
4170 'appear as given here'),
4171 Sig('spam', help='spam help'),
4172 ]
4173 argument_group_signatures = [
4174 (Sig('title', description=' This text\n'
4175 ' should be indented\n'
4176 ' exactly like it is here\n'),
4177 [Sig('--bar', help='bar help')]),
4178 ]
4179 usage = '''\
4180 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
4181 '''
4182 help = usage + '''\
4183
4184 Keep the formatting
4185 exactly as it is written
4186
4187 here
4188
4189 positional arguments:
4190 spam spam help
4191
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004192 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004193 -h, --help show this help message and exit
4194 --foo FOO foo help should also
4195 appear as given here
4196
4197 title:
4198 This text
4199 should be indented
4200 exactly like it is here
4201
4202 --bar BAR bar help
4203 '''
4204 version = ''
4205
4206
4207class TestHelpRawDescription(HelpTestCase):
4208 """Test the RawTextHelpFormatter"""
4209
4210 parser_signature = Sig(
4211 prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter,
4212 description='Keep the formatting\n'
4213 ' exactly as it is written\n'
4214 '\n'
4215 'here\n')
4216
4217 argument_signatures = [
4218 Sig('--foo', help=' foo help should not\n'
4219 ' retain this odd formatting'),
4220 Sig('spam', help='spam help'),
4221 ]
4222 argument_group_signatures = [
4223 (Sig('title', description=' This text\n'
4224 ' should be indented\n'
4225 ' exactly like it is here\n'),
4226 [Sig('--bar', help='bar help')]),
4227 ]
4228 usage = '''\
4229 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
4230 '''
4231 help = usage + '''\
4232
4233 Keep the formatting
4234 exactly as it is written
4235
4236 here
4237
4238 positional arguments:
4239 spam spam help
4240
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004241 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004242 -h, --help show this help message and exit
4243 --foo FOO foo help should not retain this odd formatting
4244
4245 title:
4246 This text
4247 should be indented
4248 exactly like it is here
4249
4250 --bar BAR bar help
4251 '''
4252 version = ''
4253
4254
4255class TestHelpArgumentDefaults(HelpTestCase):
4256 """Test the ArgumentDefaultsHelpFormatter"""
4257
4258 parser_signature = Sig(
4259 prog='PROG', formatter_class=argparse.ArgumentDefaultsHelpFormatter,
4260 description='description')
4261
4262 argument_signatures = [
4263 Sig('--foo', help='foo help - oh and by the way, %(default)s'),
4264 Sig('--bar', action='store_true', help='bar help'),
4265 Sig('spam', help='spam help'),
4266 Sig('badger', nargs='?', default='wooden', help='badger help'),
4267 ]
4268 argument_group_signatures = [
4269 (Sig('title', description='description'),
4270 [Sig('--baz', type=int, default=42, help='baz help')]),
4271 ]
4272 usage = '''\
4273 usage: PROG [-h] [--foo FOO] [--bar] [--baz BAZ] spam [badger]
4274 '''
4275 help = usage + '''\
4276
4277 description
4278
4279 positional arguments:
4280 spam spam help
4281 badger badger help (default: wooden)
4282
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004283 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004284 -h, --help show this help message and exit
4285 --foo FOO foo help - oh and by the way, None
4286 --bar bar help (default: False)
4287
4288 title:
4289 description
4290
4291 --baz BAZ baz help (default: 42)
4292 '''
4293 version = ''
4294
Steven Bethard50fe5932010-05-24 03:47:38 +00004295class TestHelpVersionAction(HelpTestCase):
4296 """Test the default help for the version action"""
4297
4298 parser_signature = Sig(prog='PROG', description='description')
4299 argument_signatures = [Sig('-V', '--version', action='version', version='3.6')]
4300 argument_group_signatures = []
4301 usage = '''\
4302 usage: PROG [-h] [-V]
4303 '''
4304 help = usage + '''\
4305
4306 description
4307
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004308 options:
Steven Bethard50fe5932010-05-24 03:47:38 +00004309 -h, --help show this help message and exit
4310 -V, --version show program's version number and exit
4311 '''
4312 version = ''
4313
Berker Peksagecb75e22015-04-10 16:11:12 +03004314
4315class TestHelpVersionActionSuppress(HelpTestCase):
4316 """Test that the --version argument can be suppressed in help messages"""
4317
4318 parser_signature = Sig(prog='PROG')
4319 argument_signatures = [
4320 Sig('-v', '--version', action='version', version='1.0',
4321 help=argparse.SUPPRESS),
4322 Sig('--foo', help='foo help'),
4323 Sig('spam', help='spam help'),
4324 ]
4325 argument_group_signatures = []
4326 usage = '''\
4327 usage: PROG [-h] [--foo FOO] spam
4328 '''
4329 help = usage + '''\
4330
4331 positional arguments:
4332 spam spam help
4333
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004334 options:
Berker Peksagecb75e22015-04-10 16:11:12 +03004335 -h, --help show this help message and exit
4336 --foo FOO foo help
4337 '''
4338
4339
Steven Bethard8a6a1982011-03-27 13:53:53 +02004340class TestHelpSubparsersOrdering(HelpTestCase):
4341 """Test ordering of subcommands in help matches the code"""
4342 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004343 description='display some subcommands')
4344 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004345
4346 subparsers_signatures = [Sig(name=name)
4347 for name in ('a', 'b', 'c', 'd', 'e')]
4348
4349 usage = '''\
4350 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4351 '''
4352
4353 help = usage + '''\
4354
4355 display some subcommands
4356
4357 positional arguments:
4358 {a,b,c,d,e}
4359
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004360 options:
Steven Bethard8a6a1982011-03-27 13:53:53 +02004361 -h, --help show this help message and exit
4362 -v, --version show program's version number and exit
4363 '''
4364
4365 version = '''\
4366 0.1
4367 '''
4368
4369class TestHelpSubparsersWithHelpOrdering(HelpTestCase):
4370 """Test ordering of subcommands in help matches the code"""
4371 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004372 description='display some subcommands')
4373 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004374
4375 subcommand_data = (('a', 'a subcommand help'),
4376 ('b', 'b subcommand help'),
4377 ('c', 'c subcommand help'),
4378 ('d', 'd subcommand help'),
4379 ('e', 'e subcommand help'),
4380 )
4381
4382 subparsers_signatures = [Sig(name=name, help=help)
4383 for name, help in subcommand_data]
4384
4385 usage = '''\
4386 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4387 '''
4388
4389 help = usage + '''\
4390
4391 display some subcommands
4392
4393 positional arguments:
4394 {a,b,c,d,e}
4395 a a subcommand help
4396 b b subcommand help
4397 c c subcommand help
4398 d d subcommand help
4399 e e subcommand help
4400
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004401 options:
Steven Bethard8a6a1982011-03-27 13:53:53 +02004402 -h, --help show this help message and exit
4403 -v, --version show program's version number and exit
4404 '''
4405
4406 version = '''\
4407 0.1
4408 '''
4409
4410
Steven Bethard0331e902011-03-26 14:48:04 +01004411
4412class TestHelpMetavarTypeFormatter(HelpTestCase):
Steven Bethard0331e902011-03-26 14:48:04 +01004413
4414 def custom_type(string):
4415 return string
4416
4417 parser_signature = Sig(prog='PROG', description='description',
4418 formatter_class=argparse.MetavarTypeHelpFormatter)
4419 argument_signatures = [Sig('a', type=int),
4420 Sig('-b', type=custom_type),
4421 Sig('-c', type=float, metavar='SOME FLOAT')]
4422 argument_group_signatures = []
4423 usage = '''\
4424 usage: PROG [-h] [-b custom_type] [-c SOME FLOAT] int
4425 '''
4426 help = usage + '''\
4427
4428 description
4429
4430 positional arguments:
4431 int
4432
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004433 options:
Steven Bethard0331e902011-03-26 14:48:04 +01004434 -h, --help show this help message and exit
4435 -b custom_type
4436 -c SOME FLOAT
4437 '''
4438 version = ''
4439
4440
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004441# =====================================
4442# Optional/Positional constructor tests
4443# =====================================
4444
4445class TestInvalidArgumentConstructors(TestCase):
4446 """Test a bunch of invalid Argument constructors"""
4447
4448 def assertTypeError(self, *args, **kwargs):
4449 parser = argparse.ArgumentParser()
4450 self.assertRaises(TypeError, parser.add_argument,
4451 *args, **kwargs)
4452
4453 def assertValueError(self, *args, **kwargs):
4454 parser = argparse.ArgumentParser()
4455 self.assertRaises(ValueError, parser.add_argument,
4456 *args, **kwargs)
4457
4458 def test_invalid_keyword_arguments(self):
4459 self.assertTypeError('-x', bar=None)
4460 self.assertTypeError('-y', callback='foo')
4461 self.assertTypeError('-y', callback_args=())
4462 self.assertTypeError('-y', callback_kwargs={})
4463
4464 def test_missing_destination(self):
4465 self.assertTypeError()
4466 for action in ['append', 'store']:
4467 self.assertTypeError(action=action)
4468
4469 def test_invalid_option_strings(self):
4470 self.assertValueError('--')
4471 self.assertValueError('---')
4472
4473 def test_invalid_type(self):
4474 self.assertValueError('--foo', type='int')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004475 self.assertValueError('--foo', type=(int, float))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004476
4477 def test_invalid_action(self):
4478 self.assertValueError('-x', action='foo')
4479 self.assertValueError('foo', action='baz')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004480 self.assertValueError('--foo', action=('store', 'append'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004481 parser = argparse.ArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004482 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004483 parser.add_argument("--foo", action="store-true")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004484 self.assertIn('unknown action', str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004485
4486 def test_multiple_dest(self):
4487 parser = argparse.ArgumentParser()
4488 parser.add_argument(dest='foo')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004489 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004490 parser.add_argument('bar', dest='baz')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004491 self.assertIn('dest supplied twice for positional argument',
4492 str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004493
4494 def test_no_argument_actions(self):
4495 for action in ['store_const', 'store_true', 'store_false',
4496 'append_const', 'count']:
4497 for attrs in [dict(type=int), dict(nargs='+'),
4498 dict(choices='ab')]:
4499 self.assertTypeError('-x', action=action, **attrs)
4500
4501 def test_no_argument_no_const_actions(self):
4502 # options with zero arguments
4503 for action in ['store_true', 'store_false', 'count']:
4504
4505 # const is always disallowed
4506 self.assertTypeError('-x', const='foo', action=action)
4507
4508 # nargs is always disallowed
4509 self.assertTypeError('-x', nargs='*', action=action)
4510
4511 def test_more_than_one_argument_actions(self):
4512 for action in ['store', 'append']:
4513
4514 # nargs=0 is disallowed
4515 self.assertValueError('-x', nargs=0, action=action)
4516 self.assertValueError('spam', nargs=0, action=action)
4517
4518 # const is disallowed with non-optional arguments
4519 for nargs in [1, '*', '+']:
4520 self.assertValueError('-x', const='foo',
4521 nargs=nargs, action=action)
4522 self.assertValueError('spam', const='foo',
4523 nargs=nargs, action=action)
4524
4525 def test_required_const_actions(self):
4526 for action in ['store_const', 'append_const']:
4527
4528 # nargs is always disallowed
4529 self.assertTypeError('-x', nargs='+', action=action)
4530
4531 def test_parsers_action_missing_params(self):
4532 self.assertTypeError('command', action='parsers')
4533 self.assertTypeError('command', action='parsers', prog='PROG')
4534 self.assertTypeError('command', action='parsers',
4535 parser_class=argparse.ArgumentParser)
4536
4537 def test_required_positional(self):
4538 self.assertTypeError('foo', required=True)
4539
4540 def test_user_defined_action(self):
4541
4542 class Success(Exception):
4543 pass
4544
4545 class Action(object):
4546
4547 def __init__(self,
4548 option_strings,
4549 dest,
4550 const,
4551 default,
4552 required=False):
4553 if dest == 'spam':
4554 if const is Success:
4555 if default is Success:
4556 raise Success()
4557
4558 def __call__(self, *args, **kwargs):
4559 pass
4560
4561 parser = argparse.ArgumentParser()
4562 self.assertRaises(Success, parser.add_argument, '--spam',
4563 action=Action, default=Success, const=Success)
4564 self.assertRaises(Success, parser.add_argument, 'spam',
4565 action=Action, default=Success, const=Success)
4566
4567# ================================
4568# Actions returned by add_argument
4569# ================================
4570
4571class TestActionsReturned(TestCase):
4572
4573 def test_dest(self):
4574 parser = argparse.ArgumentParser()
4575 action = parser.add_argument('--foo')
4576 self.assertEqual(action.dest, 'foo')
4577 action = parser.add_argument('-b', '--bar')
4578 self.assertEqual(action.dest, 'bar')
4579 action = parser.add_argument('-x', '-y')
4580 self.assertEqual(action.dest, 'x')
4581
4582 def test_misc(self):
4583 parser = argparse.ArgumentParser()
4584 action = parser.add_argument('--foo', nargs='?', const=42,
4585 default=84, type=int, choices=[1, 2],
4586 help='FOO', metavar='BAR', dest='baz')
4587 self.assertEqual(action.nargs, '?')
4588 self.assertEqual(action.const, 42)
4589 self.assertEqual(action.default, 84)
4590 self.assertEqual(action.type, int)
4591 self.assertEqual(action.choices, [1, 2])
4592 self.assertEqual(action.help, 'FOO')
4593 self.assertEqual(action.metavar, 'BAR')
4594 self.assertEqual(action.dest, 'baz')
4595
4596
4597# ================================
4598# Argument conflict handling tests
4599# ================================
4600
4601class TestConflictHandling(TestCase):
4602
4603 def test_bad_type(self):
4604 self.assertRaises(ValueError, argparse.ArgumentParser,
4605 conflict_handler='foo')
4606
4607 def test_conflict_error(self):
4608 parser = argparse.ArgumentParser()
4609 parser.add_argument('-x')
4610 self.assertRaises(argparse.ArgumentError,
4611 parser.add_argument, '-x')
4612 parser.add_argument('--spam')
4613 self.assertRaises(argparse.ArgumentError,
4614 parser.add_argument, '--spam')
4615
4616 def test_resolve_error(self):
4617 get_parser = argparse.ArgumentParser
4618 parser = get_parser(prog='PROG', conflict_handler='resolve')
4619
4620 parser.add_argument('-x', help='OLD X')
4621 parser.add_argument('-x', help='NEW X')
4622 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4623 usage: PROG [-h] [-x X]
4624
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004625 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004626 -h, --help show this help message and exit
4627 -x X NEW X
4628 '''))
4629
4630 parser.add_argument('--spam', metavar='OLD_SPAM')
4631 parser.add_argument('--spam', metavar='NEW_SPAM')
4632 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4633 usage: PROG [-h] [-x X] [--spam NEW_SPAM]
4634
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004635 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004636 -h, --help show this help message and exit
4637 -x X NEW X
4638 --spam NEW_SPAM
4639 '''))
4640
4641
4642# =============================
4643# Help and Version option tests
4644# =============================
4645
4646class TestOptionalsHelpVersionActions(TestCase):
4647 """Test the help and version actions"""
4648
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004649 def assertPrintHelpExit(self, parser, args_str):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004650 with self.assertRaises(ArgumentParserError) as cm:
4651 parser.parse_args(args_str.split())
4652 self.assertEqual(parser.format_help(), cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004653
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004654 def assertArgumentParserError(self, parser, *args):
4655 self.assertRaises(ArgumentParserError, parser.parse_args, args)
4656
4657 def test_version(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004658 parser = ErrorRaisingArgumentParser()
4659 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004660 self.assertPrintHelpExit(parser, '-h')
4661 self.assertPrintHelpExit(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004662 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004663
4664 def test_version_format(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004665 parser = ErrorRaisingArgumentParser(prog='PPP')
4666 parser.add_argument('-v', '--version', action='version', version='%(prog)s 3.5')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004667 with self.assertRaises(ArgumentParserError) as cm:
4668 parser.parse_args(['-v'])
4669 self.assertEqual('PPP 3.5\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004670
4671 def test_version_no_help(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004672 parser = ErrorRaisingArgumentParser(add_help=False)
4673 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004674 self.assertArgumentParserError(parser, '-h')
4675 self.assertArgumentParserError(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004676 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004677
4678 def test_version_action(self):
4679 parser = ErrorRaisingArgumentParser(prog='XXX')
4680 parser.add_argument('-V', action='version', version='%(prog)s 3.7')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004681 with self.assertRaises(ArgumentParserError) as cm:
4682 parser.parse_args(['-V'])
4683 self.assertEqual('XXX 3.7\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004684
4685 def test_no_help(self):
4686 parser = ErrorRaisingArgumentParser(add_help=False)
4687 self.assertArgumentParserError(parser, '-h')
4688 self.assertArgumentParserError(parser, '--help')
4689 self.assertArgumentParserError(parser, '-v')
4690 self.assertArgumentParserError(parser, '--version')
4691
4692 def test_alternate_help_version(self):
4693 parser = ErrorRaisingArgumentParser()
4694 parser.add_argument('-x', action='help')
4695 parser.add_argument('-y', action='version')
4696 self.assertPrintHelpExit(parser, '-x')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004697 self.assertArgumentParserError(parser, '-v')
4698 self.assertArgumentParserError(parser, '--version')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004699 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004700
4701 def test_help_version_extra_arguments(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004702 parser = ErrorRaisingArgumentParser()
4703 parser.add_argument('--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004704 parser.add_argument('-x', action='store_true')
4705 parser.add_argument('y')
4706
4707 # try all combinations of valid prefixes and suffixes
4708 valid_prefixes = ['', '-x', 'foo', '-x bar', 'baz -x']
4709 valid_suffixes = valid_prefixes + ['--bad-option', 'foo bar baz']
4710 for prefix in valid_prefixes:
4711 for suffix in valid_suffixes:
4712 format = '%s %%s %s' % (prefix, suffix)
4713 self.assertPrintHelpExit(parser, format % '-h')
4714 self.assertPrintHelpExit(parser, format % '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004715 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004716
4717
4718# ======================
4719# str() and repr() tests
4720# ======================
4721
4722class TestStrings(TestCase):
4723 """Test str() and repr() on Optionals and Positionals"""
4724
4725 def assertStringEqual(self, obj, result_string):
4726 for func in [str, repr]:
4727 self.assertEqual(func(obj), result_string)
4728
4729 def test_optional(self):
4730 option = argparse.Action(
4731 option_strings=['--foo', '-a', '-b'],
4732 dest='b',
4733 type='int',
4734 nargs='+',
4735 default=42,
4736 choices=[1, 2, 3],
4737 help='HELP',
4738 metavar='METAVAR')
4739 string = (
4740 "Action(option_strings=['--foo', '-a', '-b'], dest='b', "
4741 "nargs='+', const=None, default=42, type='int', "
4742 "choices=[1, 2, 3], help='HELP', metavar='METAVAR')")
4743 self.assertStringEqual(option, string)
4744
4745 def test_argument(self):
4746 argument = argparse.Action(
4747 option_strings=[],
4748 dest='x',
4749 type=float,
4750 nargs='?',
4751 default=2.5,
4752 choices=[0.5, 1.5, 2.5],
4753 help='H HH H',
4754 metavar='MV MV MV')
4755 string = (
4756 "Action(option_strings=[], dest='x', nargs='?', "
4757 "const=None, default=2.5, type=%r, choices=[0.5, 1.5, 2.5], "
4758 "help='H HH H', metavar='MV MV MV')" % float)
4759 self.assertStringEqual(argument, string)
4760
4761 def test_namespace(self):
4762 ns = argparse.Namespace(foo=42, bar='spam')
Raymond Hettinger96819532020-05-17 18:53:01 -07004763 string = "Namespace(foo=42, bar='spam')"
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004764 self.assertStringEqual(ns, string)
4765
Berker Peksag76b17142015-07-29 23:51:47 +03004766 def test_namespace_starkwargs_notidentifier(self):
4767 ns = argparse.Namespace(**{'"': 'quote'})
4768 string = """Namespace(**{'"': 'quote'})"""
4769 self.assertStringEqual(ns, string)
4770
4771 def test_namespace_kwargs_and_starkwargs_notidentifier(self):
4772 ns = argparse.Namespace(a=1, **{'"': 'quote'})
4773 string = """Namespace(a=1, **{'"': 'quote'})"""
4774 self.assertStringEqual(ns, string)
4775
4776 def test_namespace_starkwargs_identifier(self):
4777 ns = argparse.Namespace(**{'valid': True})
4778 string = "Namespace(valid=True)"
4779 self.assertStringEqual(ns, string)
4780
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004781 def test_parser(self):
4782 parser = argparse.ArgumentParser(prog='PROG')
4783 string = (
4784 "ArgumentParser(prog='PROG', usage=None, description=None, "
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004785 "formatter_class=%r, conflict_handler='error', "
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004786 "add_help=True)" % argparse.HelpFormatter)
4787 self.assertStringEqual(parser, string)
4788
4789# ===============
4790# Namespace tests
4791# ===============
4792
4793class TestNamespace(TestCase):
4794
4795 def test_constructor(self):
4796 ns = argparse.Namespace()
4797 self.assertRaises(AttributeError, getattr, ns, 'x')
4798
4799 ns = argparse.Namespace(a=42, b='spam')
4800 self.assertEqual(ns.a, 42)
4801 self.assertEqual(ns.b, 'spam')
4802
4803 def test_equality(self):
4804 ns1 = argparse.Namespace(a=1, b=2)
4805 ns2 = argparse.Namespace(b=2, a=1)
4806 ns3 = argparse.Namespace(a=1)
4807 ns4 = argparse.Namespace(b=2)
4808
4809 self.assertEqual(ns1, ns2)
4810 self.assertNotEqual(ns1, ns3)
4811 self.assertNotEqual(ns1, ns4)
4812 self.assertNotEqual(ns2, ns3)
4813 self.assertNotEqual(ns2, ns4)
4814 self.assertTrue(ns1 != ns3)
4815 self.assertTrue(ns1 != ns4)
4816 self.assertTrue(ns2 != ns3)
4817 self.assertTrue(ns2 != ns4)
4818
Berker Peksagc16387b2016-09-28 17:21:52 +03004819 def test_equality_returns_notimplemented(self):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07004820 # See issue 21481
4821 ns = argparse.Namespace(a=1, b=2)
4822 self.assertIs(ns.__eq__(None), NotImplemented)
4823 self.assertIs(ns.__ne__(None), NotImplemented)
4824
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004825
4826# ===================
4827# File encoding tests
4828# ===================
4829
4830class TestEncoding(TestCase):
4831
4832 def _test_module_encoding(self, path):
4833 path, _ = os.path.splitext(path)
4834 path += ".py"
Victor Stinner272d8882017-06-16 08:59:01 +02004835 with open(path, 'r', encoding='utf-8') as f:
Antoine Pitroub86680e2010-10-14 21:15:17 +00004836 f.read()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004837
4838 def test_argparse_module_encoding(self):
4839 self._test_module_encoding(argparse.__file__)
4840
4841 def test_test_argparse_module_encoding(self):
4842 self._test_module_encoding(__file__)
4843
4844# ===================
4845# ArgumentError tests
4846# ===================
4847
4848class TestArgumentError(TestCase):
4849
4850 def test_argument_error(self):
4851 msg = "my error here"
4852 error = argparse.ArgumentError(None, msg)
4853 self.assertEqual(str(error), msg)
4854
4855# =======================
4856# ArgumentTypeError tests
4857# =======================
4858
R. David Murray722b5fd2010-11-20 03:48:58 +00004859class TestArgumentTypeError(TestCase):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004860
4861 def test_argument_type_error(self):
4862
4863 def spam(string):
4864 raise argparse.ArgumentTypeError('spam!')
4865
4866 parser = ErrorRaisingArgumentParser(prog='PROG', add_help=False)
4867 parser.add_argument('x', type=spam)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004868 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004869 parser.parse_args(['XXX'])
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004870 self.assertEqual('usage: PROG x\nPROG: error: argument x: spam!\n',
4871 cm.exception.stderr)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004872
R David Murrayf97c59a2011-06-09 12:34:07 -04004873# =========================
4874# MessageContentError tests
4875# =========================
4876
4877class TestMessageContentError(TestCase):
4878
4879 def test_missing_argument_name_in_message(self):
4880 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4881 parser.add_argument('req_pos', type=str)
4882 parser.add_argument('-req_opt', type=int, required=True)
4883 parser.add_argument('need_one', type=str, nargs='+')
4884
4885 with self.assertRaises(ArgumentParserError) as cm:
4886 parser.parse_args([])
4887 msg = str(cm.exception)
4888 self.assertRegex(msg, 'req_pos')
4889 self.assertRegex(msg, 'req_opt')
4890 self.assertRegex(msg, 'need_one')
4891 with self.assertRaises(ArgumentParserError) as cm:
4892 parser.parse_args(['myXargument'])
4893 msg = str(cm.exception)
4894 self.assertNotIn(msg, 'req_pos')
4895 self.assertRegex(msg, 'req_opt')
4896 self.assertRegex(msg, 'need_one')
4897 with self.assertRaises(ArgumentParserError) as cm:
4898 parser.parse_args(['myXargument', '-req_opt=1'])
4899 msg = str(cm.exception)
4900 self.assertNotIn(msg, 'req_pos')
4901 self.assertNotIn(msg, 'req_opt')
4902 self.assertRegex(msg, 'need_one')
4903
4904 def test_optional_optional_not_in_message(self):
4905 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4906 parser.add_argument('req_pos', type=str)
4907 parser.add_argument('--req_opt', type=int, required=True)
4908 parser.add_argument('--opt_opt', type=bool, nargs='?',
4909 default=True)
4910 with self.assertRaises(ArgumentParserError) as cm:
4911 parser.parse_args([])
4912 msg = str(cm.exception)
4913 self.assertRegex(msg, 'req_pos')
4914 self.assertRegex(msg, 'req_opt')
4915 self.assertNotIn(msg, 'opt_opt')
4916 with self.assertRaises(ArgumentParserError) as cm:
4917 parser.parse_args(['--req_opt=1'])
4918 msg = str(cm.exception)
4919 self.assertRegex(msg, 'req_pos')
4920 self.assertNotIn(msg, 'req_opt')
4921 self.assertNotIn(msg, 'opt_opt')
4922
4923 def test_optional_positional_not_in_message(self):
4924 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4925 parser.add_argument('req_pos')
4926 parser.add_argument('optional_positional', nargs='?', default='eggs')
4927 with self.assertRaises(ArgumentParserError) as cm:
4928 parser.parse_args([])
4929 msg = str(cm.exception)
4930 self.assertRegex(msg, 'req_pos')
4931 self.assertNotIn(msg, 'optional_positional')
4932
4933
R David Murray6fb8fb12012-08-31 22:45:20 -04004934# ================================================
4935# Check that the type function is called only once
4936# ================================================
4937
4938class TestTypeFunctionCallOnlyOnce(TestCase):
4939
4940 def test_type_function_call_only_once(self):
4941 def spam(string_to_convert):
4942 self.assertEqual(string_to_convert, 'spam!')
4943 return 'foo_converted'
4944
4945 parser = argparse.ArgumentParser()
4946 parser.add_argument('--foo', type=spam, default='bar')
4947 args = parser.parse_args('--foo spam!'.split())
4948 self.assertEqual(NS(foo='foo_converted'), args)
4949
Barry Warsaweaae1b72012-09-12 14:34:50 -04004950# ==================================================================
4951# Check semantics regarding the default argument and type conversion
4952# ==================================================================
R David Murray6fb8fb12012-08-31 22:45:20 -04004953
Barry Warsaweaae1b72012-09-12 14:34:50 -04004954class TestTypeFunctionCalledOnDefault(TestCase):
R David Murray6fb8fb12012-08-31 22:45:20 -04004955
4956 def test_type_function_call_with_non_string_default(self):
4957 def spam(int_to_convert):
4958 self.assertEqual(int_to_convert, 0)
4959 return 'foo_converted'
4960
4961 parser = argparse.ArgumentParser()
4962 parser.add_argument('--foo', type=spam, default=0)
4963 args = parser.parse_args([])
Barry Warsaweaae1b72012-09-12 14:34:50 -04004964 # foo should *not* be converted because its default is not a string.
4965 self.assertEqual(NS(foo=0), args)
4966
4967 def test_type_function_call_with_string_default(self):
4968 def spam(int_to_convert):
4969 return 'foo_converted'
4970
4971 parser = argparse.ArgumentParser()
4972 parser.add_argument('--foo', type=spam, default='0')
4973 args = parser.parse_args([])
4974 # foo is converted because its default is a string.
R David Murray6fb8fb12012-08-31 22:45:20 -04004975 self.assertEqual(NS(foo='foo_converted'), args)
4976
Barry Warsaweaae1b72012-09-12 14:34:50 -04004977 def test_no_double_type_conversion_of_default(self):
4978 def extend(str_to_convert):
4979 return str_to_convert + '*'
4980
4981 parser = argparse.ArgumentParser()
4982 parser.add_argument('--test', type=extend, default='*')
4983 args = parser.parse_args([])
4984 # The test argument will be two stars, one coming from the default
4985 # value and one coming from the type conversion being called exactly
4986 # once.
4987 self.assertEqual(NS(test='**'), args)
4988
Barry Warsaw4b2f9e92012-09-11 22:38:47 -04004989 def test_issue_15906(self):
4990 # Issue #15906: When action='append', type=str, default=[] are
4991 # providing, the dest value was the string representation "[]" when it
4992 # should have been an empty list.
4993 parser = argparse.ArgumentParser()
4994 parser.add_argument('--test', dest='test', type=str,
4995 default=[], action='append')
4996 args = parser.parse_args([])
4997 self.assertEqual(args.test, [])
4998
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004999# ======================
5000# parse_known_args tests
5001# ======================
5002
5003class TestParseKnownArgs(TestCase):
5004
R David Murrayb5228282012-09-08 12:08:01 -04005005 def test_arguments_tuple(self):
5006 parser = argparse.ArgumentParser()
5007 parser.parse_args(())
5008
5009 def test_arguments_list(self):
5010 parser = argparse.ArgumentParser()
5011 parser.parse_args([])
5012
5013 def test_arguments_tuple_positional(self):
5014 parser = argparse.ArgumentParser()
5015 parser.add_argument('x')
5016 parser.parse_args(('x',))
5017
5018 def test_arguments_list_positional(self):
5019 parser = argparse.ArgumentParser()
5020 parser.add_argument('x')
5021 parser.parse_args(['x'])
5022
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005023 def test_optionals(self):
5024 parser = argparse.ArgumentParser()
5025 parser.add_argument('--foo')
5026 args, extras = parser.parse_known_args('--foo F --bar --baz'.split())
5027 self.assertEqual(NS(foo='F'), args)
5028 self.assertEqual(['--bar', '--baz'], extras)
5029
5030 def test_mixed(self):
5031 parser = argparse.ArgumentParser()
5032 parser.add_argument('-v', nargs='?', const=1, type=int)
5033 parser.add_argument('--spam', action='store_false')
5034 parser.add_argument('badger')
5035
5036 argv = ["B", "C", "--foo", "-v", "3", "4"]
5037 args, extras = parser.parse_known_args(argv)
5038 self.assertEqual(NS(v=3, spam=True, badger="B"), args)
5039 self.assertEqual(["C", "--foo", "4"], extras)
5040
R. David Murray0f6b9d22017-09-06 20:25:40 -04005041# ===========================
5042# parse_intermixed_args tests
5043# ===========================
5044
5045class TestIntermixedArgs(TestCase):
5046 def test_basic(self):
5047 # test parsing intermixed optionals and positionals
5048 parser = argparse.ArgumentParser(prog='PROG')
5049 parser.add_argument('--foo', dest='foo')
5050 bar = parser.add_argument('--bar', dest='bar', required=True)
5051 parser.add_argument('cmd')
5052 parser.add_argument('rest', nargs='*', type=int)
5053 argv = 'cmd --foo x 1 --bar y 2 3'.split()
5054 args = parser.parse_intermixed_args(argv)
5055 # rest gets [1,2,3] despite the foo and bar strings
5056 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args)
5057
5058 args, extras = parser.parse_known_args(argv)
5059 # cannot parse the '1,2,3'
5060 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[]), args)
5061 self.assertEqual(["1", "2", "3"], extras)
5062
5063 argv = 'cmd --foo x 1 --error 2 --bar y 3'.split()
5064 args, extras = parser.parse_known_intermixed_args(argv)
5065 # unknown optionals go into extras
5066 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1]), args)
5067 self.assertEqual(['--error', '2', '3'], extras)
5068
5069 # restores attributes that were temporarily changed
5070 self.assertIsNone(parser.usage)
5071 self.assertEqual(bar.required, True)
5072
5073 def test_remainder(self):
5074 # Intermixed and remainder are incompatible
5075 parser = ErrorRaisingArgumentParser(prog='PROG')
5076 parser.add_argument('-z')
5077 parser.add_argument('x')
5078 parser.add_argument('y', nargs='...')
5079 argv = 'X A B -z Z'.split()
5080 # intermixed fails with '...' (also 'A...')
5081 # self.assertRaises(TypeError, parser.parse_intermixed_args, argv)
5082 with self.assertRaises(TypeError) as cm:
5083 parser.parse_intermixed_args(argv)
5084 self.assertRegex(str(cm.exception), r'\.\.\.')
5085
5086 def test_exclusive(self):
5087 # mutually exclusive group; intermixed works fine
5088 parser = ErrorRaisingArgumentParser(prog='PROG')
5089 group = parser.add_mutually_exclusive_group(required=True)
5090 group.add_argument('--foo', action='store_true', help='FOO')
5091 group.add_argument('--spam', help='SPAM')
5092 parser.add_argument('badger', nargs='*', default='X', help='BADGER')
5093 args = parser.parse_intermixed_args('1 --foo 2'.split())
5094 self.assertEqual(NS(badger=['1', '2'], foo=True, spam=None), args)
5095 self.assertRaises(ArgumentParserError, parser.parse_intermixed_args, '1 2'.split())
5096 self.assertEqual(group.required, True)
5097
5098 def test_exclusive_incompatible(self):
5099 # mutually exclusive group including positional - fail
5100 parser = ErrorRaisingArgumentParser(prog='PROG')
5101 group = parser.add_mutually_exclusive_group(required=True)
5102 group.add_argument('--foo', action='store_true', help='FOO')
5103 group.add_argument('--spam', help='SPAM')
5104 group.add_argument('badger', nargs='*', default='X', help='BADGER')
5105 self.assertRaises(TypeError, parser.parse_intermixed_args, [])
5106 self.assertEqual(group.required, True)
5107
5108class TestIntermixedMessageContentError(TestCase):
5109 # case where Intermixed gives different error message
5110 # error is raised by 1st parsing step
5111 def test_missing_argument_name_in_message(self):
5112 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
5113 parser.add_argument('req_pos', type=str)
5114 parser.add_argument('-req_opt', type=int, required=True)
5115
5116 with self.assertRaises(ArgumentParserError) as cm:
5117 parser.parse_args([])
5118 msg = str(cm.exception)
5119 self.assertRegex(msg, 'req_pos')
5120 self.assertRegex(msg, 'req_opt')
5121
5122 with self.assertRaises(ArgumentParserError) as cm:
5123 parser.parse_intermixed_args([])
5124 msg = str(cm.exception)
5125 self.assertNotRegex(msg, 'req_pos')
5126 self.assertRegex(msg, 'req_opt')
5127
Steven Bethard8d9a4622011-03-26 17:33:56 +01005128# ==========================
5129# add_argument metavar tests
5130# ==========================
5131
5132class TestAddArgumentMetavar(TestCase):
5133
5134 EXPECTED_MESSAGE = "length of metavar tuple does not match nargs"
5135
5136 def do_test_no_exception(self, nargs, metavar):
5137 parser = argparse.ArgumentParser()
5138 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
5139
5140 def do_test_exception(self, nargs, metavar):
5141 parser = argparse.ArgumentParser()
5142 with self.assertRaises(ValueError) as cm:
5143 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
5144 self.assertEqual(cm.exception.args[0], self.EXPECTED_MESSAGE)
5145
5146 # Unit tests for different values of metavar when nargs=None
5147
5148 def test_nargs_None_metavar_string(self):
5149 self.do_test_no_exception(nargs=None, metavar="1")
5150
5151 def test_nargs_None_metavar_length0(self):
5152 self.do_test_exception(nargs=None, metavar=tuple())
5153
5154 def test_nargs_None_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005155 self.do_test_no_exception(nargs=None, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005156
5157 def test_nargs_None_metavar_length2(self):
5158 self.do_test_exception(nargs=None, metavar=("1", "2"))
5159
5160 def test_nargs_None_metavar_length3(self):
5161 self.do_test_exception(nargs=None, metavar=("1", "2", "3"))
5162
5163 # Unit tests for different values of metavar when nargs=?
5164
5165 def test_nargs_optional_metavar_string(self):
5166 self.do_test_no_exception(nargs="?", metavar="1")
5167
5168 def test_nargs_optional_metavar_length0(self):
5169 self.do_test_exception(nargs="?", metavar=tuple())
5170
5171 def test_nargs_optional_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005172 self.do_test_no_exception(nargs="?", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005173
5174 def test_nargs_optional_metavar_length2(self):
5175 self.do_test_exception(nargs="?", metavar=("1", "2"))
5176
5177 def test_nargs_optional_metavar_length3(self):
5178 self.do_test_exception(nargs="?", metavar=("1", "2", "3"))
5179
5180 # Unit tests for different values of metavar when nargs=*
5181
5182 def test_nargs_zeroormore_metavar_string(self):
5183 self.do_test_no_exception(nargs="*", metavar="1")
5184
5185 def test_nargs_zeroormore_metavar_length0(self):
5186 self.do_test_exception(nargs="*", metavar=tuple())
5187
5188 def test_nargs_zeroormore_metavar_length1(self):
Brandt Buchera0ed99b2019-11-11 12:47:48 -08005189 self.do_test_no_exception(nargs="*", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005190
5191 def test_nargs_zeroormore_metavar_length2(self):
5192 self.do_test_no_exception(nargs="*", metavar=("1", "2"))
5193
5194 def test_nargs_zeroormore_metavar_length3(self):
5195 self.do_test_exception(nargs="*", metavar=("1", "2", "3"))
5196
5197 # Unit tests for different values of metavar when nargs=+
5198
5199 def test_nargs_oneormore_metavar_string(self):
5200 self.do_test_no_exception(nargs="+", metavar="1")
5201
5202 def test_nargs_oneormore_metavar_length0(self):
5203 self.do_test_exception(nargs="+", metavar=tuple())
5204
5205 def test_nargs_oneormore_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005206 self.do_test_exception(nargs="+", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005207
5208 def test_nargs_oneormore_metavar_length2(self):
5209 self.do_test_no_exception(nargs="+", metavar=("1", "2"))
5210
5211 def test_nargs_oneormore_metavar_length3(self):
5212 self.do_test_exception(nargs="+", metavar=("1", "2", "3"))
5213
5214 # Unit tests for different values of metavar when nargs=...
5215
5216 def test_nargs_remainder_metavar_string(self):
5217 self.do_test_no_exception(nargs="...", metavar="1")
5218
5219 def test_nargs_remainder_metavar_length0(self):
5220 self.do_test_no_exception(nargs="...", metavar=tuple())
5221
5222 def test_nargs_remainder_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005223 self.do_test_no_exception(nargs="...", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005224
5225 def test_nargs_remainder_metavar_length2(self):
5226 self.do_test_no_exception(nargs="...", metavar=("1", "2"))
5227
5228 def test_nargs_remainder_metavar_length3(self):
5229 self.do_test_no_exception(nargs="...", metavar=("1", "2", "3"))
5230
5231 # Unit tests for different values of metavar when nargs=A...
5232
5233 def test_nargs_parser_metavar_string(self):
5234 self.do_test_no_exception(nargs="A...", metavar="1")
5235
5236 def test_nargs_parser_metavar_length0(self):
5237 self.do_test_exception(nargs="A...", metavar=tuple())
5238
5239 def test_nargs_parser_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005240 self.do_test_no_exception(nargs="A...", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005241
5242 def test_nargs_parser_metavar_length2(self):
5243 self.do_test_exception(nargs="A...", metavar=("1", "2"))
5244
5245 def test_nargs_parser_metavar_length3(self):
5246 self.do_test_exception(nargs="A...", metavar=("1", "2", "3"))
5247
5248 # Unit tests for different values of metavar when nargs=1
5249
5250 def test_nargs_1_metavar_string(self):
5251 self.do_test_no_exception(nargs=1, metavar="1")
5252
5253 def test_nargs_1_metavar_length0(self):
5254 self.do_test_exception(nargs=1, metavar=tuple())
5255
5256 def test_nargs_1_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005257 self.do_test_no_exception(nargs=1, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005258
5259 def test_nargs_1_metavar_length2(self):
5260 self.do_test_exception(nargs=1, metavar=("1", "2"))
5261
5262 def test_nargs_1_metavar_length3(self):
5263 self.do_test_exception(nargs=1, metavar=("1", "2", "3"))
5264
5265 # Unit tests for different values of metavar when nargs=2
5266
5267 def test_nargs_2_metavar_string(self):
5268 self.do_test_no_exception(nargs=2, metavar="1")
5269
5270 def test_nargs_2_metavar_length0(self):
5271 self.do_test_exception(nargs=2, metavar=tuple())
5272
5273 def test_nargs_2_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005274 self.do_test_exception(nargs=2, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005275
5276 def test_nargs_2_metavar_length2(self):
5277 self.do_test_no_exception(nargs=2, metavar=("1", "2"))
5278
5279 def test_nargs_2_metavar_length3(self):
5280 self.do_test_exception(nargs=2, metavar=("1", "2", "3"))
5281
5282 # Unit tests for different values of metavar when nargs=3
5283
5284 def test_nargs_3_metavar_string(self):
5285 self.do_test_no_exception(nargs=3, metavar="1")
5286
5287 def test_nargs_3_metavar_length0(self):
5288 self.do_test_exception(nargs=3, metavar=tuple())
5289
5290 def test_nargs_3_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005291 self.do_test_exception(nargs=3, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005292
5293 def test_nargs_3_metavar_length2(self):
5294 self.do_test_exception(nargs=3, metavar=("1", "2"))
5295
5296 def test_nargs_3_metavar_length3(self):
5297 self.do_test_no_exception(nargs=3, metavar=("1", "2", "3"))
5298
tmblweed4b3e9752019-08-01 21:57:13 -07005299
5300class TestInvalidNargs(TestCase):
5301
5302 EXPECTED_INVALID_MESSAGE = "invalid nargs value"
5303 EXPECTED_RANGE_MESSAGE = ("nargs for store actions must be != 0; if you "
5304 "have nothing to store, actions such as store "
5305 "true or store const may be more appropriate")
5306
5307 def do_test_range_exception(self, nargs):
5308 parser = argparse.ArgumentParser()
5309 with self.assertRaises(ValueError) as cm:
5310 parser.add_argument("--foo", nargs=nargs)
5311 self.assertEqual(cm.exception.args[0], self.EXPECTED_RANGE_MESSAGE)
5312
5313 def do_test_invalid_exception(self, nargs):
5314 parser = argparse.ArgumentParser()
5315 with self.assertRaises(ValueError) as cm:
5316 parser.add_argument("--foo", nargs=nargs)
5317 self.assertEqual(cm.exception.args[0], self.EXPECTED_INVALID_MESSAGE)
5318
5319 # Unit tests for different values of nargs
5320
5321 def test_nargs_alphabetic(self):
5322 self.do_test_invalid_exception(nargs='a')
5323 self.do_test_invalid_exception(nargs="abcd")
5324
5325 def test_nargs_zero(self):
5326 self.do_test_range_exception(nargs=0)
5327
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005328# ============================
5329# from argparse import * tests
5330# ============================
5331
5332class TestImportStar(TestCase):
5333
5334 def test(self):
5335 for name in argparse.__all__:
5336 self.assertTrue(hasattr(argparse, name))
5337
Steven Bethard72c55382010-11-01 15:23:12 +00005338 def test_all_exports_everything_but_modules(self):
5339 items = [
5340 name
5341 for name, value in vars(argparse).items()
Éric Araujo12159152010-12-04 17:31:49 +00005342 if not (name.startswith("_") or name == 'ngettext')
Steven Bethard72c55382010-11-01 15:23:12 +00005343 if not inspect.ismodule(value)
5344 ]
5345 self.assertEqual(sorted(items), sorted(argparse.__all__))
5346
wim glenn66f02aa2018-06-08 05:12:49 -05005347
5348class TestWrappingMetavar(TestCase):
5349
5350 def setUp(self):
Berker Peksag74102c92018-07-25 18:23:44 +03005351 super().setUp()
wim glenn66f02aa2018-06-08 05:12:49 -05005352 self.parser = ErrorRaisingArgumentParser(
5353 'this_is_spammy_prog_with_a_long_name_sorry_about_the_name'
5354 )
5355 # this metavar was triggering library assertion errors due to usage
5356 # message formatting incorrectly splitting on the ] chars within
5357 metavar = '<http[s]://example:1234>'
5358 self.parser.add_argument('--proxy', metavar=metavar)
5359
5360 def test_help_with_metavar(self):
5361 help_text = self.parser.format_help()
5362 self.assertEqual(help_text, textwrap.dedent('''\
5363 usage: this_is_spammy_prog_with_a_long_name_sorry_about_the_name
5364 [-h] [--proxy <http[s]://example:1234>]
5365
Raymond Hettinger41b223d2020-12-23 09:40:56 -08005366 options:
wim glenn66f02aa2018-06-08 05:12:49 -05005367 -h, --help show this help message and exit
5368 --proxy <http[s]://example:1234>
5369 '''))
5370
5371
Hai Shif5456382019-09-12 05:56:05 -05005372class TestExitOnError(TestCase):
5373
5374 def setUp(self):
5375 self.parser = argparse.ArgumentParser(exit_on_error=False)
5376 self.parser.add_argument('--integers', metavar='N', type=int)
5377
5378 def test_exit_on_error_with_good_args(self):
5379 ns = self.parser.parse_args('--integers 4'.split())
5380 self.assertEqual(ns, argparse.Namespace(integers=4))
5381
5382 def test_exit_on_error_with_bad_args(self):
5383 with self.assertRaises(argparse.ArgumentError):
5384 self.parser.parse_args('--integers a'.split())
5385
5386
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005387def test_main():
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02005388 support.run_unittest(__name__)
Benjamin Peterson4fd181c2010-03-02 23:46:42 +00005389 # Remove global references to avoid looking like we have refleaks.
5390 RFile.seen = {}
5391 WFile.seen = set()
5392
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005393
5394
5395if __name__ == '__main__':
5396 test_main()