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