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