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