blob: 85449c729902fba30caf5b557c8f062c713477cf [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
3import codecs
Steven Bethard72c55382010-11-01 15:23:12 +00004import inspect
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005import os
6import shutil
Steven Bethardb0270112011-01-24 21:02:50 +00007import stat
Benjamin Peterson698a18a2010-03-02 22:34:37 +00008import sys
9import textwrap
10import tempfile
11import unittest
Benjamin Peterson698a18a2010-03-02 22:34:37 +000012import argparse
13
Benjamin Peterson16f2fd02010-03-02 23:09:38 +000014from io import StringIO
15
Benjamin Peterson698a18a2010-03-02 22:34:37 +000016from test import support
Petri Lehtinen74d6c252012-12-15 22:39:32 +020017from unittest import mock
Benjamin Petersonb48af542010-04-11 20:43:16 +000018class StdIOBuffer(StringIO):
19 pass
Benjamin Peterson698a18a2010-03-02 22:34:37 +000020
Benjamin Peterson698a18a2010-03-02 22:34:37 +000021class TestCase(unittest.TestCase):
22
Steven Bethard1f1c2472010-11-01 13:56:09 +000023 def setUp(self):
24 # The tests assume that line wrapping occurs at 80 columns, but this
25 # behaviour can be overridden by setting the COLUMNS environment
26 # variable. To ensure that this assumption is true, unset COLUMNS.
27 env = support.EnvironmentVarGuard()
28 env.unset("COLUMNS")
29 self.addCleanup(env.__exit__)
Benjamin Peterson698a18a2010-03-02 22:34:37 +000030
Benjamin Petersonb48af542010-04-11 20:43:16 +000031
Benjamin Peterson698a18a2010-03-02 22:34:37 +000032class TempDirMixin(object):
33
34 def setUp(self):
35 self.temp_dir = tempfile.mkdtemp()
36 self.old_dir = os.getcwd()
37 os.chdir(self.temp_dir)
38
39 def tearDown(self):
40 os.chdir(self.old_dir)
Benjamin Peterson511e2222014-04-04 13:55:56 -040041 for root, dirs, files in os.walk(self.temp_dir, topdown=False):
42 for name in files:
43 os.chmod(os.path.join(self.temp_dir, name), stat.S_IWRITE)
Steven Bethardb0270112011-01-24 21:02:50 +000044 shutil.rmtree(self.temp_dir, True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +000045
Steven Bethardb0270112011-01-24 21:02:50 +000046 def create_readonly_file(self, filename):
47 file_path = os.path.join(self.temp_dir, filename)
48 with open(file_path, 'w') as file:
49 file.write(filename)
50 os.chmod(file_path, stat.S_IREAD)
Benjamin Peterson698a18a2010-03-02 22:34:37 +000051
52class Sig(object):
53
54 def __init__(self, *args, **kwargs):
55 self.args = args
56 self.kwargs = kwargs
57
58
59class NS(object):
60
61 def __init__(self, **kwargs):
62 self.__dict__.update(kwargs)
63
64 def __repr__(self):
65 sorted_items = sorted(self.__dict__.items())
66 kwarg_str = ', '.join(['%s=%r' % tup for tup in sorted_items])
67 return '%s(%s)' % (type(self).__name__, kwarg_str)
68
69 def __eq__(self, other):
70 return vars(self) == vars(other)
71
Benjamin Peterson698a18a2010-03-02 22:34:37 +000072
73class ArgumentParserError(Exception):
74
75 def __init__(self, message, stdout=None, stderr=None, error_code=None):
76 Exception.__init__(self, message, stdout, stderr)
77 self.message = message
78 self.stdout = stdout
79 self.stderr = stderr
80 self.error_code = error_code
81
82
83def stderr_to_parser_error(parse_args, *args, **kwargs):
84 # if this is being called recursively and stderr or stdout is already being
85 # redirected, simply call the function and let the enclosing function
86 # catch the exception
Benjamin Petersonb48af542010-04-11 20:43:16 +000087 if isinstance(sys.stderr, StdIOBuffer) or isinstance(sys.stdout, StdIOBuffer):
Benjamin Peterson698a18a2010-03-02 22:34:37 +000088 return parse_args(*args, **kwargs)
89
90 # if this is not being called recursively, redirect stderr and
91 # use it as the ArgumentParserError message
92 old_stdout = sys.stdout
93 old_stderr = sys.stderr
Benjamin Petersonb48af542010-04-11 20:43:16 +000094 sys.stdout = StdIOBuffer()
95 sys.stderr = StdIOBuffer()
Benjamin Peterson698a18a2010-03-02 22:34:37 +000096 try:
97 try:
98 result = parse_args(*args, **kwargs)
99 for key in list(vars(result)):
100 if getattr(result, key) is sys.stdout:
101 setattr(result, key, old_stdout)
102 if getattr(result, key) is sys.stderr:
103 setattr(result, key, old_stderr)
104 return result
105 except SystemExit:
106 code = sys.exc_info()[1].code
107 stdout = sys.stdout.getvalue()
108 stderr = sys.stderr.getvalue()
109 raise ArgumentParserError("SystemExit", stdout, stderr, code)
110 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
690
691class TestOptionalsActionAppend(ParserTestCase):
692 """Tests the append action for an Optional"""
693
694 argument_signatures = [Sig('--baz', action='append')]
695 failures = ['a', '--baz', 'a --baz', '--baz a b']
696 successes = [
697 ('', NS(baz=None)),
698 ('--baz a', NS(baz=['a'])),
699 ('--baz a --baz b', NS(baz=['a', 'b'])),
700 ]
701
702
703class TestOptionalsActionAppendWithDefault(ParserTestCase):
704 """Tests the append action for an Optional"""
705
706 argument_signatures = [Sig('--baz', action='append', default=['X'])]
707 failures = ['a', '--baz', 'a --baz', '--baz a b']
708 successes = [
709 ('', NS(baz=['X'])),
710 ('--baz a', NS(baz=['X', 'a'])),
711 ('--baz a --baz b', NS(baz=['X', 'a', 'b'])),
712 ]
713
714
715class TestOptionalsActionAppendConst(ParserTestCase):
716 """Tests the append_const action for an Optional"""
717
718 argument_signatures = [
719 Sig('-b', action='append_const', const=Exception),
720 Sig('-c', action='append', dest='b'),
721 ]
722 failures = ['a', '-c', 'a -c', '-bx', '-b x']
723 successes = [
724 ('', NS(b=None)),
725 ('-b', NS(b=[Exception])),
726 ('-b -cx -b -cyz', NS(b=[Exception, 'x', Exception, 'yz'])),
727 ]
728
729
730class TestOptionalsActionAppendConstWithDefault(ParserTestCase):
731 """Tests the append_const action for an Optional"""
732
733 argument_signatures = [
734 Sig('-b', action='append_const', const=Exception, default=['X']),
735 Sig('-c', action='append', dest='b'),
736 ]
737 failures = ['a', '-c', 'a -c', '-bx', '-b x']
738 successes = [
739 ('', NS(b=['X'])),
740 ('-b', NS(b=['X', Exception])),
741 ('-b -cx -b -cyz', NS(b=['X', Exception, 'x', Exception, 'yz'])),
742 ]
743
744
745class TestOptionalsActionCount(ParserTestCase):
746 """Tests the count action for an Optional"""
747
748 argument_signatures = [Sig('-x', action='count')]
749 failures = ['a', '-x a', '-x b', '-x a -x b']
750 successes = [
751 ('', NS(x=None)),
752 ('-x', NS(x=1)),
753 ]
754
755
Berker Peksag8089cd62015-02-14 01:39:17 +0200756class TestOptionalsAllowLongAbbreviation(ParserTestCase):
757 """Allow long options to be abbreviated unambiguously"""
758
759 argument_signatures = [
760 Sig('--foo'),
761 Sig('--foobaz'),
762 Sig('--fooble', action='store_true'),
763 ]
764 failures = ['--foob 5', '--foob']
765 successes = [
766 ('', NS(foo=None, foobaz=None, fooble=False)),
767 ('--foo 7', NS(foo='7', foobaz=None, fooble=False)),
768 ('--fooba a', NS(foo=None, foobaz='a', fooble=False)),
769 ('--foobl --foo g', NS(foo='g', foobaz=None, fooble=True)),
770 ]
771
772
773class TestOptionalsDisallowLongAbbreviation(ParserTestCase):
774 """Do not allow abbreviations of long options at all"""
775
776 parser_signature = Sig(allow_abbrev=False)
777 argument_signatures = [
778 Sig('--foo'),
779 Sig('--foodle', action='store_true'),
780 Sig('--foonly'),
781 ]
782 failures = ['-foon 3', '--foon 3', '--food', '--food --foo 2']
783 successes = [
784 ('', NS(foo=None, foodle=False, foonly=None)),
785 ('--foo 3', NS(foo='3', foodle=False, foonly=None)),
786 ('--foonly 7 --foodle --foo 2', NS(foo='2', foodle=True, foonly='7')),
787 ]
788
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000789# ================
790# Positional tests
791# ================
792
793class TestPositionalsNargsNone(ParserTestCase):
794 """Test a Positional that doesn't specify nargs"""
795
796 argument_signatures = [Sig('foo')]
797 failures = ['', '-x', 'a b']
798 successes = [
799 ('a', NS(foo='a')),
800 ]
801
802
803class TestPositionalsNargs1(ParserTestCase):
804 """Test a Positional that specifies an nargs of 1"""
805
806 argument_signatures = [Sig('foo', nargs=1)]
807 failures = ['', '-x', 'a b']
808 successes = [
809 ('a', NS(foo=['a'])),
810 ]
811
812
813class TestPositionalsNargs2(ParserTestCase):
814 """Test a Positional that specifies an nargs of 2"""
815
816 argument_signatures = [Sig('foo', nargs=2)]
817 failures = ['', 'a', '-x', 'a b c']
818 successes = [
819 ('a b', NS(foo=['a', 'b'])),
820 ]
821
822
823class TestPositionalsNargsZeroOrMore(ParserTestCase):
824 """Test a Positional that specifies unlimited nargs"""
825
826 argument_signatures = [Sig('foo', nargs='*')]
827 failures = ['-x']
828 successes = [
829 ('', NS(foo=[])),
830 ('a', NS(foo=['a'])),
831 ('a b', NS(foo=['a', 'b'])),
832 ]
833
834
835class TestPositionalsNargsZeroOrMoreDefault(ParserTestCase):
836 """Test a Positional that specifies unlimited nargs and a default"""
837
838 argument_signatures = [Sig('foo', nargs='*', default='bar')]
839 failures = ['-x']
840 successes = [
841 ('', NS(foo='bar')),
842 ('a', NS(foo=['a'])),
843 ('a b', NS(foo=['a', 'b'])),
844 ]
845
846
847class TestPositionalsNargsOneOrMore(ParserTestCase):
848 """Test a Positional that specifies one or more nargs"""
849
850 argument_signatures = [Sig('foo', nargs='+')]
851 failures = ['', '-x']
852 successes = [
853 ('a', NS(foo=['a'])),
854 ('a b', NS(foo=['a', 'b'])),
855 ]
856
857
858class TestPositionalsNargsOptional(ParserTestCase):
859 """Tests an Optional Positional"""
860
861 argument_signatures = [Sig('foo', nargs='?')]
862 failures = ['-x', 'a b']
863 successes = [
864 ('', NS(foo=None)),
865 ('a', NS(foo='a')),
866 ]
867
868
869class TestPositionalsNargsOptionalDefault(ParserTestCase):
870 """Tests an Optional Positional with a default value"""
871
872 argument_signatures = [Sig('foo', nargs='?', default=42)]
873 failures = ['-x', 'a b']
874 successes = [
875 ('', NS(foo=42)),
876 ('a', NS(foo='a')),
877 ]
878
879
880class TestPositionalsNargsOptionalConvertedDefault(ParserTestCase):
881 """Tests an Optional Positional with a default value
882 that needs to be converted to the appropriate type.
883 """
884
885 argument_signatures = [
886 Sig('foo', nargs='?', type=int, default='42'),
887 ]
888 failures = ['-x', 'a b', '1 2']
889 successes = [
890 ('', NS(foo=42)),
891 ('1', NS(foo=1)),
892 ]
893
894
895class TestPositionalsNargsNoneNone(ParserTestCase):
896 """Test two Positionals that don't specify nargs"""
897
898 argument_signatures = [Sig('foo'), Sig('bar')]
899 failures = ['', '-x', 'a', 'a b c']
900 successes = [
901 ('a b', NS(foo='a', bar='b')),
902 ]
903
904
905class TestPositionalsNargsNone1(ParserTestCase):
906 """Test a Positional with no nargs followed by one with 1"""
907
908 argument_signatures = [Sig('foo'), Sig('bar', nargs=1)]
909 failures = ['', '--foo', 'a', 'a b c']
910 successes = [
911 ('a b', NS(foo='a', bar=['b'])),
912 ]
913
914
915class TestPositionalsNargs2None(ParserTestCase):
916 """Test a Positional with 2 nargs followed by one with none"""
917
918 argument_signatures = [Sig('foo', nargs=2), Sig('bar')]
919 failures = ['', '--foo', 'a', 'a b', 'a b c d']
920 successes = [
921 ('a b c', NS(foo=['a', 'b'], bar='c')),
922 ]
923
924
925class TestPositionalsNargsNoneZeroOrMore(ParserTestCase):
926 """Test a Positional with no nargs followed by one with unlimited"""
927
928 argument_signatures = [Sig('foo'), Sig('bar', nargs='*')]
929 failures = ['', '--foo']
930 successes = [
931 ('a', NS(foo='a', bar=[])),
932 ('a b', NS(foo='a', bar=['b'])),
933 ('a b c', NS(foo='a', bar=['b', 'c'])),
934 ]
935
936
937class TestPositionalsNargsNoneOneOrMore(ParserTestCase):
938 """Test a Positional with no nargs followed by one with one or more"""
939
940 argument_signatures = [Sig('foo'), Sig('bar', nargs='+')]
941 failures = ['', '--foo', 'a']
942 successes = [
943 ('a b', NS(foo='a', bar=['b'])),
944 ('a b c', NS(foo='a', bar=['b', 'c'])),
945 ]
946
947
948class TestPositionalsNargsNoneOptional(ParserTestCase):
949 """Test a Positional with no nargs followed by one with an Optional"""
950
951 argument_signatures = [Sig('foo'), Sig('bar', nargs='?')]
952 failures = ['', '--foo', 'a b c']
953 successes = [
954 ('a', NS(foo='a', bar=None)),
955 ('a b', NS(foo='a', bar='b')),
956 ]
957
958
959class TestPositionalsNargsZeroOrMoreNone(ParserTestCase):
960 """Test a Positional with unlimited nargs followed by one with none"""
961
962 argument_signatures = [Sig('foo', nargs='*'), Sig('bar')]
963 failures = ['', '--foo']
964 successes = [
965 ('a', NS(foo=[], bar='a')),
966 ('a b', NS(foo=['a'], bar='b')),
967 ('a b c', NS(foo=['a', 'b'], bar='c')),
968 ]
969
970
971class TestPositionalsNargsOneOrMoreNone(ParserTestCase):
972 """Test a Positional with one or more nargs followed by one with none"""
973
974 argument_signatures = [Sig('foo', nargs='+'), Sig('bar')]
975 failures = ['', '--foo', 'a']
976 successes = [
977 ('a b', NS(foo=['a'], bar='b')),
978 ('a b c', NS(foo=['a', 'b'], bar='c')),
979 ]
980
981
982class TestPositionalsNargsOptionalNone(ParserTestCase):
983 """Test a Positional with an Optional nargs followed by one with none"""
984
985 argument_signatures = [Sig('foo', nargs='?', default=42), Sig('bar')]
986 failures = ['', '--foo', 'a b c']
987 successes = [
988 ('a', NS(foo=42, bar='a')),
989 ('a b', NS(foo='a', bar='b')),
990 ]
991
992
993class TestPositionalsNargs2ZeroOrMore(ParserTestCase):
994 """Test a Positional with 2 nargs followed by one with unlimited"""
995
996 argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='*')]
997 failures = ['', '--foo', 'a']
998 successes = [
999 ('a b', NS(foo=['a', 'b'], bar=[])),
1000 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1001 ]
1002
1003
1004class TestPositionalsNargs2OneOrMore(ParserTestCase):
1005 """Test a Positional with 2 nargs followed by one with one or more"""
1006
1007 argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='+')]
1008 failures = ['', '--foo', 'a', 'a b']
1009 successes = [
1010 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1011 ]
1012
1013
1014class TestPositionalsNargs2Optional(ParserTestCase):
1015 """Test a Positional with 2 nargs followed by one optional"""
1016
1017 argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='?')]
1018 failures = ['', '--foo', 'a', 'a b c d']
1019 successes = [
1020 ('a b', NS(foo=['a', 'b'], bar=None)),
1021 ('a b c', NS(foo=['a', 'b'], bar='c')),
1022 ]
1023
1024
1025class TestPositionalsNargsZeroOrMore1(ParserTestCase):
1026 """Test a Positional with unlimited nargs followed by one with 1"""
1027
1028 argument_signatures = [Sig('foo', nargs='*'), Sig('bar', nargs=1)]
1029 failures = ['', '--foo', ]
1030 successes = [
1031 ('a', NS(foo=[], bar=['a'])),
1032 ('a b', NS(foo=['a'], bar=['b'])),
1033 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1034 ]
1035
1036
1037class TestPositionalsNargsOneOrMore1(ParserTestCase):
1038 """Test a Positional with one or more nargs followed by one with 1"""
1039
1040 argument_signatures = [Sig('foo', nargs='+'), Sig('bar', nargs=1)]
1041 failures = ['', '--foo', 'a']
1042 successes = [
1043 ('a b', NS(foo=['a'], bar=['b'])),
1044 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1045 ]
1046
1047
1048class TestPositionalsNargsOptional1(ParserTestCase):
1049 """Test a Positional with an Optional nargs followed by one with 1"""
1050
1051 argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs=1)]
1052 failures = ['', '--foo', 'a b c']
1053 successes = [
1054 ('a', NS(foo=None, bar=['a'])),
1055 ('a b', NS(foo='a', bar=['b'])),
1056 ]
1057
1058
1059class TestPositionalsNargsNoneZeroOrMore1(ParserTestCase):
1060 """Test three Positionals: no nargs, unlimited nargs and 1 nargs"""
1061
1062 argument_signatures = [
1063 Sig('foo'),
1064 Sig('bar', nargs='*'),
1065 Sig('baz', nargs=1),
1066 ]
1067 failures = ['', '--foo', 'a']
1068 successes = [
1069 ('a b', NS(foo='a', bar=[], baz=['b'])),
1070 ('a b c', NS(foo='a', bar=['b'], baz=['c'])),
1071 ]
1072
1073
1074class TestPositionalsNargsNoneOneOrMore1(ParserTestCase):
1075 """Test three Positionals: no nargs, one or more nargs and 1 nargs"""
1076
1077 argument_signatures = [
1078 Sig('foo'),
1079 Sig('bar', nargs='+'),
1080 Sig('baz', nargs=1),
1081 ]
1082 failures = ['', '--foo', 'a', 'b']
1083 successes = [
1084 ('a b c', NS(foo='a', bar=['b'], baz=['c'])),
1085 ('a b c d', NS(foo='a', bar=['b', 'c'], baz=['d'])),
1086 ]
1087
1088
1089class TestPositionalsNargsNoneOptional1(ParserTestCase):
1090 """Test three Positionals: no nargs, optional narg and 1 nargs"""
1091
1092 argument_signatures = [
1093 Sig('foo'),
1094 Sig('bar', nargs='?', default=0.625),
1095 Sig('baz', nargs=1),
1096 ]
1097 failures = ['', '--foo', 'a']
1098 successes = [
1099 ('a b', NS(foo='a', bar=0.625, baz=['b'])),
1100 ('a b c', NS(foo='a', bar='b', baz=['c'])),
1101 ]
1102
1103
1104class TestPositionalsNargsOptionalOptional(ParserTestCase):
1105 """Test two optional nargs"""
1106
1107 argument_signatures = [
1108 Sig('foo', nargs='?'),
1109 Sig('bar', nargs='?', default=42),
1110 ]
1111 failures = ['--foo', 'a b c']
1112 successes = [
1113 ('', NS(foo=None, bar=42)),
1114 ('a', NS(foo='a', bar=42)),
1115 ('a b', NS(foo='a', bar='b')),
1116 ]
1117
1118
1119class TestPositionalsNargsOptionalZeroOrMore(ParserTestCase):
1120 """Test an Optional narg followed by unlimited nargs"""
1121
1122 argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs='*')]
1123 failures = ['--foo']
1124 successes = [
1125 ('', NS(foo=None, bar=[])),
1126 ('a', NS(foo='a', bar=[])),
1127 ('a b', NS(foo='a', bar=['b'])),
1128 ('a b c', NS(foo='a', bar=['b', 'c'])),
1129 ]
1130
1131
1132class TestPositionalsNargsOptionalOneOrMore(ParserTestCase):
1133 """Test an Optional narg followed by one or more nargs"""
1134
1135 argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs='+')]
1136 failures = ['', '--foo']
1137 successes = [
1138 ('a', NS(foo=None, bar=['a'])),
1139 ('a b', NS(foo='a', bar=['b'])),
1140 ('a b c', NS(foo='a', bar=['b', 'c'])),
1141 ]
1142
1143
1144class TestPositionalsChoicesString(ParserTestCase):
1145 """Test a set of single-character choices"""
1146
1147 argument_signatures = [Sig('spam', choices=set('abcdefg'))]
1148 failures = ['', '--foo', 'h', '42', 'ef']
1149 successes = [
1150 ('a', NS(spam='a')),
1151 ('g', NS(spam='g')),
1152 ]
1153
1154
1155class TestPositionalsChoicesInt(ParserTestCase):
1156 """Test a set of integer choices"""
1157
1158 argument_signatures = [Sig('spam', type=int, choices=range(20))]
1159 failures = ['', '--foo', 'h', '42', 'ef']
1160 successes = [
1161 ('4', NS(spam=4)),
1162 ('15', NS(spam=15)),
1163 ]
1164
1165
1166class TestPositionalsActionAppend(ParserTestCase):
1167 """Test the 'append' action"""
1168
1169 argument_signatures = [
1170 Sig('spam', action='append'),
1171 Sig('spam', action='append', nargs=2),
1172 ]
1173 failures = ['', '--foo', 'a', 'a b', 'a b c d']
1174 successes = [
1175 ('a b c', NS(spam=['a', ['b', 'c']])),
1176 ]
1177
1178# ========================================
1179# Combined optionals and positionals tests
1180# ========================================
1181
1182class TestOptionalsNumericAndPositionals(ParserTestCase):
1183 """Tests negative number args when numeric options are present"""
1184
1185 argument_signatures = [
1186 Sig('x', nargs='?'),
1187 Sig('-4', dest='y', action='store_true'),
1188 ]
1189 failures = ['-2', '-315']
1190 successes = [
1191 ('', NS(x=None, y=False)),
1192 ('a', NS(x='a', y=False)),
1193 ('-4', NS(x=None, y=True)),
1194 ('-4 a', NS(x='a', y=True)),
1195 ]
1196
1197
1198class TestOptionalsAlmostNumericAndPositionals(ParserTestCase):
1199 """Tests negative number args when almost numeric options are present"""
1200
1201 argument_signatures = [
1202 Sig('x', nargs='?'),
1203 Sig('-k4', dest='y', action='store_true'),
1204 ]
1205 failures = ['-k3']
1206 successes = [
1207 ('', NS(x=None, y=False)),
1208 ('-2', NS(x='-2', y=False)),
1209 ('a', NS(x='a', y=False)),
1210 ('-k4', NS(x=None, y=True)),
1211 ('-k4 a', NS(x='a', y=True)),
1212 ]
1213
1214
1215class TestEmptyAndSpaceContainingArguments(ParserTestCase):
1216
1217 argument_signatures = [
1218 Sig('x', nargs='?'),
1219 Sig('-y', '--yyy', dest='y'),
1220 ]
1221 failures = ['-y']
1222 successes = [
1223 ([''], NS(x='', y=None)),
1224 (['a badger'], NS(x='a badger', y=None)),
1225 (['-a badger'], NS(x='-a badger', y=None)),
1226 (['-y', ''], NS(x=None, y='')),
1227 (['-y', 'a badger'], NS(x=None, y='a badger')),
1228 (['-y', '-a badger'], NS(x=None, y='-a badger')),
1229 (['--yyy=a badger'], NS(x=None, y='a badger')),
1230 (['--yyy=-a badger'], NS(x=None, y='-a badger')),
1231 ]
1232
1233
1234class TestPrefixCharacterOnlyArguments(ParserTestCase):
1235
1236 parser_signature = Sig(prefix_chars='-+')
1237 argument_signatures = [
1238 Sig('-', dest='x', nargs='?', const='badger'),
1239 Sig('+', dest='y', type=int, default=42),
1240 Sig('-+-', dest='z', action='store_true'),
1241 ]
1242 failures = ['-y', '+ -']
1243 successes = [
1244 ('', NS(x=None, y=42, z=False)),
1245 ('-', NS(x='badger', y=42, z=False)),
1246 ('- X', NS(x='X', y=42, z=False)),
1247 ('+ -3', NS(x=None, y=-3, z=False)),
1248 ('-+-', NS(x=None, y=42, z=True)),
1249 ('- ===', NS(x='===', y=42, z=False)),
1250 ]
1251
1252
1253class TestNargsZeroOrMore(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +00001254 """Tests specifying args for an Optional that accepts zero or more"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001255
1256 argument_signatures = [Sig('-x', nargs='*'), Sig('y', nargs='*')]
1257 failures = []
1258 successes = [
1259 ('', NS(x=None, y=[])),
1260 ('-x', NS(x=[], y=[])),
1261 ('-x a', NS(x=['a'], y=[])),
1262 ('-x a -- b', NS(x=['a'], y=['b'])),
1263 ('a', NS(x=None, y=['a'])),
1264 ('a -x', NS(x=[], y=['a'])),
1265 ('a -x b', NS(x=['b'], y=['a'])),
1266 ]
1267
1268
1269class TestNargsRemainder(ParserTestCase):
1270 """Tests specifying a positional with nargs=REMAINDER"""
1271
1272 argument_signatures = [Sig('x'), Sig('y', nargs='...'), Sig('-z')]
1273 failures = ['', '-z', '-z Z']
1274 successes = [
1275 ('X', NS(x='X', y=[], z=None)),
1276 ('-z Z X', NS(x='X', y=[], z='Z')),
1277 ('X A B -z Z', NS(x='X', y=['A', 'B', '-z', 'Z'], z=None)),
1278 ('X Y --foo', NS(x='X', y=['Y', '--foo'], z=None)),
1279 ]
1280
1281
1282class TestOptionLike(ParserTestCase):
1283 """Tests options that may or may not be arguments"""
1284
1285 argument_signatures = [
1286 Sig('-x', type=float),
1287 Sig('-3', type=float, dest='y'),
1288 Sig('z', nargs='*'),
1289 ]
1290 failures = ['-x', '-y2.5', '-xa', '-x -a',
1291 '-x -3', '-x -3.5', '-3 -3.5',
1292 '-x -2.5', '-x -2.5 a', '-3 -.5',
1293 'a x -1', '-x -1 a', '-3 -1 a']
1294 successes = [
1295 ('', NS(x=None, y=None, z=[])),
1296 ('-x 2.5', NS(x=2.5, y=None, z=[])),
1297 ('-x 2.5 a', NS(x=2.5, y=None, z=['a'])),
1298 ('-3.5', NS(x=None, y=0.5, z=[])),
1299 ('-3-.5', NS(x=None, y=-0.5, z=[])),
1300 ('-3 .5', NS(x=None, y=0.5, z=[])),
1301 ('a -3.5', NS(x=None, y=0.5, z=['a'])),
1302 ('a', NS(x=None, y=None, z=['a'])),
1303 ('a -x 1', NS(x=1.0, y=None, z=['a'])),
1304 ('-x 1 a', NS(x=1.0, y=None, z=['a'])),
1305 ('-3 1 a', NS(x=None, y=1.0, z=['a'])),
1306 ]
1307
1308
1309class TestDefaultSuppress(ParserTestCase):
1310 """Test actions with suppressed defaults"""
1311
1312 argument_signatures = [
1313 Sig('foo', nargs='?', default=argparse.SUPPRESS),
1314 Sig('bar', nargs='*', default=argparse.SUPPRESS),
1315 Sig('--baz', action='store_true', default=argparse.SUPPRESS),
1316 ]
1317 failures = ['-x']
1318 successes = [
1319 ('', NS()),
1320 ('a', NS(foo='a')),
1321 ('a b', NS(foo='a', bar=['b'])),
1322 ('--baz', NS(baz=True)),
1323 ('a --baz', NS(foo='a', baz=True)),
1324 ('--baz a b', NS(foo='a', bar=['b'], baz=True)),
1325 ]
1326
1327
1328class TestParserDefaultSuppress(ParserTestCase):
1329 """Test actions with a parser-level default of SUPPRESS"""
1330
1331 parser_signature = Sig(argument_default=argparse.SUPPRESS)
1332 argument_signatures = [
1333 Sig('foo', nargs='?'),
1334 Sig('bar', nargs='*'),
1335 Sig('--baz', action='store_true'),
1336 ]
1337 failures = ['-x']
1338 successes = [
1339 ('', NS()),
1340 ('a', NS(foo='a')),
1341 ('a b', NS(foo='a', bar=['b'])),
1342 ('--baz', NS(baz=True)),
1343 ('a --baz', NS(foo='a', baz=True)),
1344 ('--baz a b', NS(foo='a', bar=['b'], baz=True)),
1345 ]
1346
1347
1348class TestParserDefault42(ParserTestCase):
1349 """Test actions with a parser-level default of 42"""
1350
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001351 parser_signature = Sig(argument_default=42)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001352 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001353 Sig('--version', action='version', version='1.0'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001354 Sig('foo', nargs='?'),
1355 Sig('bar', nargs='*'),
1356 Sig('--baz', action='store_true'),
1357 ]
1358 failures = ['-x']
1359 successes = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001360 ('', NS(foo=42, bar=42, baz=42, version=42)),
1361 ('a', NS(foo='a', bar=42, baz=42, version=42)),
1362 ('a b', NS(foo='a', bar=['b'], baz=42, version=42)),
1363 ('--baz', NS(foo=42, bar=42, baz=True, version=42)),
1364 ('a --baz', NS(foo='a', bar=42, baz=True, version=42)),
1365 ('--baz a b', NS(foo='a', bar=['b'], baz=True, version=42)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001366 ]
1367
1368
1369class TestArgumentsFromFile(TempDirMixin, ParserTestCase):
1370 """Test reading arguments from a file"""
1371
1372 def setUp(self):
1373 super(TestArgumentsFromFile, self).setUp()
1374 file_texts = [
1375 ('hello', 'hello world!\n'),
1376 ('recursive', '-a\n'
1377 'A\n'
1378 '@hello'),
1379 ('invalid', '@no-such-path\n'),
1380 ]
1381 for path, text in file_texts:
1382 file = open(path, 'w')
1383 file.write(text)
1384 file.close()
1385
1386 parser_signature = Sig(fromfile_prefix_chars='@')
1387 argument_signatures = [
1388 Sig('-a'),
1389 Sig('x'),
1390 Sig('y', nargs='+'),
1391 ]
1392 failures = ['', '-b', 'X', '@invalid', '@missing']
1393 successes = [
1394 ('X Y', NS(a=None, x='X', y=['Y'])),
1395 ('X -a A Y Z', NS(a='A', x='X', y=['Y', 'Z'])),
1396 ('@hello X', NS(a=None, x='hello world!', y=['X'])),
1397 ('X @hello', NS(a=None, x='X', y=['hello world!'])),
1398 ('-a B @recursive Y Z', NS(a='A', x='hello world!', y=['Y', 'Z'])),
1399 ('X @recursive Z -a B', NS(a='B', x='X', y=['hello world!', 'Z'])),
R David Murrayb94082a2012-07-21 22:20:11 -04001400 (["-a", "", "X", "Y"], NS(a='', x='X', y=['Y'])),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001401 ]
1402
1403
1404class TestArgumentsFromFileConverter(TempDirMixin, ParserTestCase):
1405 """Test reading arguments from a file"""
1406
1407 def setUp(self):
1408 super(TestArgumentsFromFileConverter, self).setUp()
1409 file_texts = [
1410 ('hello', 'hello world!\n'),
1411 ]
1412 for path, text in file_texts:
1413 file = open(path, 'w')
1414 file.write(text)
1415 file.close()
1416
1417 class FromFileConverterArgumentParser(ErrorRaisingArgumentParser):
1418
1419 def convert_arg_line_to_args(self, arg_line):
1420 for arg in arg_line.split():
1421 if not arg.strip():
1422 continue
1423 yield arg
1424 parser_class = FromFileConverterArgumentParser
1425 parser_signature = Sig(fromfile_prefix_chars='@')
1426 argument_signatures = [
1427 Sig('y', nargs='+'),
1428 ]
1429 failures = []
1430 successes = [
1431 ('@hello X', NS(y=['hello', 'world!', 'X'])),
1432 ]
1433
1434
1435# =====================
1436# Type conversion tests
1437# =====================
1438
1439class TestFileTypeRepr(TestCase):
1440
1441 def test_r(self):
1442 type = argparse.FileType('r')
1443 self.assertEqual("FileType('r')", repr(type))
1444
1445 def test_wb_1(self):
1446 type = argparse.FileType('wb', 1)
1447 self.assertEqual("FileType('wb', 1)", repr(type))
1448
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001449 def test_r_latin(self):
1450 type = argparse.FileType('r', encoding='latin_1')
1451 self.assertEqual("FileType('r', encoding='latin_1')", repr(type))
1452
1453 def test_w_big5_ignore(self):
1454 type = argparse.FileType('w', encoding='big5', errors='ignore')
1455 self.assertEqual("FileType('w', encoding='big5', errors='ignore')",
1456 repr(type))
1457
1458 def test_r_1_replace(self):
1459 type = argparse.FileType('r', 1, errors='replace')
1460 self.assertEqual("FileType('r', 1, errors='replace')", repr(type))
1461
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001462
1463class RFile(object):
1464 seen = {}
1465
1466 def __init__(self, name):
1467 self.name = name
1468
1469 def __eq__(self, other):
1470 if other in self.seen:
1471 text = self.seen[other]
1472 else:
1473 text = self.seen[other] = other.read()
1474 other.close()
1475 if not isinstance(text, str):
1476 text = text.decode('ascii')
1477 return self.name == other.name == text
1478
1479
1480class TestFileTypeR(TempDirMixin, ParserTestCase):
1481 """Test the FileType option/argument type for reading files"""
1482
1483 def setUp(self):
1484 super(TestFileTypeR, self).setUp()
1485 for file_name in ['foo', 'bar']:
1486 file = open(os.path.join(self.temp_dir, file_name), 'w')
1487 file.write(file_name)
1488 file.close()
Steven Bethardb0270112011-01-24 21:02:50 +00001489 self.create_readonly_file('readonly')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001490
1491 argument_signatures = [
1492 Sig('-x', type=argparse.FileType()),
1493 Sig('spam', type=argparse.FileType('r')),
1494 ]
Steven Bethardb0270112011-01-24 21:02:50 +00001495 failures = ['-x', '', 'non-existent-file.txt']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001496 successes = [
1497 ('foo', NS(x=None, spam=RFile('foo'))),
1498 ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
1499 ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
1500 ('-x - -', NS(x=sys.stdin, spam=sys.stdin)),
Steven Bethardb0270112011-01-24 21:02:50 +00001501 ('readonly', NS(x=None, spam=RFile('readonly'))),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001502 ]
1503
R David Murray6fb8fb12012-08-31 22:45:20 -04001504class TestFileTypeDefaults(TempDirMixin, ParserTestCase):
1505 """Test that a file is not created unless the default is needed"""
1506 def setUp(self):
1507 super(TestFileTypeDefaults, self).setUp()
1508 file = open(os.path.join(self.temp_dir, 'good'), 'w')
1509 file.write('good')
1510 file.close()
1511
1512 argument_signatures = [
1513 Sig('-c', type=argparse.FileType('r'), default='no-file.txt'),
1514 ]
1515 # should provoke no such file error
1516 failures = ['']
1517 # should not provoke error because default file is created
1518 successes = [('-c good', NS(c=RFile('good')))]
1519
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001520
1521class TestFileTypeRB(TempDirMixin, ParserTestCase):
1522 """Test the FileType option/argument type for reading files"""
1523
1524 def setUp(self):
1525 super(TestFileTypeRB, self).setUp()
1526 for file_name in ['foo', 'bar']:
1527 file = open(os.path.join(self.temp_dir, file_name), 'w')
1528 file.write(file_name)
1529 file.close()
1530
1531 argument_signatures = [
1532 Sig('-x', type=argparse.FileType('rb')),
1533 Sig('spam', type=argparse.FileType('rb')),
1534 ]
1535 failures = ['-x', '']
1536 successes = [
1537 ('foo', NS(x=None, spam=RFile('foo'))),
1538 ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
1539 ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
1540 ('-x - -', NS(x=sys.stdin, spam=sys.stdin)),
1541 ]
1542
1543
1544class WFile(object):
1545 seen = set()
1546
1547 def __init__(self, name):
1548 self.name = name
1549
1550 def __eq__(self, other):
1551 if other not in self.seen:
1552 text = 'Check that file is writable.'
1553 if 'b' in other.mode:
1554 text = text.encode('ascii')
1555 other.write(text)
1556 other.close()
1557 self.seen.add(other)
1558 return self.name == other.name
1559
1560
Victor Stinnera04b39b2011-11-20 23:09:09 +01001561@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
1562 "non-root user required")
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001563class TestFileTypeW(TempDirMixin, ParserTestCase):
1564 """Test the FileType option/argument type for writing files"""
1565
Steven Bethardb0270112011-01-24 21:02:50 +00001566 def setUp(self):
1567 super(TestFileTypeW, self).setUp()
1568 self.create_readonly_file('readonly')
1569
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001570 argument_signatures = [
1571 Sig('-x', type=argparse.FileType('w')),
1572 Sig('spam', type=argparse.FileType('w')),
1573 ]
Steven Bethardb0270112011-01-24 21:02:50 +00001574 failures = ['-x', '', 'readonly']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001575 successes = [
1576 ('foo', NS(x=None, spam=WFile('foo'))),
1577 ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
1578 ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))),
1579 ('-x - -', NS(x=sys.stdout, spam=sys.stdout)),
1580 ]
1581
1582
1583class TestFileTypeWB(TempDirMixin, ParserTestCase):
1584
1585 argument_signatures = [
1586 Sig('-x', type=argparse.FileType('wb')),
1587 Sig('spam', type=argparse.FileType('wb')),
1588 ]
1589 failures = ['-x', '']
1590 successes = [
1591 ('foo', NS(x=None, spam=WFile('foo'))),
1592 ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
1593 ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))),
1594 ('-x - -', NS(x=sys.stdout, spam=sys.stdout)),
1595 ]
1596
1597
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001598class TestFileTypeOpenArgs(TestCase):
1599 """Test that open (the builtin) is correctly called"""
1600
1601 def test_open_args(self):
1602 FT = argparse.FileType
1603 cases = [
1604 (FT('rb'), ('rb', -1, None, None)),
1605 (FT('w', 1), ('w', 1, None, None)),
1606 (FT('w', errors='replace'), ('w', -1, None, 'replace')),
1607 (FT('wb', encoding='big5'), ('wb', -1, 'big5', None)),
1608 (FT('w', 0, 'l1', 'strict'), ('w', 0, 'l1', 'strict')),
1609 ]
1610 with mock.patch('builtins.open') as m:
1611 for type, args in cases:
1612 type('foo')
1613 m.assert_called_with('foo', *args)
1614
1615
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001616class TestTypeCallable(ParserTestCase):
1617 """Test some callables as option/argument types"""
1618
1619 argument_signatures = [
1620 Sig('--eggs', type=complex),
1621 Sig('spam', type=float),
1622 ]
1623 failures = ['a', '42j', '--eggs a', '--eggs 2i']
1624 successes = [
1625 ('--eggs=42 42', NS(eggs=42, spam=42.0)),
1626 ('--eggs 2j -- -1.5', NS(eggs=2j, spam=-1.5)),
1627 ('1024.675', NS(eggs=None, spam=1024.675)),
1628 ]
1629
1630
1631class TestTypeUserDefined(ParserTestCase):
1632 """Test a user-defined option/argument type"""
1633
1634 class MyType(TestCase):
1635
1636 def __init__(self, value):
1637 self.value = value
1638
1639 def __eq__(self, other):
1640 return (type(self), self.value) == (type(other), other.value)
1641
1642 argument_signatures = [
1643 Sig('-x', type=MyType),
1644 Sig('spam', type=MyType),
1645 ]
1646 failures = []
1647 successes = [
1648 ('a -x b', NS(x=MyType('b'), spam=MyType('a'))),
1649 ('-xf g', NS(x=MyType('f'), spam=MyType('g'))),
1650 ]
1651
1652
1653class TestTypeClassicClass(ParserTestCase):
1654 """Test a classic class type"""
1655
1656 class C:
1657
1658 def __init__(self, value):
1659 self.value = value
1660
1661 def __eq__(self, other):
1662 return (type(self), self.value) == (type(other), other.value)
1663
1664 argument_signatures = [
1665 Sig('-x', type=C),
1666 Sig('spam', type=C),
1667 ]
1668 failures = []
1669 successes = [
1670 ('a -x b', NS(x=C('b'), spam=C('a'))),
1671 ('-xf g', NS(x=C('f'), spam=C('g'))),
1672 ]
1673
1674
1675class TestTypeRegistration(TestCase):
1676 """Test a user-defined type by registering it"""
1677
1678 def test(self):
1679
1680 def get_my_type(string):
1681 return 'my_type{%s}' % string
1682
1683 parser = argparse.ArgumentParser()
1684 parser.register('type', 'my_type', get_my_type)
1685 parser.add_argument('-x', type='my_type')
1686 parser.add_argument('y', type='my_type')
1687
1688 self.assertEqual(parser.parse_args('1'.split()),
1689 NS(x=None, y='my_type{1}'))
1690 self.assertEqual(parser.parse_args('-x 1 42'.split()),
1691 NS(x='my_type{1}', y='my_type{42}'))
1692
1693
1694# ============
1695# Action tests
1696# ============
1697
1698class TestActionUserDefined(ParserTestCase):
1699 """Test a user-defined option/argument action"""
1700
1701 class OptionalAction(argparse.Action):
1702
1703 def __call__(self, parser, namespace, value, option_string=None):
1704 try:
1705 # check destination and option string
1706 assert self.dest == 'spam', 'dest: %s' % self.dest
1707 assert option_string == '-s', 'flag: %s' % option_string
1708 # when option is before argument, badger=2, and when
1709 # option is after argument, badger=<whatever was set>
1710 expected_ns = NS(spam=0.25)
1711 if value in [0.125, 0.625]:
1712 expected_ns.badger = 2
1713 elif value in [2.0]:
1714 expected_ns.badger = 84
1715 else:
1716 raise AssertionError('value: %s' % value)
1717 assert expected_ns == namespace, ('expected %s, got %s' %
1718 (expected_ns, namespace))
1719 except AssertionError:
1720 e = sys.exc_info()[1]
1721 raise ArgumentParserError('opt_action failed: %s' % e)
1722 setattr(namespace, 'spam', value)
1723
1724 class PositionalAction(argparse.Action):
1725
1726 def __call__(self, parser, namespace, value, option_string=None):
1727 try:
1728 assert option_string is None, ('option_string: %s' %
1729 option_string)
1730 # check destination
1731 assert self.dest == 'badger', 'dest: %s' % self.dest
1732 # when argument is before option, spam=0.25, and when
1733 # option is after argument, spam=<whatever was set>
1734 expected_ns = NS(badger=2)
1735 if value in [42, 84]:
1736 expected_ns.spam = 0.25
1737 elif value in [1]:
1738 expected_ns.spam = 0.625
1739 elif value in [2]:
1740 expected_ns.spam = 0.125
1741 else:
1742 raise AssertionError('value: %s' % value)
1743 assert expected_ns == namespace, ('expected %s, got %s' %
1744 (expected_ns, namespace))
1745 except AssertionError:
1746 e = sys.exc_info()[1]
1747 raise ArgumentParserError('arg_action failed: %s' % e)
1748 setattr(namespace, 'badger', value)
1749
1750 argument_signatures = [
1751 Sig('-s', dest='spam', action=OptionalAction,
1752 type=float, default=0.25),
1753 Sig('badger', action=PositionalAction,
1754 type=int, nargs='?', default=2),
1755 ]
1756 failures = []
1757 successes = [
1758 ('-s0.125', NS(spam=0.125, badger=2)),
1759 ('42', NS(spam=0.25, badger=42)),
1760 ('-s 0.625 1', NS(spam=0.625, badger=1)),
1761 ('84 -s2', NS(spam=2.0, badger=84)),
1762 ]
1763
1764
1765class TestActionRegistration(TestCase):
1766 """Test a user-defined action supplied by registering it"""
1767
1768 class MyAction(argparse.Action):
1769
1770 def __call__(self, parser, namespace, values, option_string=None):
1771 setattr(namespace, self.dest, 'foo[%s]' % values)
1772
1773 def test(self):
1774
1775 parser = argparse.ArgumentParser()
1776 parser.register('action', 'my_action', self.MyAction)
1777 parser.add_argument('badger', action='my_action')
1778
1779 self.assertEqual(parser.parse_args(['1']), NS(badger='foo[1]'))
1780 self.assertEqual(parser.parse_args(['42']), NS(badger='foo[42]'))
1781
1782
1783# ================
1784# Subparsers tests
1785# ================
1786
1787class TestAddSubparsers(TestCase):
1788 """Test the add_subparsers method"""
1789
1790 def assertArgumentParserError(self, *args, **kwargs):
1791 self.assertRaises(ArgumentParserError, *args, **kwargs)
1792
Steven Bethardfd311a72010-12-18 11:19:23 +00001793 def _get_parser(self, subparser_help=False, prefix_chars=None,
1794 aliases=False):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001795 # create a parser with a subparsers argument
R. David Murray88c49fe2010-08-03 17:56:09 +00001796 if prefix_chars:
1797 parser = ErrorRaisingArgumentParser(
1798 prog='PROG', description='main description', prefix_chars=prefix_chars)
1799 parser.add_argument(
1800 prefix_chars[0] * 2 + 'foo', action='store_true', help='foo help')
1801 else:
1802 parser = ErrorRaisingArgumentParser(
1803 prog='PROG', description='main description')
1804 parser.add_argument(
1805 '--foo', action='store_true', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001806 parser.add_argument(
1807 'bar', type=float, help='bar help')
1808
1809 # check that only one subparsers argument can be added
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001810 subparsers_kwargs = {'required': False}
Steven Bethardfd311a72010-12-18 11:19:23 +00001811 if aliases:
1812 subparsers_kwargs['metavar'] = 'COMMAND'
1813 subparsers_kwargs['title'] = 'commands'
1814 else:
1815 subparsers_kwargs['help'] = 'command help'
1816 subparsers = parser.add_subparsers(**subparsers_kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001817 self.assertArgumentParserError(parser.add_subparsers)
1818
1819 # add first sub-parser
1820 parser1_kwargs = dict(description='1 description')
1821 if subparser_help:
1822 parser1_kwargs['help'] = '1 help'
Steven Bethardfd311a72010-12-18 11:19:23 +00001823 if aliases:
1824 parser1_kwargs['aliases'] = ['1alias1', '1alias2']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001825 parser1 = subparsers.add_parser('1', **parser1_kwargs)
1826 parser1.add_argument('-w', type=int, help='w help')
1827 parser1.add_argument('x', choices='abc', help='x help')
1828
1829 # add second sub-parser
1830 parser2_kwargs = dict(description='2 description')
1831 if subparser_help:
1832 parser2_kwargs['help'] = '2 help'
1833 parser2 = subparsers.add_parser('2', **parser2_kwargs)
1834 parser2.add_argument('-y', choices='123', help='y help')
1835 parser2.add_argument('z', type=complex, nargs='*', help='z help')
1836
R David Murray00528e82012-07-21 22:48:35 -04001837 # add third sub-parser
1838 parser3_kwargs = dict(description='3 description')
1839 if subparser_help:
1840 parser3_kwargs['help'] = '3 help'
1841 parser3 = subparsers.add_parser('3', **parser3_kwargs)
1842 parser3.add_argument('t', type=int, help='t help')
1843 parser3.add_argument('u', nargs='...', help='u help')
1844
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001845 # return the main parser
1846 return parser
1847
1848 def setUp(self):
Steven Bethard1f1c2472010-11-01 13:56:09 +00001849 super().setUp()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001850 self.parser = self._get_parser()
1851 self.command_help_parser = self._get_parser(subparser_help=True)
1852
1853 def test_parse_args_failures(self):
1854 # check some failure cases:
1855 for args_str in ['', 'a', 'a a', '0.5 a', '0.5 1',
1856 '0.5 1 -y', '0.5 2 -w']:
1857 args = args_str.split()
1858 self.assertArgumentParserError(self.parser.parse_args, args)
1859
1860 def test_parse_args(self):
1861 # check some non-failure cases:
1862 self.assertEqual(
1863 self.parser.parse_args('0.5 1 b -w 7'.split()),
1864 NS(foo=False, bar=0.5, w=7, x='b'),
1865 )
1866 self.assertEqual(
1867 self.parser.parse_args('0.25 --foo 2 -y 2 3j -- -1j'.split()),
1868 NS(foo=True, bar=0.25, y='2', z=[3j, -1j]),
1869 )
1870 self.assertEqual(
1871 self.parser.parse_args('--foo 0.125 1 c'.split()),
1872 NS(foo=True, bar=0.125, w=None, x='c'),
1873 )
R David Murray00528e82012-07-21 22:48:35 -04001874 self.assertEqual(
1875 self.parser.parse_args('-1.5 3 11 -- a --foo 7 -- b'.split()),
1876 NS(foo=False, bar=-1.5, t=11, u=['a', '--foo', '7', '--', 'b']),
1877 )
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001878
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001879 def test_parse_known_args(self):
1880 self.assertEqual(
1881 self.parser.parse_known_args('0.5 1 b -w 7'.split()),
1882 (NS(foo=False, bar=0.5, w=7, x='b'), []),
1883 )
1884 self.assertEqual(
1885 self.parser.parse_known_args('0.5 -p 1 b -w 7'.split()),
1886 (NS(foo=False, bar=0.5, w=7, x='b'), ['-p']),
1887 )
1888 self.assertEqual(
1889 self.parser.parse_known_args('0.5 1 b -w 7 -p'.split()),
1890 (NS(foo=False, bar=0.5, w=7, x='b'), ['-p']),
1891 )
1892 self.assertEqual(
1893 self.parser.parse_known_args('0.5 1 b -q -rs -w 7'.split()),
1894 (NS(foo=False, bar=0.5, w=7, x='b'), ['-q', '-rs']),
1895 )
1896 self.assertEqual(
1897 self.parser.parse_known_args('0.5 -W 1 b -X Y -w 7 Z'.split()),
1898 (NS(foo=False, bar=0.5, w=7, x='b'), ['-W', '-X', 'Y', 'Z']),
1899 )
1900
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001901 def test_dest(self):
1902 parser = ErrorRaisingArgumentParser()
1903 parser.add_argument('--foo', action='store_true')
1904 subparsers = parser.add_subparsers(dest='bar')
1905 parser1 = subparsers.add_parser('1')
1906 parser1.add_argument('baz')
1907 self.assertEqual(NS(foo=False, bar='1', baz='2'),
1908 parser.parse_args('1 2'.split()))
1909
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001910 def _test_required_subparsers(self, parser):
1911 # Should parse the sub command
1912 ret = parser.parse_args(['run'])
1913 self.assertEqual(ret.command, 'run')
1914
1915 # Error when the command is missing
1916 self.assertArgumentParserError(parser.parse_args, ())
1917
1918 def test_required_subparsers_via_attribute(self):
1919 parser = ErrorRaisingArgumentParser()
1920 subparsers = parser.add_subparsers(dest='command')
1921 subparsers.required = True
1922 subparsers.add_parser('run')
1923 self._test_required_subparsers(parser)
1924
1925 def test_required_subparsers_via_kwarg(self):
1926 parser = ErrorRaisingArgumentParser()
1927 subparsers = parser.add_subparsers(dest='command', required=True)
1928 subparsers.add_parser('run')
1929 self._test_required_subparsers(parser)
1930
1931 def test_required_subparsers_default(self):
1932 parser = ErrorRaisingArgumentParser()
1933 subparsers = parser.add_subparsers(dest='command')
1934 subparsers.add_parser('run')
Miss Islington (bot)dd7a2552018-05-23 19:22:46 -07001935 # No error here
1936 ret = parser.parse_args(())
1937 self.assertIsNone(ret.command)
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001938
1939 def test_optional_subparsers(self):
1940 parser = ErrorRaisingArgumentParser()
1941 subparsers = parser.add_subparsers(dest='command', required=False)
1942 subparsers.add_parser('run')
1943 # No error here
1944 ret = parser.parse_args(())
1945 self.assertIsNone(ret.command)
1946
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001947 def test_help(self):
1948 self.assertEqual(self.parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01001949 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001950 self.assertEqual(self.parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01001951 usage: PROG [-h] [--foo] bar {1,2,3} ...
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001952
1953 main description
1954
1955 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01001956 bar bar help
1957 {1,2,3} command help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001958
1959 optional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01001960 -h, --help show this help message and exit
1961 --foo foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001962 '''))
1963
R. David Murray88c49fe2010-08-03 17:56:09 +00001964 def test_help_extra_prefix_chars(self):
1965 # Make sure - is still used for help if it is a non-first prefix char
1966 parser = self._get_parser(prefix_chars='+:-')
1967 self.assertEqual(parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01001968 'usage: PROG [-h] [++foo] bar {1,2,3} ...\n')
R. David Murray88c49fe2010-08-03 17:56:09 +00001969 self.assertEqual(parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01001970 usage: PROG [-h] [++foo] bar {1,2,3} ...
R. David Murray88c49fe2010-08-03 17:56:09 +00001971
1972 main description
1973
1974 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01001975 bar bar help
1976 {1,2,3} command help
R. David Murray88c49fe2010-08-03 17:56:09 +00001977
1978 optional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01001979 -h, --help show this help message and exit
1980 ++foo foo help
R. David Murray88c49fe2010-08-03 17:56:09 +00001981 '''))
1982
Xiang Zhang7fe28ad2017-01-22 14:37:22 +08001983 def test_help_non_breaking_spaces(self):
1984 parser = ErrorRaisingArgumentParser(
1985 prog='PROG', description='main description')
1986 parser.add_argument(
1987 "--non-breaking", action='store_false',
1988 help='help message containing non-breaking spaces shall not '
1989 'wrap\N{NO-BREAK SPACE}at non-breaking spaces')
1990 self.assertEqual(parser.format_help(), textwrap.dedent('''\
1991 usage: PROG [-h] [--non-breaking]
1992
1993 main description
1994
1995 optional arguments:
1996 -h, --help show this help message and exit
1997 --non-breaking help message containing non-breaking spaces shall not
1998 wrap\N{NO-BREAK SPACE}at non-breaking spaces
1999 '''))
R. David Murray88c49fe2010-08-03 17:56:09 +00002000
2001 def test_help_alternate_prefix_chars(self):
2002 parser = self._get_parser(prefix_chars='+:/')
2003 self.assertEqual(parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002004 'usage: PROG [+h] [++foo] bar {1,2,3} ...\n')
R. David Murray88c49fe2010-08-03 17:56:09 +00002005 self.assertEqual(parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002006 usage: PROG [+h] [++foo] bar {1,2,3} ...
R. David Murray88c49fe2010-08-03 17:56:09 +00002007
2008 main description
2009
2010 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002011 bar bar help
2012 {1,2,3} command help
R. David Murray88c49fe2010-08-03 17:56:09 +00002013
2014 optional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002015 +h, ++help show this help message and exit
2016 ++foo foo help
R. David Murray88c49fe2010-08-03 17:56:09 +00002017 '''))
2018
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002019 def test_parser_command_help(self):
2020 self.assertEqual(self.command_help_parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002021 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002022 self.assertEqual(self.command_help_parser.format_help(),
2023 textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002024 usage: PROG [-h] [--foo] bar {1,2,3} ...
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002025
2026 main description
2027
2028 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002029 bar bar help
2030 {1,2,3} command help
2031 1 1 help
2032 2 2 help
2033 3 3 help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002034
2035 optional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002036 -h, --help show this help message and exit
2037 --foo foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002038 '''))
2039
2040 def test_subparser_title_help(self):
2041 parser = ErrorRaisingArgumentParser(prog='PROG',
2042 description='main description')
2043 parser.add_argument('--foo', action='store_true', help='foo help')
2044 parser.add_argument('bar', help='bar help')
2045 subparsers = parser.add_subparsers(title='subcommands',
2046 description='command help',
2047 help='additional text')
2048 parser1 = subparsers.add_parser('1')
2049 parser2 = subparsers.add_parser('2')
2050 self.assertEqual(parser.format_usage(),
2051 'usage: PROG [-h] [--foo] bar {1,2} ...\n')
2052 self.assertEqual(parser.format_help(), textwrap.dedent('''\
2053 usage: PROG [-h] [--foo] bar {1,2} ...
2054
2055 main description
2056
2057 positional arguments:
2058 bar bar help
2059
2060 optional arguments:
2061 -h, --help show this help message and exit
2062 --foo foo help
2063
2064 subcommands:
2065 command help
2066
2067 {1,2} additional text
2068 '''))
2069
2070 def _test_subparser_help(self, args_str, expected_help):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002071 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002072 self.parser.parse_args(args_str.split())
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002073 self.assertEqual(expected_help, cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002074
2075 def test_subparser1_help(self):
2076 self._test_subparser_help('5.0 1 -h', textwrap.dedent('''\
2077 usage: PROG bar 1 [-h] [-w W] {a,b,c}
2078
2079 1 description
2080
2081 positional arguments:
2082 {a,b,c} x help
2083
2084 optional arguments:
2085 -h, --help show this help message and exit
2086 -w W w help
2087 '''))
2088
2089 def test_subparser2_help(self):
2090 self._test_subparser_help('5.0 2 -h', textwrap.dedent('''\
2091 usage: PROG bar 2 [-h] [-y {1,2,3}] [z [z ...]]
2092
2093 2 description
2094
2095 positional arguments:
2096 z z help
2097
2098 optional arguments:
2099 -h, --help show this help message and exit
2100 -y {1,2,3} y help
2101 '''))
2102
Steven Bethardfd311a72010-12-18 11:19:23 +00002103 def test_alias_invocation(self):
2104 parser = self._get_parser(aliases=True)
2105 self.assertEqual(
2106 parser.parse_known_args('0.5 1alias1 b'.split()),
2107 (NS(foo=False, bar=0.5, w=None, x='b'), []),
2108 )
2109 self.assertEqual(
2110 parser.parse_known_args('0.5 1alias2 b'.split()),
2111 (NS(foo=False, bar=0.5, w=None, x='b'), []),
2112 )
2113
2114 def test_error_alias_invocation(self):
2115 parser = self._get_parser(aliases=True)
2116 self.assertArgumentParserError(parser.parse_args,
2117 '0.5 1alias3 b'.split())
2118
2119 def test_alias_help(self):
2120 parser = self._get_parser(aliases=True, subparser_help=True)
2121 self.maxDiff = None
2122 self.assertEqual(parser.format_help(), textwrap.dedent("""\
2123 usage: PROG [-h] [--foo] bar COMMAND ...
2124
2125 main description
2126
2127 positional arguments:
2128 bar bar help
2129
2130 optional arguments:
2131 -h, --help show this help message and exit
2132 --foo foo help
2133
2134 commands:
2135 COMMAND
2136 1 (1alias1, 1alias2)
2137 1 help
2138 2 2 help
R David Murray00528e82012-07-21 22:48:35 -04002139 3 3 help
Steven Bethardfd311a72010-12-18 11:19:23 +00002140 """))
2141
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002142# ============
2143# Groups tests
2144# ============
2145
2146class TestPositionalsGroups(TestCase):
2147 """Tests that order of group positionals matches construction order"""
2148
2149 def test_nongroup_first(self):
2150 parser = ErrorRaisingArgumentParser()
2151 parser.add_argument('foo')
2152 group = parser.add_argument_group('g')
2153 group.add_argument('bar')
2154 parser.add_argument('baz')
2155 expected = NS(foo='1', bar='2', baz='3')
2156 result = parser.parse_args('1 2 3'.split())
2157 self.assertEqual(expected, result)
2158
2159 def test_group_first(self):
2160 parser = ErrorRaisingArgumentParser()
2161 group = parser.add_argument_group('xxx')
2162 group.add_argument('foo')
2163 parser.add_argument('bar')
2164 parser.add_argument('baz')
2165 expected = NS(foo='1', bar='2', baz='3')
2166 result = parser.parse_args('1 2 3'.split())
2167 self.assertEqual(expected, result)
2168
2169 def test_interleaved_groups(self):
2170 parser = ErrorRaisingArgumentParser()
2171 group = parser.add_argument_group('xxx')
2172 parser.add_argument('foo')
2173 group.add_argument('bar')
2174 parser.add_argument('baz')
2175 group = parser.add_argument_group('yyy')
2176 group.add_argument('frell')
2177 expected = NS(foo='1', bar='2', baz='3', frell='4')
2178 result = parser.parse_args('1 2 3 4'.split())
2179 self.assertEqual(expected, result)
2180
2181# ===================
2182# Parent parser tests
2183# ===================
2184
2185class TestParentParsers(TestCase):
2186 """Tests that parsers can be created with parent parsers"""
2187
2188 def assertArgumentParserError(self, *args, **kwargs):
2189 self.assertRaises(ArgumentParserError, *args, **kwargs)
2190
2191 def setUp(self):
Steven Bethard1f1c2472010-11-01 13:56:09 +00002192 super().setUp()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002193 self.wxyz_parent = ErrorRaisingArgumentParser(add_help=False)
2194 self.wxyz_parent.add_argument('--w')
2195 x_group = self.wxyz_parent.add_argument_group('x')
2196 x_group.add_argument('-y')
2197 self.wxyz_parent.add_argument('z')
2198
2199 self.abcd_parent = ErrorRaisingArgumentParser(add_help=False)
2200 self.abcd_parent.add_argument('a')
2201 self.abcd_parent.add_argument('-b')
2202 c_group = self.abcd_parent.add_argument_group('c')
2203 c_group.add_argument('--d')
2204
2205 self.w_parent = ErrorRaisingArgumentParser(add_help=False)
2206 self.w_parent.add_argument('--w')
2207
2208 self.z_parent = ErrorRaisingArgumentParser(add_help=False)
2209 self.z_parent.add_argument('z')
2210
2211 # parents with mutually exclusive groups
2212 self.ab_mutex_parent = ErrorRaisingArgumentParser(add_help=False)
2213 group = self.ab_mutex_parent.add_mutually_exclusive_group()
2214 group.add_argument('-a', action='store_true')
2215 group.add_argument('-b', action='store_true')
2216
2217 self.main_program = os.path.basename(sys.argv[0])
2218
2219 def test_single_parent(self):
2220 parser = ErrorRaisingArgumentParser(parents=[self.wxyz_parent])
2221 self.assertEqual(parser.parse_args('-y 1 2 --w 3'.split()),
2222 NS(w='3', y='1', z='2'))
2223
2224 def test_single_parent_mutex(self):
2225 self._test_mutex_ab(self.ab_mutex_parent.parse_args)
2226 parser = ErrorRaisingArgumentParser(parents=[self.ab_mutex_parent])
2227 self._test_mutex_ab(parser.parse_args)
2228
2229 def test_single_granparent_mutex(self):
2230 parents = [self.ab_mutex_parent]
2231 parser = ErrorRaisingArgumentParser(add_help=False, parents=parents)
2232 parser = ErrorRaisingArgumentParser(parents=[parser])
2233 self._test_mutex_ab(parser.parse_args)
2234
2235 def _test_mutex_ab(self, parse_args):
2236 self.assertEqual(parse_args([]), NS(a=False, b=False))
2237 self.assertEqual(parse_args(['-a']), NS(a=True, b=False))
2238 self.assertEqual(parse_args(['-b']), NS(a=False, b=True))
2239 self.assertArgumentParserError(parse_args, ['-a', '-b'])
2240 self.assertArgumentParserError(parse_args, ['-b', '-a'])
2241 self.assertArgumentParserError(parse_args, ['-c'])
2242 self.assertArgumentParserError(parse_args, ['-a', '-c'])
2243 self.assertArgumentParserError(parse_args, ['-b', '-c'])
2244
2245 def test_multiple_parents(self):
2246 parents = [self.abcd_parent, self.wxyz_parent]
2247 parser = ErrorRaisingArgumentParser(parents=parents)
2248 self.assertEqual(parser.parse_args('--d 1 --w 2 3 4'.split()),
2249 NS(a='3', b=None, d='1', w='2', y=None, z='4'))
2250
2251 def test_multiple_parents_mutex(self):
2252 parents = [self.ab_mutex_parent, self.wxyz_parent]
2253 parser = ErrorRaisingArgumentParser(parents=parents)
2254 self.assertEqual(parser.parse_args('-a --w 2 3'.split()),
2255 NS(a=True, b=False, w='2', y=None, z='3'))
2256 self.assertArgumentParserError(
2257 parser.parse_args, '-a --w 2 3 -b'.split())
2258 self.assertArgumentParserError(
2259 parser.parse_args, '-a -b --w 2 3'.split())
2260
2261 def test_conflicting_parents(self):
2262 self.assertRaises(
2263 argparse.ArgumentError,
2264 argparse.ArgumentParser,
2265 parents=[self.w_parent, self.wxyz_parent])
2266
2267 def test_conflicting_parents_mutex(self):
2268 self.assertRaises(
2269 argparse.ArgumentError,
2270 argparse.ArgumentParser,
2271 parents=[self.abcd_parent, self.ab_mutex_parent])
2272
2273 def test_same_argument_name_parents(self):
2274 parents = [self.wxyz_parent, self.z_parent]
2275 parser = ErrorRaisingArgumentParser(parents=parents)
2276 self.assertEqual(parser.parse_args('1 2'.split()),
2277 NS(w=None, y=None, z='2'))
2278
2279 def test_subparser_parents(self):
2280 parser = ErrorRaisingArgumentParser()
2281 subparsers = parser.add_subparsers()
2282 abcde_parser = subparsers.add_parser('bar', parents=[self.abcd_parent])
2283 abcde_parser.add_argument('e')
2284 self.assertEqual(parser.parse_args('bar -b 1 --d 2 3 4'.split()),
2285 NS(a='3', b='1', d='2', e='4'))
2286
2287 def test_subparser_parents_mutex(self):
2288 parser = ErrorRaisingArgumentParser()
2289 subparsers = parser.add_subparsers()
2290 parents = [self.ab_mutex_parent]
2291 abc_parser = subparsers.add_parser('foo', parents=parents)
2292 c_group = abc_parser.add_argument_group('c_group')
2293 c_group.add_argument('c')
2294 parents = [self.wxyz_parent, self.ab_mutex_parent]
2295 wxyzabe_parser = subparsers.add_parser('bar', parents=parents)
2296 wxyzabe_parser.add_argument('e')
2297 self.assertEqual(parser.parse_args('foo -a 4'.split()),
2298 NS(a=True, b=False, c='4'))
2299 self.assertEqual(parser.parse_args('bar -b --w 2 3 4'.split()),
2300 NS(a=False, b=True, w='2', y=None, z='3', e='4'))
2301 self.assertArgumentParserError(
2302 parser.parse_args, 'foo -a -b 4'.split())
2303 self.assertArgumentParserError(
2304 parser.parse_args, 'bar -b -a 4'.split())
2305
2306 def test_parent_help(self):
2307 parents = [self.abcd_parent, self.wxyz_parent]
2308 parser = ErrorRaisingArgumentParser(parents=parents)
2309 parser_help = parser.format_help()
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002310 progname = self.main_program
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002311 self.assertEqual(parser_help, textwrap.dedent('''\
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002312 usage: {}{}[-h] [-b B] [--d D] [--w W] [-y Y] a z
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002313
2314 positional arguments:
2315 a
2316 z
2317
2318 optional arguments:
2319 -h, --help show this help message and exit
2320 -b B
2321 --w W
2322
2323 c:
2324 --d D
2325
2326 x:
2327 -y Y
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002328 '''.format(progname, ' ' if progname else '' )))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002329
2330 def test_groups_parents(self):
2331 parent = ErrorRaisingArgumentParser(add_help=False)
2332 g = parent.add_argument_group(title='g', description='gd')
2333 g.add_argument('-w')
2334 g.add_argument('-x')
2335 m = parent.add_mutually_exclusive_group()
2336 m.add_argument('-y')
2337 m.add_argument('-z')
2338 parser = ErrorRaisingArgumentParser(parents=[parent])
2339
2340 self.assertRaises(ArgumentParserError, parser.parse_args,
2341 ['-y', 'Y', '-z', 'Z'])
2342
2343 parser_help = parser.format_help()
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002344 progname = self.main_program
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002345 self.assertEqual(parser_help, textwrap.dedent('''\
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002346 usage: {}{}[-h] [-w W] [-x X] [-y Y | -z Z]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002347
2348 optional arguments:
2349 -h, --help show this help message and exit
2350 -y Y
2351 -z Z
2352
2353 g:
2354 gd
2355
2356 -w W
2357 -x X
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002358 '''.format(progname, ' ' if progname else '' )))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002359
2360# ==============================
2361# Mutually exclusive group tests
2362# ==============================
2363
2364class TestMutuallyExclusiveGroupErrors(TestCase):
2365
2366 def test_invalid_add_argument_group(self):
2367 parser = ErrorRaisingArgumentParser()
2368 raises = self.assertRaises
2369 raises(TypeError, parser.add_mutually_exclusive_group, title='foo')
2370
2371 def test_invalid_add_argument(self):
2372 parser = ErrorRaisingArgumentParser()
2373 group = parser.add_mutually_exclusive_group()
2374 add_argument = group.add_argument
2375 raises = self.assertRaises
2376 raises(ValueError, add_argument, '--foo', required=True)
2377 raises(ValueError, add_argument, 'bar')
2378 raises(ValueError, add_argument, 'bar', nargs='+')
2379 raises(ValueError, add_argument, 'bar', nargs=1)
2380 raises(ValueError, add_argument, 'bar', nargs=argparse.PARSER)
2381
Steven Bethard49998ee2010-11-01 16:29:26 +00002382 def test_help(self):
2383 parser = ErrorRaisingArgumentParser(prog='PROG')
2384 group1 = parser.add_mutually_exclusive_group()
2385 group1.add_argument('--foo', action='store_true')
2386 group1.add_argument('--bar', action='store_false')
2387 group2 = parser.add_mutually_exclusive_group()
2388 group2.add_argument('--soup', action='store_true')
2389 group2.add_argument('--nuts', action='store_false')
2390 expected = '''\
2391 usage: PROG [-h] [--foo | --bar] [--soup | --nuts]
2392
2393 optional arguments:
2394 -h, --help show this help message and exit
2395 --foo
2396 --bar
2397 --soup
2398 --nuts
2399 '''
2400 self.assertEqual(parser.format_help(), textwrap.dedent(expected))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002401
2402class MEMixin(object):
2403
2404 def test_failures_when_not_required(self):
2405 parse_args = self.get_parser(required=False).parse_args
2406 error = ArgumentParserError
2407 for args_string in self.failures:
2408 self.assertRaises(error, parse_args, args_string.split())
2409
2410 def test_failures_when_required(self):
2411 parse_args = self.get_parser(required=True).parse_args
2412 error = ArgumentParserError
2413 for args_string in self.failures + ['']:
2414 self.assertRaises(error, parse_args, args_string.split())
2415
2416 def test_successes_when_not_required(self):
2417 parse_args = self.get_parser(required=False).parse_args
2418 successes = self.successes + self.successes_when_not_required
2419 for args_string, expected_ns in successes:
2420 actual_ns = parse_args(args_string.split())
2421 self.assertEqual(actual_ns, expected_ns)
2422
2423 def test_successes_when_required(self):
2424 parse_args = self.get_parser(required=True).parse_args
2425 for args_string, expected_ns in self.successes:
2426 actual_ns = parse_args(args_string.split())
2427 self.assertEqual(actual_ns, expected_ns)
2428
2429 def test_usage_when_not_required(self):
2430 format_usage = self.get_parser(required=False).format_usage
2431 expected_usage = self.usage_when_not_required
2432 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))
2433
2434 def test_usage_when_required(self):
2435 format_usage = self.get_parser(required=True).format_usage
2436 expected_usage = self.usage_when_required
2437 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))
2438
2439 def test_help_when_not_required(self):
2440 format_help = self.get_parser(required=False).format_help
2441 help = self.usage_when_not_required + self.help
2442 self.assertEqual(format_help(), textwrap.dedent(help))
2443
2444 def test_help_when_required(self):
2445 format_help = self.get_parser(required=True).format_help
2446 help = self.usage_when_required + self.help
2447 self.assertEqual(format_help(), textwrap.dedent(help))
2448
2449
2450class TestMutuallyExclusiveSimple(MEMixin, TestCase):
2451
2452 def get_parser(self, required=None):
2453 parser = ErrorRaisingArgumentParser(prog='PROG')
2454 group = parser.add_mutually_exclusive_group(required=required)
2455 group.add_argument('--bar', help='bar help')
2456 group.add_argument('--baz', nargs='?', const='Z', help='baz help')
2457 return parser
2458
2459 failures = ['--bar X --baz Y', '--bar X --baz']
2460 successes = [
2461 ('--bar X', NS(bar='X', baz=None)),
2462 ('--bar X --bar Z', NS(bar='Z', baz=None)),
2463 ('--baz Y', NS(bar=None, baz='Y')),
2464 ('--baz', NS(bar=None, baz='Z')),
2465 ]
2466 successes_when_not_required = [
2467 ('', NS(bar=None, baz=None)),
2468 ]
2469
2470 usage_when_not_required = '''\
2471 usage: PROG [-h] [--bar BAR | --baz [BAZ]]
2472 '''
2473 usage_when_required = '''\
2474 usage: PROG [-h] (--bar BAR | --baz [BAZ])
2475 '''
2476 help = '''\
2477
2478 optional arguments:
2479 -h, --help show this help message and exit
2480 --bar BAR bar help
2481 --baz [BAZ] baz help
2482 '''
2483
2484
2485class TestMutuallyExclusiveLong(MEMixin, TestCase):
2486
2487 def get_parser(self, required=None):
2488 parser = ErrorRaisingArgumentParser(prog='PROG')
2489 parser.add_argument('--abcde', help='abcde help')
2490 parser.add_argument('--fghij', help='fghij help')
2491 group = parser.add_mutually_exclusive_group(required=required)
2492 group.add_argument('--klmno', help='klmno help')
2493 group.add_argument('--pqrst', help='pqrst help')
2494 return parser
2495
2496 failures = ['--klmno X --pqrst Y']
2497 successes = [
2498 ('--klmno X', NS(abcde=None, fghij=None, klmno='X', pqrst=None)),
2499 ('--abcde Y --klmno X',
2500 NS(abcde='Y', fghij=None, klmno='X', pqrst=None)),
2501 ('--pqrst X', NS(abcde=None, fghij=None, klmno=None, pqrst='X')),
2502 ('--pqrst X --fghij Y',
2503 NS(abcde=None, fghij='Y', klmno=None, pqrst='X')),
2504 ]
2505 successes_when_not_required = [
2506 ('', NS(abcde=None, fghij=None, klmno=None, pqrst=None)),
2507 ]
2508
2509 usage_when_not_required = '''\
2510 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]
2511 [--klmno KLMNO | --pqrst PQRST]
2512 '''
2513 usage_when_required = '''\
2514 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]
2515 (--klmno KLMNO | --pqrst PQRST)
2516 '''
2517 help = '''\
2518
2519 optional arguments:
2520 -h, --help show this help message and exit
2521 --abcde ABCDE abcde help
2522 --fghij FGHIJ fghij help
2523 --klmno KLMNO klmno help
2524 --pqrst PQRST pqrst help
2525 '''
2526
2527
2528class TestMutuallyExclusiveFirstSuppressed(MEMixin, TestCase):
2529
2530 def get_parser(self, required):
2531 parser = ErrorRaisingArgumentParser(prog='PROG')
2532 group = parser.add_mutually_exclusive_group(required=required)
2533 group.add_argument('-x', help=argparse.SUPPRESS)
2534 group.add_argument('-y', action='store_false', help='y help')
2535 return parser
2536
2537 failures = ['-x X -y']
2538 successes = [
2539 ('-x X', NS(x='X', y=True)),
2540 ('-x X -x Y', NS(x='Y', y=True)),
2541 ('-y', NS(x=None, y=False)),
2542 ]
2543 successes_when_not_required = [
2544 ('', NS(x=None, y=True)),
2545 ]
2546
2547 usage_when_not_required = '''\
2548 usage: PROG [-h] [-y]
2549 '''
2550 usage_when_required = '''\
2551 usage: PROG [-h] -y
2552 '''
2553 help = '''\
2554
2555 optional arguments:
2556 -h, --help show this help message and exit
2557 -y y help
2558 '''
2559
2560
2561class TestMutuallyExclusiveManySuppressed(MEMixin, TestCase):
2562
2563 def get_parser(self, required):
2564 parser = ErrorRaisingArgumentParser(prog='PROG')
2565 group = parser.add_mutually_exclusive_group(required=required)
2566 add = group.add_argument
2567 add('--spam', action='store_true', help=argparse.SUPPRESS)
2568 add('--badger', action='store_false', help=argparse.SUPPRESS)
2569 add('--bladder', help=argparse.SUPPRESS)
2570 return parser
2571
2572 failures = [
2573 '--spam --badger',
2574 '--badger --bladder B',
2575 '--bladder B --spam',
2576 ]
2577 successes = [
2578 ('--spam', NS(spam=True, badger=True, bladder=None)),
2579 ('--badger', NS(spam=False, badger=False, bladder=None)),
2580 ('--bladder B', NS(spam=False, badger=True, bladder='B')),
2581 ('--spam --spam', NS(spam=True, badger=True, bladder=None)),
2582 ]
2583 successes_when_not_required = [
2584 ('', NS(spam=False, badger=True, bladder=None)),
2585 ]
2586
2587 usage_when_required = usage_when_not_required = '''\
2588 usage: PROG [-h]
2589 '''
2590 help = '''\
2591
2592 optional arguments:
2593 -h, --help show this help message and exit
2594 '''
2595
2596
2597class TestMutuallyExclusiveOptionalAndPositional(MEMixin, TestCase):
2598
2599 def get_parser(self, required):
2600 parser = ErrorRaisingArgumentParser(prog='PROG')
2601 group = parser.add_mutually_exclusive_group(required=required)
2602 group.add_argument('--foo', action='store_true', help='FOO')
2603 group.add_argument('--spam', help='SPAM')
2604 group.add_argument('badger', nargs='*', default='X', help='BADGER')
2605 return parser
2606
2607 failures = [
2608 '--foo --spam S',
2609 '--spam S X',
2610 'X --foo',
2611 'X Y Z --spam S',
2612 '--foo X Y',
2613 ]
2614 successes = [
2615 ('--foo', NS(foo=True, spam=None, badger='X')),
2616 ('--spam S', NS(foo=False, spam='S', badger='X')),
2617 ('X', NS(foo=False, spam=None, badger=['X'])),
2618 ('X Y Z', NS(foo=False, spam=None, badger=['X', 'Y', 'Z'])),
2619 ]
2620 successes_when_not_required = [
2621 ('', NS(foo=False, spam=None, badger='X')),
2622 ]
2623
2624 usage_when_not_required = '''\
2625 usage: PROG [-h] [--foo | --spam SPAM | badger [badger ...]]
2626 '''
2627 usage_when_required = '''\
2628 usage: PROG [-h] (--foo | --spam SPAM | badger [badger ...])
2629 '''
2630 help = '''\
2631
2632 positional arguments:
2633 badger BADGER
2634
2635 optional arguments:
2636 -h, --help show this help message and exit
2637 --foo FOO
2638 --spam SPAM SPAM
2639 '''
2640
2641
2642class TestMutuallyExclusiveOptionalsMixed(MEMixin, TestCase):
2643
2644 def get_parser(self, required):
2645 parser = ErrorRaisingArgumentParser(prog='PROG')
2646 parser.add_argument('-x', action='store_true', help='x help')
2647 group = parser.add_mutually_exclusive_group(required=required)
2648 group.add_argument('-a', action='store_true', help='a help')
2649 group.add_argument('-b', action='store_true', help='b help')
2650 parser.add_argument('-y', action='store_true', help='y help')
2651 group.add_argument('-c', action='store_true', help='c help')
2652 return parser
2653
2654 failures = ['-a -b', '-b -c', '-a -c', '-a -b -c']
2655 successes = [
2656 ('-a', NS(a=True, b=False, c=False, x=False, y=False)),
2657 ('-b', NS(a=False, b=True, c=False, x=False, y=False)),
2658 ('-c', NS(a=False, b=False, c=True, x=False, y=False)),
2659 ('-a -x', NS(a=True, b=False, c=False, x=True, y=False)),
2660 ('-y -b', NS(a=False, b=True, c=False, x=False, y=True)),
2661 ('-x -y -c', NS(a=False, b=False, c=True, x=True, y=True)),
2662 ]
2663 successes_when_not_required = [
2664 ('', NS(a=False, b=False, c=False, x=False, y=False)),
2665 ('-x', NS(a=False, b=False, c=False, x=True, y=False)),
2666 ('-y', NS(a=False, b=False, c=False, x=False, y=True)),
2667 ]
2668
2669 usage_when_required = usage_when_not_required = '''\
2670 usage: PROG [-h] [-x] [-a] [-b] [-y] [-c]
2671 '''
2672 help = '''\
2673
2674 optional arguments:
2675 -h, --help show this help message and exit
2676 -x x help
2677 -a a help
2678 -b b help
2679 -y y help
2680 -c c help
2681 '''
2682
2683
Georg Brandl0f6b47a2011-01-30 12:19:35 +00002684class TestMutuallyExclusiveInGroup(MEMixin, TestCase):
2685
2686 def get_parser(self, required=None):
2687 parser = ErrorRaisingArgumentParser(prog='PROG')
2688 titled_group = parser.add_argument_group(
2689 title='Titled group', description='Group description')
2690 mutex_group = \
2691 titled_group.add_mutually_exclusive_group(required=required)
2692 mutex_group.add_argument('--bar', help='bar help')
2693 mutex_group.add_argument('--baz', help='baz help')
2694 return parser
2695
2696 failures = ['--bar X --baz Y', '--baz X --bar Y']
2697 successes = [
2698 ('--bar X', NS(bar='X', baz=None)),
2699 ('--baz Y', NS(bar=None, baz='Y')),
2700 ]
2701 successes_when_not_required = [
2702 ('', NS(bar=None, baz=None)),
2703 ]
2704
2705 usage_when_not_required = '''\
2706 usage: PROG [-h] [--bar BAR | --baz BAZ]
2707 '''
2708 usage_when_required = '''\
2709 usage: PROG [-h] (--bar BAR | --baz BAZ)
2710 '''
2711 help = '''\
2712
2713 optional arguments:
2714 -h, --help show this help message and exit
2715
2716 Titled group:
2717 Group description
2718
2719 --bar BAR bar help
2720 --baz BAZ baz help
2721 '''
2722
2723
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002724class TestMutuallyExclusiveOptionalsAndPositionalsMixed(MEMixin, TestCase):
2725
2726 def get_parser(self, required):
2727 parser = ErrorRaisingArgumentParser(prog='PROG')
2728 parser.add_argument('x', help='x help')
2729 parser.add_argument('-y', action='store_true', help='y help')
2730 group = parser.add_mutually_exclusive_group(required=required)
2731 group.add_argument('a', nargs='?', help='a help')
2732 group.add_argument('-b', action='store_true', help='b help')
2733 group.add_argument('-c', action='store_true', help='c help')
2734 return parser
2735
2736 failures = ['X A -b', '-b -c', '-c X A']
2737 successes = [
2738 ('X A', NS(a='A', b=False, c=False, x='X', y=False)),
2739 ('X -b', NS(a=None, b=True, c=False, x='X', y=False)),
2740 ('X -c', NS(a=None, b=False, c=True, x='X', y=False)),
2741 ('X A -y', NS(a='A', b=False, c=False, x='X', y=True)),
2742 ('X -y -b', NS(a=None, b=True, c=False, x='X', y=True)),
2743 ]
2744 successes_when_not_required = [
2745 ('X', NS(a=None, b=False, c=False, x='X', y=False)),
2746 ('X -y', NS(a=None, b=False, c=False, x='X', y=True)),
2747 ]
2748
2749 usage_when_required = usage_when_not_required = '''\
2750 usage: PROG [-h] [-y] [-b] [-c] x [a]
2751 '''
2752 help = '''\
2753
2754 positional arguments:
2755 x x help
2756 a a help
2757
2758 optional arguments:
2759 -h, --help show this help message and exit
2760 -y y help
2761 -b b help
2762 -c c help
2763 '''
2764
2765# =================================================
2766# Mutually exclusive group in parent parser tests
2767# =================================================
2768
2769class MEPBase(object):
2770
2771 def get_parser(self, required=None):
2772 parent = super(MEPBase, self).get_parser(required=required)
2773 parser = ErrorRaisingArgumentParser(
2774 prog=parent.prog, add_help=False, parents=[parent])
2775 return parser
2776
2777
2778class TestMutuallyExclusiveGroupErrorsParent(
2779 MEPBase, TestMutuallyExclusiveGroupErrors):
2780 pass
2781
2782
2783class TestMutuallyExclusiveSimpleParent(
2784 MEPBase, TestMutuallyExclusiveSimple):
2785 pass
2786
2787
2788class TestMutuallyExclusiveLongParent(
2789 MEPBase, TestMutuallyExclusiveLong):
2790 pass
2791
2792
2793class TestMutuallyExclusiveFirstSuppressedParent(
2794 MEPBase, TestMutuallyExclusiveFirstSuppressed):
2795 pass
2796
2797
2798class TestMutuallyExclusiveManySuppressedParent(
2799 MEPBase, TestMutuallyExclusiveManySuppressed):
2800 pass
2801
2802
2803class TestMutuallyExclusiveOptionalAndPositionalParent(
2804 MEPBase, TestMutuallyExclusiveOptionalAndPositional):
2805 pass
2806
2807
2808class TestMutuallyExclusiveOptionalsMixedParent(
2809 MEPBase, TestMutuallyExclusiveOptionalsMixed):
2810 pass
2811
2812
2813class TestMutuallyExclusiveOptionalsAndPositionalsMixedParent(
2814 MEPBase, TestMutuallyExclusiveOptionalsAndPositionalsMixed):
2815 pass
2816
2817# =================
2818# Set default tests
2819# =================
2820
2821class TestSetDefaults(TestCase):
2822
2823 def test_set_defaults_no_args(self):
2824 parser = ErrorRaisingArgumentParser()
2825 parser.set_defaults(x='foo')
2826 parser.set_defaults(y='bar', z=1)
2827 self.assertEqual(NS(x='foo', y='bar', z=1),
2828 parser.parse_args([]))
2829 self.assertEqual(NS(x='foo', y='bar', z=1),
2830 parser.parse_args([], NS()))
2831 self.assertEqual(NS(x='baz', y='bar', z=1),
2832 parser.parse_args([], NS(x='baz')))
2833 self.assertEqual(NS(x='baz', y='bar', z=2),
2834 parser.parse_args([], NS(x='baz', z=2)))
2835
2836 def test_set_defaults_with_args(self):
2837 parser = ErrorRaisingArgumentParser()
2838 parser.set_defaults(x='foo', y='bar')
2839 parser.add_argument('-x', default='xfoox')
2840 self.assertEqual(NS(x='xfoox', y='bar'),
2841 parser.parse_args([]))
2842 self.assertEqual(NS(x='xfoox', y='bar'),
2843 parser.parse_args([], NS()))
2844 self.assertEqual(NS(x='baz', y='bar'),
2845 parser.parse_args([], NS(x='baz')))
2846 self.assertEqual(NS(x='1', y='bar'),
2847 parser.parse_args('-x 1'.split()))
2848 self.assertEqual(NS(x='1', y='bar'),
2849 parser.parse_args('-x 1'.split(), NS()))
2850 self.assertEqual(NS(x='1', y='bar'),
2851 parser.parse_args('-x 1'.split(), NS(x='baz')))
2852
2853 def test_set_defaults_subparsers(self):
2854 parser = ErrorRaisingArgumentParser()
2855 parser.set_defaults(x='foo')
2856 subparsers = parser.add_subparsers()
2857 parser_a = subparsers.add_parser('a')
2858 parser_a.set_defaults(y='bar')
2859 self.assertEqual(NS(x='foo', y='bar'),
2860 parser.parse_args('a'.split()))
2861
2862 def test_set_defaults_parents(self):
2863 parent = ErrorRaisingArgumentParser(add_help=False)
2864 parent.set_defaults(x='foo')
2865 parser = ErrorRaisingArgumentParser(parents=[parent])
2866 self.assertEqual(NS(x='foo'), parser.parse_args([]))
2867
R David Murray7570cbd2014-10-17 19:55:11 -04002868 def test_set_defaults_on_parent_and_subparser(self):
2869 parser = argparse.ArgumentParser()
2870 xparser = parser.add_subparsers().add_parser('X')
2871 parser.set_defaults(foo=1)
2872 xparser.set_defaults(foo=2)
2873 self.assertEqual(NS(foo=2), parser.parse_args(['X']))
2874
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002875 def test_set_defaults_same_as_add_argument(self):
2876 parser = ErrorRaisingArgumentParser()
2877 parser.set_defaults(w='W', x='X', y='Y', z='Z')
2878 parser.add_argument('-w')
2879 parser.add_argument('-x', default='XX')
2880 parser.add_argument('y', nargs='?')
2881 parser.add_argument('z', nargs='?', default='ZZ')
2882
2883 # defaults set previously
2884 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
2885 parser.parse_args([]))
2886
2887 # reset defaults
2888 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
2889 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
2890 parser.parse_args([]))
2891
2892 def test_set_defaults_same_as_add_argument_group(self):
2893 parser = ErrorRaisingArgumentParser()
2894 parser.set_defaults(w='W', x='X', y='Y', z='Z')
2895 group = parser.add_argument_group('foo')
2896 group.add_argument('-w')
2897 group.add_argument('-x', default='XX')
2898 group.add_argument('y', nargs='?')
2899 group.add_argument('z', nargs='?', default='ZZ')
2900
2901
2902 # defaults set previously
2903 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
2904 parser.parse_args([]))
2905
2906 # reset defaults
2907 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
2908 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
2909 parser.parse_args([]))
2910
2911# =================
2912# Get default tests
2913# =================
2914
2915class TestGetDefault(TestCase):
2916
2917 def test_get_default(self):
2918 parser = ErrorRaisingArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002919 self.assertIsNone(parser.get_default("foo"))
2920 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002921
2922 parser.add_argument("--foo")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002923 self.assertIsNone(parser.get_default("foo"))
2924 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002925
2926 parser.add_argument("--bar", type=int, default=42)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002927 self.assertIsNone(parser.get_default("foo"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002928 self.assertEqual(42, parser.get_default("bar"))
2929
2930 parser.set_defaults(foo="badger")
2931 self.assertEqual("badger", parser.get_default("foo"))
2932 self.assertEqual(42, parser.get_default("bar"))
2933
2934# ==========================
2935# Namespace 'contains' tests
2936# ==========================
2937
2938class TestNamespaceContainsSimple(TestCase):
2939
2940 def test_empty(self):
2941 ns = argparse.Namespace()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002942 self.assertNotIn('', ns)
2943 self.assertNotIn('x', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002944
2945 def test_non_empty(self):
2946 ns = argparse.Namespace(x=1, y=2)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002947 self.assertNotIn('', ns)
2948 self.assertIn('x', ns)
2949 self.assertIn('y', ns)
2950 self.assertNotIn('xx', ns)
2951 self.assertNotIn('z', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002952
2953# =====================
2954# Help formatting tests
2955# =====================
2956
2957class TestHelpFormattingMetaclass(type):
2958
2959 def __init__(cls, name, bases, bodydict):
2960 if name == 'HelpTestCase':
2961 return
2962
2963 class AddTests(object):
2964
2965 def __init__(self, test_class, func_suffix, std_name):
2966 self.func_suffix = func_suffix
2967 self.std_name = std_name
2968
2969 for test_func in [self.test_format,
2970 self.test_print,
2971 self.test_print_file]:
2972 test_name = '%s_%s' % (test_func.__name__, func_suffix)
2973
2974 def test_wrapper(self, test_func=test_func):
2975 test_func(self)
2976 try:
2977 test_wrapper.__name__ = test_name
2978 except TypeError:
2979 pass
2980 setattr(test_class, test_name, test_wrapper)
2981
2982 def _get_parser(self, tester):
2983 parser = argparse.ArgumentParser(
2984 *tester.parser_signature.args,
2985 **tester.parser_signature.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02002986 for argument_sig in getattr(tester, 'argument_signatures', []):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002987 parser.add_argument(*argument_sig.args,
2988 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02002989 group_sigs = getattr(tester, 'argument_group_signatures', [])
2990 for group_sig, argument_sigs in group_sigs:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002991 group = parser.add_argument_group(*group_sig.args,
2992 **group_sig.kwargs)
2993 for argument_sig in argument_sigs:
2994 group.add_argument(*argument_sig.args,
2995 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02002996 subparsers_sigs = getattr(tester, 'subparsers_signatures', [])
2997 if subparsers_sigs:
2998 subparsers = parser.add_subparsers()
2999 for subparser_sig in subparsers_sigs:
3000 subparsers.add_parser(*subparser_sig.args,
3001 **subparser_sig.kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003002 return parser
3003
3004 def _test(self, tester, parser_text):
3005 expected_text = getattr(tester, self.func_suffix)
3006 expected_text = textwrap.dedent(expected_text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003007 tester.assertEqual(expected_text, parser_text)
3008
3009 def test_format(self, tester):
3010 parser = self._get_parser(tester)
3011 format = getattr(parser, 'format_%s' % self.func_suffix)
3012 self._test(tester, format())
3013
3014 def test_print(self, tester):
3015 parser = self._get_parser(tester)
3016 print_ = getattr(parser, 'print_%s' % self.func_suffix)
3017 old_stream = getattr(sys, self.std_name)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003018 setattr(sys, self.std_name, StdIOBuffer())
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003019 try:
3020 print_()
3021 parser_text = getattr(sys, self.std_name).getvalue()
3022 finally:
3023 setattr(sys, self.std_name, old_stream)
3024 self._test(tester, parser_text)
3025
3026 def test_print_file(self, tester):
3027 parser = self._get_parser(tester)
3028 print_ = getattr(parser, 'print_%s' % self.func_suffix)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003029 sfile = StdIOBuffer()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003030 print_(sfile)
3031 parser_text = sfile.getvalue()
3032 self._test(tester, parser_text)
3033
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003034 # add tests for {format,print}_{usage,help}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003035 for func_suffix, std_name in [('usage', 'stdout'),
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003036 ('help', 'stdout')]:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003037 AddTests(cls, func_suffix, std_name)
3038
3039bases = TestCase,
3040HelpTestCase = TestHelpFormattingMetaclass('HelpTestCase', bases, {})
3041
3042
3043class TestHelpBiggerOptionals(HelpTestCase):
3044 """Make sure that argument help aligns when options are longer"""
3045
3046 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003047 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003048 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003049 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003050 Sig('-x', action='store_true', help='X HELP'),
3051 Sig('--y', help='Y HELP'),
3052 Sig('foo', help='FOO HELP'),
3053 Sig('bar', help='BAR HELP'),
3054 ]
3055 argument_group_signatures = []
3056 usage = '''\
3057 usage: PROG [-h] [-v] [-x] [--y Y] foo bar
3058 '''
3059 help = usage + '''\
3060
3061 DESCRIPTION
3062
3063 positional arguments:
3064 foo FOO HELP
3065 bar BAR HELP
3066
3067 optional arguments:
3068 -h, --help show this help message and exit
3069 -v, --version show program's version number and exit
3070 -x X HELP
3071 --y Y Y HELP
3072
3073 EPILOG
3074 '''
3075 version = '''\
3076 0.1
3077 '''
3078
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003079class TestShortColumns(HelpTestCase):
3080 '''Test extremely small number of columns.
3081
3082 TestCase prevents "COLUMNS" from being too small in the tests themselves,
Martin Panter2e4571a2015-11-14 01:07:43 +00003083 but we don't want any exceptions thrown in such cases. Only ugly representation.
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003084 '''
3085 def setUp(self):
3086 env = support.EnvironmentVarGuard()
3087 env.set("COLUMNS", '15')
3088 self.addCleanup(env.__exit__)
3089
3090 parser_signature = TestHelpBiggerOptionals.parser_signature
3091 argument_signatures = TestHelpBiggerOptionals.argument_signatures
3092 argument_group_signatures = TestHelpBiggerOptionals.argument_group_signatures
3093 usage = '''\
3094 usage: PROG
3095 [-h]
3096 [-v]
3097 [-x]
3098 [--y Y]
3099 foo
3100 bar
3101 '''
3102 help = usage + '''\
3103
3104 DESCRIPTION
3105
3106 positional arguments:
3107 foo
3108 FOO HELP
3109 bar
3110 BAR HELP
3111
3112 optional arguments:
3113 -h, --help
3114 show this
3115 help
3116 message and
3117 exit
3118 -v, --version
3119 show
3120 program's
3121 version
3122 number and
3123 exit
3124 -x
3125 X HELP
3126 --y Y
3127 Y HELP
3128
3129 EPILOG
3130 '''
3131 version = TestHelpBiggerOptionals.version
3132
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003133
3134class TestHelpBiggerOptionalGroups(HelpTestCase):
3135 """Make sure that argument help aligns when options are longer"""
3136
3137 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003138 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003139 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003140 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003141 Sig('-x', action='store_true', help='X HELP'),
3142 Sig('--y', help='Y HELP'),
3143 Sig('foo', help='FOO HELP'),
3144 Sig('bar', help='BAR HELP'),
3145 ]
3146 argument_group_signatures = [
3147 (Sig('GROUP TITLE', description='GROUP DESCRIPTION'), [
3148 Sig('baz', help='BAZ HELP'),
3149 Sig('-z', nargs='+', help='Z HELP')]),
3150 ]
3151 usage = '''\
3152 usage: PROG [-h] [-v] [-x] [--y Y] [-z Z [Z ...]] foo bar baz
3153 '''
3154 help = usage + '''\
3155
3156 DESCRIPTION
3157
3158 positional arguments:
3159 foo FOO HELP
3160 bar BAR HELP
3161
3162 optional arguments:
3163 -h, --help show this help message and exit
3164 -v, --version show program's version number and exit
3165 -x X HELP
3166 --y Y Y HELP
3167
3168 GROUP TITLE:
3169 GROUP DESCRIPTION
3170
3171 baz BAZ HELP
3172 -z Z [Z ...] Z HELP
3173
3174 EPILOG
3175 '''
3176 version = '''\
3177 0.1
3178 '''
3179
3180
3181class TestHelpBiggerPositionals(HelpTestCase):
3182 """Make sure that help aligns when arguments are longer"""
3183
3184 parser_signature = Sig(usage='USAGE', description='DESCRIPTION')
3185 argument_signatures = [
3186 Sig('-x', action='store_true', help='X HELP'),
3187 Sig('--y', help='Y HELP'),
3188 Sig('ekiekiekifekang', help='EKI HELP'),
3189 Sig('bar', help='BAR HELP'),
3190 ]
3191 argument_group_signatures = []
3192 usage = '''\
3193 usage: USAGE
3194 '''
3195 help = usage + '''\
3196
3197 DESCRIPTION
3198
3199 positional arguments:
3200 ekiekiekifekang EKI HELP
3201 bar BAR HELP
3202
3203 optional arguments:
3204 -h, --help show this help message and exit
3205 -x X HELP
3206 --y Y Y HELP
3207 '''
3208
3209 version = ''
3210
3211
3212class TestHelpReformatting(HelpTestCase):
3213 """Make sure that text after short names starts on the first line"""
3214
3215 parser_signature = Sig(
3216 prog='PROG',
3217 description=' oddly formatted\n'
3218 'description\n'
3219 '\n'
3220 'that is so long that it should go onto multiple '
3221 'lines when wrapped')
3222 argument_signatures = [
3223 Sig('-x', metavar='XX', help='oddly\n'
3224 ' formatted -x help'),
3225 Sig('y', metavar='yyy', help='normal y help'),
3226 ]
3227 argument_group_signatures = [
3228 (Sig('title', description='\n'
3229 ' oddly formatted group\n'
3230 '\n'
3231 'description'),
3232 [Sig('-a', action='store_true',
3233 help=' oddly \n'
3234 'formatted -a help \n'
3235 ' again, so long that it should be wrapped over '
3236 'multiple lines')]),
3237 ]
3238 usage = '''\
3239 usage: PROG [-h] [-x XX] [-a] yyy
3240 '''
3241 help = usage + '''\
3242
3243 oddly formatted description that is so long that it should go onto \
3244multiple
3245 lines when wrapped
3246
3247 positional arguments:
3248 yyy normal y help
3249
3250 optional arguments:
3251 -h, --help show this help message and exit
3252 -x XX oddly formatted -x help
3253
3254 title:
3255 oddly formatted group description
3256
3257 -a oddly formatted -a help again, so long that it should \
3258be wrapped
3259 over multiple lines
3260 '''
3261 version = ''
3262
3263
3264class TestHelpWrappingShortNames(HelpTestCase):
3265 """Make sure that text after short names starts on the first line"""
3266
3267 parser_signature = Sig(prog='PROG', description= 'D\nD' * 30)
3268 argument_signatures = [
3269 Sig('-x', metavar='XX', help='XHH HX' * 20),
3270 Sig('y', metavar='yyy', help='YH YH' * 20),
3271 ]
3272 argument_group_signatures = [
3273 (Sig('ALPHAS'), [
3274 Sig('-a', action='store_true', help='AHHH HHA' * 10)]),
3275 ]
3276 usage = '''\
3277 usage: PROG [-h] [-x XX] [-a] yyy
3278 '''
3279 help = usage + '''\
3280
3281 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3282DD DD DD
3283 DD DD DD DD D
3284
3285 positional arguments:
3286 yyy YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3287YHYH YHYH
3288 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3289
3290 optional arguments:
3291 -h, --help show this help message and exit
3292 -x XX XHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH \
3293HXXHH HXXHH
3294 HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HX
3295
3296 ALPHAS:
3297 -a AHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH \
3298HHAAHHH
3299 HHAAHHH HHAAHHH HHA
3300 '''
3301 version = ''
3302
3303
3304class TestHelpWrappingLongNames(HelpTestCase):
3305 """Make sure that text after long names starts on the next line"""
3306
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003307 parser_signature = Sig(usage='USAGE', description= 'D D' * 30)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003308 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003309 Sig('-v', '--version', action='version', version='V V' * 30),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003310 Sig('-x', metavar='X' * 25, help='XH XH' * 20),
3311 Sig('y', metavar='y' * 25, help='YH YH' * 20),
3312 ]
3313 argument_group_signatures = [
3314 (Sig('ALPHAS'), [
3315 Sig('-a', metavar='A' * 25, help='AH AH' * 20),
3316 Sig('z', metavar='z' * 25, help='ZH ZH' * 20)]),
3317 ]
3318 usage = '''\
3319 usage: USAGE
3320 '''
3321 help = usage + '''\
3322
3323 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3324DD DD DD
3325 DD DD DD DD D
3326
3327 positional arguments:
3328 yyyyyyyyyyyyyyyyyyyyyyyyy
3329 YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3330YHYH YHYH
3331 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3332
3333 optional arguments:
3334 -h, --help show this help message and exit
3335 -v, --version show program's version number and exit
3336 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3337 XH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH \
3338XHXH XHXH
3339 XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XH
3340
3341 ALPHAS:
3342 -a AAAAAAAAAAAAAAAAAAAAAAAAA
3343 AH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH \
3344AHAH AHAH
3345 AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AH
3346 zzzzzzzzzzzzzzzzzzzzzzzzz
3347 ZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH \
3348ZHZH ZHZH
3349 ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZH
3350 '''
3351 version = '''\
3352 V VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV \
3353VV VV VV
3354 VV VV VV VV V
3355 '''
3356
3357
3358class TestHelpUsage(HelpTestCase):
3359 """Test basic usage messages"""
3360
3361 parser_signature = Sig(prog='PROG')
3362 argument_signatures = [
3363 Sig('-w', nargs='+', help='w'),
3364 Sig('-x', nargs='*', help='x'),
3365 Sig('a', help='a'),
3366 Sig('b', help='b', nargs=2),
3367 Sig('c', help='c', nargs='?'),
3368 ]
3369 argument_group_signatures = [
3370 (Sig('group'), [
3371 Sig('-y', nargs='?', help='y'),
3372 Sig('-z', nargs=3, help='z'),
3373 Sig('d', help='d', nargs='*'),
3374 Sig('e', help='e', nargs='+'),
3375 ])
3376 ]
3377 usage = '''\
3378 usage: PROG [-h] [-w W [W ...]] [-x [X [X ...]]] [-y [Y]] [-z Z Z Z]
3379 a b b [c] [d [d ...]] e [e ...]
3380 '''
3381 help = usage + '''\
3382
3383 positional arguments:
3384 a a
3385 b b
3386 c c
3387
3388 optional arguments:
3389 -h, --help show this help message and exit
3390 -w W [W ...] w
3391 -x [X [X ...]] x
3392
3393 group:
3394 -y [Y] y
3395 -z Z Z Z z
3396 d d
3397 e e
3398 '''
3399 version = ''
3400
3401
3402class TestHelpOnlyUserGroups(HelpTestCase):
3403 """Test basic usage messages"""
3404
3405 parser_signature = Sig(prog='PROG', add_help=False)
3406 argument_signatures = []
3407 argument_group_signatures = [
3408 (Sig('xxxx'), [
3409 Sig('-x', help='x'),
3410 Sig('a', help='a'),
3411 ]),
3412 (Sig('yyyy'), [
3413 Sig('b', help='b'),
3414 Sig('-y', help='y'),
3415 ]),
3416 ]
3417 usage = '''\
3418 usage: PROG [-x X] [-y Y] a b
3419 '''
3420 help = usage + '''\
3421
3422 xxxx:
3423 -x X x
3424 a a
3425
3426 yyyy:
3427 b b
3428 -y Y y
3429 '''
3430 version = ''
3431
3432
3433class TestHelpUsageLongProg(HelpTestCase):
3434 """Test usage messages where the prog is long"""
3435
3436 parser_signature = Sig(prog='P' * 60)
3437 argument_signatures = [
3438 Sig('-w', metavar='W'),
3439 Sig('-x', metavar='X'),
3440 Sig('a'),
3441 Sig('b'),
3442 ]
3443 argument_group_signatures = []
3444 usage = '''\
3445 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3446 [-h] [-w W] [-x X] a b
3447 '''
3448 help = usage + '''\
3449
3450 positional arguments:
3451 a
3452 b
3453
3454 optional arguments:
3455 -h, --help show this help message and exit
3456 -w W
3457 -x X
3458 '''
3459 version = ''
3460
3461
3462class TestHelpUsageLongProgOptionsWrap(HelpTestCase):
3463 """Test usage messages where the prog is long and the optionals wrap"""
3464
3465 parser_signature = Sig(prog='P' * 60)
3466 argument_signatures = [
3467 Sig('-w', metavar='W' * 25),
3468 Sig('-x', metavar='X' * 25),
3469 Sig('-y', metavar='Y' * 25),
3470 Sig('-z', metavar='Z' * 25),
3471 Sig('a'),
3472 Sig('b'),
3473 ]
3474 argument_group_signatures = []
3475 usage = '''\
3476 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3477 [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3478[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3479 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3480 a b
3481 '''
3482 help = usage + '''\
3483
3484 positional arguments:
3485 a
3486 b
3487
3488 optional arguments:
3489 -h, --help show this help message and exit
3490 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3491 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3492 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3493 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3494 '''
3495 version = ''
3496
3497
3498class TestHelpUsageLongProgPositionalsWrap(HelpTestCase):
3499 """Test usage messages where the prog is long and the positionals wrap"""
3500
3501 parser_signature = Sig(prog='P' * 60, add_help=False)
3502 argument_signatures = [
3503 Sig('a' * 25),
3504 Sig('b' * 25),
3505 Sig('c' * 25),
3506 ]
3507 argument_group_signatures = []
3508 usage = '''\
3509 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3510 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3511 ccccccccccccccccccccccccc
3512 '''
3513 help = usage + '''\
3514
3515 positional arguments:
3516 aaaaaaaaaaaaaaaaaaaaaaaaa
3517 bbbbbbbbbbbbbbbbbbbbbbbbb
3518 ccccccccccccccccccccccccc
3519 '''
3520 version = ''
3521
3522
3523class TestHelpUsageOptionalsWrap(HelpTestCase):
3524 """Test usage messages where the optionals wrap"""
3525
3526 parser_signature = Sig(prog='PROG')
3527 argument_signatures = [
3528 Sig('-w', metavar='W' * 25),
3529 Sig('-x', metavar='X' * 25),
3530 Sig('-y', metavar='Y' * 25),
3531 Sig('-z', metavar='Z' * 25),
3532 Sig('a'),
3533 Sig('b'),
3534 Sig('c'),
3535 ]
3536 argument_group_signatures = []
3537 usage = '''\
3538 usage: PROG [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3539[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3540 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] \
3541[-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3542 a b c
3543 '''
3544 help = usage + '''\
3545
3546 positional arguments:
3547 a
3548 b
3549 c
3550
3551 optional arguments:
3552 -h, --help show this help message and exit
3553 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3554 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3555 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3556 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3557 '''
3558 version = ''
3559
3560
3561class TestHelpUsagePositionalsWrap(HelpTestCase):
3562 """Test usage messages where the positionals wrap"""
3563
3564 parser_signature = Sig(prog='PROG')
3565 argument_signatures = [
3566 Sig('-x'),
3567 Sig('-y'),
3568 Sig('-z'),
3569 Sig('a' * 25),
3570 Sig('b' * 25),
3571 Sig('c' * 25),
3572 ]
3573 argument_group_signatures = []
3574 usage = '''\
3575 usage: PROG [-h] [-x X] [-y Y] [-z Z]
3576 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3577 ccccccccccccccccccccccccc
3578 '''
3579 help = usage + '''\
3580
3581 positional arguments:
3582 aaaaaaaaaaaaaaaaaaaaaaaaa
3583 bbbbbbbbbbbbbbbbbbbbbbbbb
3584 ccccccccccccccccccccccccc
3585
3586 optional arguments:
3587 -h, --help show this help message and exit
3588 -x X
3589 -y Y
3590 -z Z
3591 '''
3592 version = ''
3593
3594
3595class TestHelpUsageOptionalsPositionalsWrap(HelpTestCase):
3596 """Test usage messages where the optionals and positionals wrap"""
3597
3598 parser_signature = Sig(prog='PROG')
3599 argument_signatures = [
3600 Sig('-x', metavar='X' * 25),
3601 Sig('-y', metavar='Y' * 25),
3602 Sig('-z', metavar='Z' * 25),
3603 Sig('a' * 25),
3604 Sig('b' * 25),
3605 Sig('c' * 25),
3606 ]
3607 argument_group_signatures = []
3608 usage = '''\
3609 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3610[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3611 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3612 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3613 ccccccccccccccccccccccccc
3614 '''
3615 help = usage + '''\
3616
3617 positional arguments:
3618 aaaaaaaaaaaaaaaaaaaaaaaaa
3619 bbbbbbbbbbbbbbbbbbbbbbbbb
3620 ccccccccccccccccccccccccc
3621
3622 optional arguments:
3623 -h, --help show this help message and exit
3624 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3625 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3626 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3627 '''
3628 version = ''
3629
3630
3631class TestHelpUsageOptionalsOnlyWrap(HelpTestCase):
3632 """Test usage messages where there are only optionals and they wrap"""
3633
3634 parser_signature = Sig(prog='PROG')
3635 argument_signatures = [
3636 Sig('-x', metavar='X' * 25),
3637 Sig('-y', metavar='Y' * 25),
3638 Sig('-z', metavar='Z' * 25),
3639 ]
3640 argument_group_signatures = []
3641 usage = '''\
3642 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3643[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3644 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3645 '''
3646 help = usage + '''\
3647
3648 optional arguments:
3649 -h, --help show this help message and exit
3650 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3651 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3652 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3653 '''
3654 version = ''
3655
3656
3657class TestHelpUsagePositionalsOnlyWrap(HelpTestCase):
3658 """Test usage messages where there are only positionals and they wrap"""
3659
3660 parser_signature = Sig(prog='PROG', add_help=False)
3661 argument_signatures = [
3662 Sig('a' * 25),
3663 Sig('b' * 25),
3664 Sig('c' * 25),
3665 ]
3666 argument_group_signatures = []
3667 usage = '''\
3668 usage: PROG aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3669 ccccccccccccccccccccccccc
3670 '''
3671 help = usage + '''\
3672
3673 positional arguments:
3674 aaaaaaaaaaaaaaaaaaaaaaaaa
3675 bbbbbbbbbbbbbbbbbbbbbbbbb
3676 ccccccccccccccccccccccccc
3677 '''
3678 version = ''
3679
3680
3681class TestHelpVariableExpansion(HelpTestCase):
3682 """Test that variables are expanded properly in help messages"""
3683
3684 parser_signature = Sig(prog='PROG')
3685 argument_signatures = [
3686 Sig('-x', type=int,
3687 help='x %(prog)s %(default)s %(type)s %%'),
3688 Sig('-y', action='store_const', default=42, const='XXX',
3689 help='y %(prog)s %(default)s %(const)s'),
3690 Sig('--foo', choices='abc',
3691 help='foo %(prog)s %(default)s %(choices)s'),
3692 Sig('--bar', default='baz', choices=[1, 2], metavar='BBB',
3693 help='bar %(prog)s %(default)s %(dest)s'),
3694 Sig('spam', help='spam %(prog)s %(default)s'),
3695 Sig('badger', default=0.5, help='badger %(prog)s %(default)s'),
3696 ]
3697 argument_group_signatures = [
3698 (Sig('group'), [
3699 Sig('-a', help='a %(prog)s %(default)s'),
3700 Sig('-b', default=-1, help='b %(prog)s %(default)s'),
3701 ])
3702 ]
3703 usage = ('''\
3704 usage: PROG [-h] [-x X] [-y] [--foo {a,b,c}] [--bar BBB] [-a A] [-b B]
3705 spam badger
3706 ''')
3707 help = usage + '''\
3708
3709 positional arguments:
3710 spam spam PROG None
3711 badger badger PROG 0.5
3712
3713 optional arguments:
3714 -h, --help show this help message and exit
3715 -x X x PROG None int %
3716 -y y PROG 42 XXX
3717 --foo {a,b,c} foo PROG None a, b, c
3718 --bar BBB bar PROG baz bar
3719
3720 group:
3721 -a A a PROG None
3722 -b B b PROG -1
3723 '''
3724 version = ''
3725
3726
3727class TestHelpVariableExpansionUsageSupplied(HelpTestCase):
3728 """Test that variables are expanded properly when usage= is present"""
3729
3730 parser_signature = Sig(prog='PROG', usage='%(prog)s FOO')
3731 argument_signatures = []
3732 argument_group_signatures = []
3733 usage = ('''\
3734 usage: PROG FOO
3735 ''')
3736 help = usage + '''\
3737
3738 optional arguments:
3739 -h, --help show this help message and exit
3740 '''
3741 version = ''
3742
3743
3744class TestHelpVariableExpansionNoArguments(HelpTestCase):
3745 """Test that variables are expanded properly with no arguments"""
3746
3747 parser_signature = Sig(prog='PROG', add_help=False)
3748 argument_signatures = []
3749 argument_group_signatures = []
3750 usage = ('''\
3751 usage: PROG
3752 ''')
3753 help = usage
3754 version = ''
3755
3756
3757class TestHelpSuppressUsage(HelpTestCase):
3758 """Test that items can be suppressed in usage messages"""
3759
3760 parser_signature = Sig(prog='PROG', usage=argparse.SUPPRESS)
3761 argument_signatures = [
3762 Sig('--foo', help='foo help'),
3763 Sig('spam', help='spam help'),
3764 ]
3765 argument_group_signatures = []
3766 help = '''\
3767 positional arguments:
3768 spam spam help
3769
3770 optional arguments:
3771 -h, --help show this help message and exit
3772 --foo FOO foo help
3773 '''
3774 usage = ''
3775 version = ''
3776
3777
3778class TestHelpSuppressOptional(HelpTestCase):
3779 """Test that optional arguments can be suppressed in help messages"""
3780
3781 parser_signature = Sig(prog='PROG', add_help=False)
3782 argument_signatures = [
3783 Sig('--foo', help=argparse.SUPPRESS),
3784 Sig('spam', help='spam help'),
3785 ]
3786 argument_group_signatures = []
3787 usage = '''\
3788 usage: PROG spam
3789 '''
3790 help = usage + '''\
3791
3792 positional arguments:
3793 spam spam help
3794 '''
3795 version = ''
3796
3797
3798class TestHelpSuppressOptionalGroup(HelpTestCase):
3799 """Test that optional groups can be suppressed in help messages"""
3800
3801 parser_signature = Sig(prog='PROG')
3802 argument_signatures = [
3803 Sig('--foo', help='foo help'),
3804 Sig('spam', help='spam help'),
3805 ]
3806 argument_group_signatures = [
3807 (Sig('group'), [Sig('--bar', help=argparse.SUPPRESS)]),
3808 ]
3809 usage = '''\
3810 usage: PROG [-h] [--foo FOO] spam
3811 '''
3812 help = usage + '''\
3813
3814 positional arguments:
3815 spam spam help
3816
3817 optional arguments:
3818 -h, --help show this help message and exit
3819 --foo FOO foo help
3820 '''
3821 version = ''
3822
3823
3824class TestHelpSuppressPositional(HelpTestCase):
3825 """Test that positional arguments can be suppressed in help messages"""
3826
3827 parser_signature = Sig(prog='PROG')
3828 argument_signatures = [
3829 Sig('--foo', help='foo help'),
3830 Sig('spam', help=argparse.SUPPRESS),
3831 ]
3832 argument_group_signatures = []
3833 usage = '''\
3834 usage: PROG [-h] [--foo FOO]
3835 '''
3836 help = usage + '''\
3837
3838 optional arguments:
3839 -h, --help show this help message and exit
3840 --foo FOO foo help
3841 '''
3842 version = ''
3843
3844
3845class TestHelpRequiredOptional(HelpTestCase):
3846 """Test that required options don't look optional"""
3847
3848 parser_signature = Sig(prog='PROG')
3849 argument_signatures = [
3850 Sig('--foo', required=True, help='foo help'),
3851 ]
3852 argument_group_signatures = []
3853 usage = '''\
3854 usage: PROG [-h] --foo FOO
3855 '''
3856 help = usage + '''\
3857
3858 optional arguments:
3859 -h, --help show this help message and exit
3860 --foo FOO foo help
3861 '''
3862 version = ''
3863
3864
3865class TestHelpAlternatePrefixChars(HelpTestCase):
3866 """Test that options display with different prefix characters"""
3867
3868 parser_signature = Sig(prog='PROG', prefix_chars='^;', add_help=False)
3869 argument_signatures = [
3870 Sig('^^foo', action='store_true', help='foo help'),
3871 Sig(';b', ';;bar', help='bar help'),
3872 ]
3873 argument_group_signatures = []
3874 usage = '''\
3875 usage: PROG [^^foo] [;b BAR]
3876 '''
3877 help = usage + '''\
3878
3879 optional arguments:
3880 ^^foo foo help
3881 ;b BAR, ;;bar BAR bar help
3882 '''
3883 version = ''
3884
3885
3886class TestHelpNoHelpOptional(HelpTestCase):
3887 """Test that the --help argument can be suppressed help messages"""
3888
3889 parser_signature = Sig(prog='PROG', add_help=False)
3890 argument_signatures = [
3891 Sig('--foo', help='foo help'),
3892 Sig('spam', help='spam help'),
3893 ]
3894 argument_group_signatures = []
3895 usage = '''\
3896 usage: PROG [--foo FOO] spam
3897 '''
3898 help = usage + '''\
3899
3900 positional arguments:
3901 spam spam help
3902
3903 optional arguments:
3904 --foo FOO foo help
3905 '''
3906 version = ''
3907
3908
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003909class TestHelpNone(HelpTestCase):
3910 """Test that no errors occur if no help is specified"""
3911
3912 parser_signature = Sig(prog='PROG')
3913 argument_signatures = [
3914 Sig('--foo'),
3915 Sig('spam'),
3916 ]
3917 argument_group_signatures = []
3918 usage = '''\
3919 usage: PROG [-h] [--foo FOO] spam
3920 '''
3921 help = usage + '''\
3922
3923 positional arguments:
3924 spam
3925
3926 optional arguments:
3927 -h, --help show this help message and exit
3928 --foo FOO
3929 '''
3930 version = ''
3931
3932
3933class TestHelpTupleMetavar(HelpTestCase):
3934 """Test specifying metavar as a tuple"""
3935
3936 parser_signature = Sig(prog='PROG')
3937 argument_signatures = [
3938 Sig('-w', help='w', nargs='+', metavar=('W1', 'W2')),
3939 Sig('-x', help='x', nargs='*', metavar=('X1', 'X2')),
3940 Sig('-y', help='y', nargs=3, metavar=('Y1', 'Y2', 'Y3')),
3941 Sig('-z', help='z', nargs='?', metavar=('Z1', )),
3942 ]
3943 argument_group_signatures = []
3944 usage = '''\
3945 usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] \
3946[-z [Z1]]
3947 '''
3948 help = usage + '''\
3949
3950 optional arguments:
3951 -h, --help show this help message and exit
3952 -w W1 [W2 ...] w
3953 -x [X1 [X2 ...]] x
3954 -y Y1 Y2 Y3 y
3955 -z [Z1] z
3956 '''
3957 version = ''
3958
3959
3960class TestHelpRawText(HelpTestCase):
3961 """Test the RawTextHelpFormatter"""
3962
3963 parser_signature = Sig(
3964 prog='PROG', formatter_class=argparse.RawTextHelpFormatter,
3965 description='Keep the formatting\n'
3966 ' exactly as it is written\n'
3967 '\n'
3968 'here\n')
3969
3970 argument_signatures = [
3971 Sig('--foo', help=' foo help should also\n'
3972 'appear as given here'),
3973 Sig('spam', help='spam help'),
3974 ]
3975 argument_group_signatures = [
3976 (Sig('title', description=' This text\n'
3977 ' should be indented\n'
3978 ' exactly like it is here\n'),
3979 [Sig('--bar', help='bar help')]),
3980 ]
3981 usage = '''\
3982 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
3983 '''
3984 help = usage + '''\
3985
3986 Keep the formatting
3987 exactly as it is written
3988
3989 here
3990
3991 positional arguments:
3992 spam spam help
3993
3994 optional arguments:
3995 -h, --help show this help message and exit
3996 --foo FOO foo help should also
3997 appear as given here
3998
3999 title:
4000 This text
4001 should be indented
4002 exactly like it is here
4003
4004 --bar BAR bar help
4005 '''
4006 version = ''
4007
4008
4009class TestHelpRawDescription(HelpTestCase):
4010 """Test the RawTextHelpFormatter"""
4011
4012 parser_signature = Sig(
4013 prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter,
4014 description='Keep the formatting\n'
4015 ' exactly as it is written\n'
4016 '\n'
4017 'here\n')
4018
4019 argument_signatures = [
4020 Sig('--foo', help=' foo help should not\n'
4021 ' retain this odd formatting'),
4022 Sig('spam', help='spam help'),
4023 ]
4024 argument_group_signatures = [
4025 (Sig('title', description=' This text\n'
4026 ' should be indented\n'
4027 ' exactly like it is here\n'),
4028 [Sig('--bar', help='bar help')]),
4029 ]
4030 usage = '''\
4031 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
4032 '''
4033 help = usage + '''\
4034
4035 Keep the formatting
4036 exactly as it is written
4037
4038 here
4039
4040 positional arguments:
4041 spam spam help
4042
4043 optional arguments:
4044 -h, --help show this help message and exit
4045 --foo FOO foo help should not retain this odd formatting
4046
4047 title:
4048 This text
4049 should be indented
4050 exactly like it is here
4051
4052 --bar BAR bar help
4053 '''
4054 version = ''
4055
4056
4057class TestHelpArgumentDefaults(HelpTestCase):
4058 """Test the ArgumentDefaultsHelpFormatter"""
4059
4060 parser_signature = Sig(
4061 prog='PROG', formatter_class=argparse.ArgumentDefaultsHelpFormatter,
4062 description='description')
4063
4064 argument_signatures = [
4065 Sig('--foo', help='foo help - oh and by the way, %(default)s'),
4066 Sig('--bar', action='store_true', help='bar help'),
4067 Sig('spam', help='spam help'),
4068 Sig('badger', nargs='?', default='wooden', help='badger help'),
4069 ]
4070 argument_group_signatures = [
4071 (Sig('title', description='description'),
4072 [Sig('--baz', type=int, default=42, help='baz help')]),
4073 ]
4074 usage = '''\
4075 usage: PROG [-h] [--foo FOO] [--bar] [--baz BAZ] spam [badger]
4076 '''
4077 help = usage + '''\
4078
4079 description
4080
4081 positional arguments:
4082 spam spam help
4083 badger badger help (default: wooden)
4084
4085 optional arguments:
4086 -h, --help show this help message and exit
4087 --foo FOO foo help - oh and by the way, None
4088 --bar bar help (default: False)
4089
4090 title:
4091 description
4092
4093 --baz BAZ baz help (default: 42)
4094 '''
4095 version = ''
4096
Steven Bethard50fe5932010-05-24 03:47:38 +00004097class TestHelpVersionAction(HelpTestCase):
4098 """Test the default help for the version action"""
4099
4100 parser_signature = Sig(prog='PROG', description='description')
4101 argument_signatures = [Sig('-V', '--version', action='version', version='3.6')]
4102 argument_group_signatures = []
4103 usage = '''\
4104 usage: PROG [-h] [-V]
4105 '''
4106 help = usage + '''\
4107
4108 description
4109
4110 optional arguments:
4111 -h, --help show this help message and exit
4112 -V, --version show program's version number and exit
4113 '''
4114 version = ''
4115
Berker Peksagecb75e22015-04-10 16:11:12 +03004116
4117class TestHelpVersionActionSuppress(HelpTestCase):
4118 """Test that the --version argument can be suppressed in help messages"""
4119
4120 parser_signature = Sig(prog='PROG')
4121 argument_signatures = [
4122 Sig('-v', '--version', action='version', version='1.0',
4123 help=argparse.SUPPRESS),
4124 Sig('--foo', help='foo help'),
4125 Sig('spam', help='spam help'),
4126 ]
4127 argument_group_signatures = []
4128 usage = '''\
4129 usage: PROG [-h] [--foo FOO] spam
4130 '''
4131 help = usage + '''\
4132
4133 positional arguments:
4134 spam spam help
4135
4136 optional arguments:
4137 -h, --help show this help message and exit
4138 --foo FOO foo help
4139 '''
4140
4141
Steven Bethard8a6a1982011-03-27 13:53:53 +02004142class TestHelpSubparsersOrdering(HelpTestCase):
4143 """Test ordering of subcommands in help matches the code"""
4144 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004145 description='display some subcommands')
4146 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004147
4148 subparsers_signatures = [Sig(name=name)
4149 for name in ('a', 'b', 'c', 'd', 'e')]
4150
4151 usage = '''\
4152 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4153 '''
4154
4155 help = usage + '''\
4156
4157 display some subcommands
4158
4159 positional arguments:
4160 {a,b,c,d,e}
4161
4162 optional arguments:
4163 -h, --help show this help message and exit
4164 -v, --version show program's version number and exit
4165 '''
4166
4167 version = '''\
4168 0.1
4169 '''
4170
4171class TestHelpSubparsersWithHelpOrdering(HelpTestCase):
4172 """Test ordering of subcommands in help matches the code"""
4173 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004174 description='display some subcommands')
4175 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004176
4177 subcommand_data = (('a', 'a subcommand help'),
4178 ('b', 'b subcommand help'),
4179 ('c', 'c subcommand help'),
4180 ('d', 'd subcommand help'),
4181 ('e', 'e subcommand help'),
4182 )
4183
4184 subparsers_signatures = [Sig(name=name, help=help)
4185 for name, help in subcommand_data]
4186
4187 usage = '''\
4188 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4189 '''
4190
4191 help = usage + '''\
4192
4193 display some subcommands
4194
4195 positional arguments:
4196 {a,b,c,d,e}
4197 a a subcommand help
4198 b b subcommand help
4199 c c subcommand help
4200 d d subcommand help
4201 e e subcommand help
4202
4203 optional arguments:
4204 -h, --help show this help message and exit
4205 -v, --version show program's version number and exit
4206 '''
4207
4208 version = '''\
4209 0.1
4210 '''
4211
4212
Steven Bethard0331e902011-03-26 14:48:04 +01004213
4214class TestHelpMetavarTypeFormatter(HelpTestCase):
4215 """"""
4216
4217 def custom_type(string):
4218 return string
4219
4220 parser_signature = Sig(prog='PROG', description='description',
4221 formatter_class=argparse.MetavarTypeHelpFormatter)
4222 argument_signatures = [Sig('a', type=int),
4223 Sig('-b', type=custom_type),
4224 Sig('-c', type=float, metavar='SOME FLOAT')]
4225 argument_group_signatures = []
4226 usage = '''\
4227 usage: PROG [-h] [-b custom_type] [-c SOME FLOAT] int
4228 '''
4229 help = usage + '''\
4230
4231 description
4232
4233 positional arguments:
4234 int
4235
4236 optional arguments:
4237 -h, --help show this help message and exit
4238 -b custom_type
4239 -c SOME FLOAT
4240 '''
4241 version = ''
4242
4243
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004244# =====================================
4245# Optional/Positional constructor tests
4246# =====================================
4247
4248class TestInvalidArgumentConstructors(TestCase):
4249 """Test a bunch of invalid Argument constructors"""
4250
4251 def assertTypeError(self, *args, **kwargs):
4252 parser = argparse.ArgumentParser()
4253 self.assertRaises(TypeError, parser.add_argument,
4254 *args, **kwargs)
4255
4256 def assertValueError(self, *args, **kwargs):
4257 parser = argparse.ArgumentParser()
4258 self.assertRaises(ValueError, parser.add_argument,
4259 *args, **kwargs)
4260
4261 def test_invalid_keyword_arguments(self):
4262 self.assertTypeError('-x', bar=None)
4263 self.assertTypeError('-y', callback='foo')
4264 self.assertTypeError('-y', callback_args=())
4265 self.assertTypeError('-y', callback_kwargs={})
4266
4267 def test_missing_destination(self):
4268 self.assertTypeError()
4269 for action in ['append', 'store']:
4270 self.assertTypeError(action=action)
4271
4272 def test_invalid_option_strings(self):
4273 self.assertValueError('--')
4274 self.assertValueError('---')
4275
4276 def test_invalid_type(self):
4277 self.assertValueError('--foo', type='int')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004278 self.assertValueError('--foo', type=(int, float))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004279
4280 def test_invalid_action(self):
4281 self.assertValueError('-x', action='foo')
4282 self.assertValueError('foo', action='baz')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004283 self.assertValueError('--foo', action=('store', 'append'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004284 parser = argparse.ArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004285 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004286 parser.add_argument("--foo", action="store-true")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004287 self.assertIn('unknown action', str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004288
4289 def test_multiple_dest(self):
4290 parser = argparse.ArgumentParser()
4291 parser.add_argument(dest='foo')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004292 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004293 parser.add_argument('bar', dest='baz')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004294 self.assertIn('dest supplied twice for positional argument',
4295 str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004296
4297 def test_no_argument_actions(self):
4298 for action in ['store_const', 'store_true', 'store_false',
4299 'append_const', 'count']:
4300 for attrs in [dict(type=int), dict(nargs='+'),
4301 dict(choices='ab')]:
4302 self.assertTypeError('-x', action=action, **attrs)
4303
4304 def test_no_argument_no_const_actions(self):
4305 # options with zero arguments
4306 for action in ['store_true', 'store_false', 'count']:
4307
4308 # const is always disallowed
4309 self.assertTypeError('-x', const='foo', action=action)
4310
4311 # nargs is always disallowed
4312 self.assertTypeError('-x', nargs='*', action=action)
4313
4314 def test_more_than_one_argument_actions(self):
4315 for action in ['store', 'append']:
4316
4317 # nargs=0 is disallowed
4318 self.assertValueError('-x', nargs=0, action=action)
4319 self.assertValueError('spam', nargs=0, action=action)
4320
4321 # const is disallowed with non-optional arguments
4322 for nargs in [1, '*', '+']:
4323 self.assertValueError('-x', const='foo',
4324 nargs=nargs, action=action)
4325 self.assertValueError('spam', const='foo',
4326 nargs=nargs, action=action)
4327
4328 def test_required_const_actions(self):
4329 for action in ['store_const', 'append_const']:
4330
4331 # nargs is always disallowed
4332 self.assertTypeError('-x', nargs='+', action=action)
4333
4334 def test_parsers_action_missing_params(self):
4335 self.assertTypeError('command', action='parsers')
4336 self.assertTypeError('command', action='parsers', prog='PROG')
4337 self.assertTypeError('command', action='parsers',
4338 parser_class=argparse.ArgumentParser)
4339
4340 def test_required_positional(self):
4341 self.assertTypeError('foo', required=True)
4342
4343 def test_user_defined_action(self):
4344
4345 class Success(Exception):
4346 pass
4347
4348 class Action(object):
4349
4350 def __init__(self,
4351 option_strings,
4352 dest,
4353 const,
4354 default,
4355 required=False):
4356 if dest == 'spam':
4357 if const is Success:
4358 if default is Success:
4359 raise Success()
4360
4361 def __call__(self, *args, **kwargs):
4362 pass
4363
4364 parser = argparse.ArgumentParser()
4365 self.assertRaises(Success, parser.add_argument, '--spam',
4366 action=Action, default=Success, const=Success)
4367 self.assertRaises(Success, parser.add_argument, 'spam',
4368 action=Action, default=Success, const=Success)
4369
4370# ================================
4371# Actions returned by add_argument
4372# ================================
4373
4374class TestActionsReturned(TestCase):
4375
4376 def test_dest(self):
4377 parser = argparse.ArgumentParser()
4378 action = parser.add_argument('--foo')
4379 self.assertEqual(action.dest, 'foo')
4380 action = parser.add_argument('-b', '--bar')
4381 self.assertEqual(action.dest, 'bar')
4382 action = parser.add_argument('-x', '-y')
4383 self.assertEqual(action.dest, 'x')
4384
4385 def test_misc(self):
4386 parser = argparse.ArgumentParser()
4387 action = parser.add_argument('--foo', nargs='?', const=42,
4388 default=84, type=int, choices=[1, 2],
4389 help='FOO', metavar='BAR', dest='baz')
4390 self.assertEqual(action.nargs, '?')
4391 self.assertEqual(action.const, 42)
4392 self.assertEqual(action.default, 84)
4393 self.assertEqual(action.type, int)
4394 self.assertEqual(action.choices, [1, 2])
4395 self.assertEqual(action.help, 'FOO')
4396 self.assertEqual(action.metavar, 'BAR')
4397 self.assertEqual(action.dest, 'baz')
4398
4399
4400# ================================
4401# Argument conflict handling tests
4402# ================================
4403
4404class TestConflictHandling(TestCase):
4405
4406 def test_bad_type(self):
4407 self.assertRaises(ValueError, argparse.ArgumentParser,
4408 conflict_handler='foo')
4409
4410 def test_conflict_error(self):
4411 parser = argparse.ArgumentParser()
4412 parser.add_argument('-x')
4413 self.assertRaises(argparse.ArgumentError,
4414 parser.add_argument, '-x')
4415 parser.add_argument('--spam')
4416 self.assertRaises(argparse.ArgumentError,
4417 parser.add_argument, '--spam')
4418
4419 def test_resolve_error(self):
4420 get_parser = argparse.ArgumentParser
4421 parser = get_parser(prog='PROG', conflict_handler='resolve')
4422
4423 parser.add_argument('-x', help='OLD X')
4424 parser.add_argument('-x', help='NEW X')
4425 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4426 usage: PROG [-h] [-x X]
4427
4428 optional arguments:
4429 -h, --help show this help message and exit
4430 -x X NEW X
4431 '''))
4432
4433 parser.add_argument('--spam', metavar='OLD_SPAM')
4434 parser.add_argument('--spam', metavar='NEW_SPAM')
4435 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4436 usage: PROG [-h] [-x X] [--spam NEW_SPAM]
4437
4438 optional arguments:
4439 -h, --help show this help message and exit
4440 -x X NEW X
4441 --spam NEW_SPAM
4442 '''))
4443
4444
4445# =============================
4446# Help and Version option tests
4447# =============================
4448
4449class TestOptionalsHelpVersionActions(TestCase):
4450 """Test the help and version actions"""
4451
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004452 def assertPrintHelpExit(self, parser, args_str):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004453 with self.assertRaises(ArgumentParserError) as cm:
4454 parser.parse_args(args_str.split())
4455 self.assertEqual(parser.format_help(), cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004456
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004457 def assertArgumentParserError(self, parser, *args):
4458 self.assertRaises(ArgumentParserError, parser.parse_args, args)
4459
4460 def test_version(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004461 parser = ErrorRaisingArgumentParser()
4462 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004463 self.assertPrintHelpExit(parser, '-h')
4464 self.assertPrintHelpExit(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004465 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004466
4467 def test_version_format(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004468 parser = ErrorRaisingArgumentParser(prog='PPP')
4469 parser.add_argument('-v', '--version', action='version', version='%(prog)s 3.5')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004470 with self.assertRaises(ArgumentParserError) as cm:
4471 parser.parse_args(['-v'])
4472 self.assertEqual('PPP 3.5\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004473
4474 def test_version_no_help(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004475 parser = ErrorRaisingArgumentParser(add_help=False)
4476 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004477 self.assertArgumentParserError(parser, '-h')
4478 self.assertArgumentParserError(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004479 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004480
4481 def test_version_action(self):
4482 parser = ErrorRaisingArgumentParser(prog='XXX')
4483 parser.add_argument('-V', action='version', version='%(prog)s 3.7')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004484 with self.assertRaises(ArgumentParserError) as cm:
4485 parser.parse_args(['-V'])
4486 self.assertEqual('XXX 3.7\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004487
4488 def test_no_help(self):
4489 parser = ErrorRaisingArgumentParser(add_help=False)
4490 self.assertArgumentParserError(parser, '-h')
4491 self.assertArgumentParserError(parser, '--help')
4492 self.assertArgumentParserError(parser, '-v')
4493 self.assertArgumentParserError(parser, '--version')
4494
4495 def test_alternate_help_version(self):
4496 parser = ErrorRaisingArgumentParser()
4497 parser.add_argument('-x', action='help')
4498 parser.add_argument('-y', action='version')
4499 self.assertPrintHelpExit(parser, '-x')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004500 self.assertArgumentParserError(parser, '-v')
4501 self.assertArgumentParserError(parser, '--version')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004502 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004503
4504 def test_help_version_extra_arguments(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004505 parser = ErrorRaisingArgumentParser()
4506 parser.add_argument('--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004507 parser.add_argument('-x', action='store_true')
4508 parser.add_argument('y')
4509
4510 # try all combinations of valid prefixes and suffixes
4511 valid_prefixes = ['', '-x', 'foo', '-x bar', 'baz -x']
4512 valid_suffixes = valid_prefixes + ['--bad-option', 'foo bar baz']
4513 for prefix in valid_prefixes:
4514 for suffix in valid_suffixes:
4515 format = '%s %%s %s' % (prefix, suffix)
4516 self.assertPrintHelpExit(parser, format % '-h')
4517 self.assertPrintHelpExit(parser, format % '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004518 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004519
4520
4521# ======================
4522# str() and repr() tests
4523# ======================
4524
4525class TestStrings(TestCase):
4526 """Test str() and repr() on Optionals and Positionals"""
4527
4528 def assertStringEqual(self, obj, result_string):
4529 for func in [str, repr]:
4530 self.assertEqual(func(obj), result_string)
4531
4532 def test_optional(self):
4533 option = argparse.Action(
4534 option_strings=['--foo', '-a', '-b'],
4535 dest='b',
4536 type='int',
4537 nargs='+',
4538 default=42,
4539 choices=[1, 2, 3],
4540 help='HELP',
4541 metavar='METAVAR')
4542 string = (
4543 "Action(option_strings=['--foo', '-a', '-b'], dest='b', "
4544 "nargs='+', const=None, default=42, type='int', "
4545 "choices=[1, 2, 3], help='HELP', metavar='METAVAR')")
4546 self.assertStringEqual(option, string)
4547
4548 def test_argument(self):
4549 argument = argparse.Action(
4550 option_strings=[],
4551 dest='x',
4552 type=float,
4553 nargs='?',
4554 default=2.5,
4555 choices=[0.5, 1.5, 2.5],
4556 help='H HH H',
4557 metavar='MV MV MV')
4558 string = (
4559 "Action(option_strings=[], dest='x', nargs='?', "
4560 "const=None, default=2.5, type=%r, choices=[0.5, 1.5, 2.5], "
4561 "help='H HH H', metavar='MV MV MV')" % float)
4562 self.assertStringEqual(argument, string)
4563
4564 def test_namespace(self):
4565 ns = argparse.Namespace(foo=42, bar='spam')
4566 string = "Namespace(bar='spam', foo=42)"
4567 self.assertStringEqual(ns, string)
4568
Berker Peksag76b17142015-07-29 23:51:47 +03004569 def test_namespace_starkwargs_notidentifier(self):
4570 ns = argparse.Namespace(**{'"': 'quote'})
4571 string = """Namespace(**{'"': 'quote'})"""
4572 self.assertStringEqual(ns, string)
4573
4574 def test_namespace_kwargs_and_starkwargs_notidentifier(self):
4575 ns = argparse.Namespace(a=1, **{'"': 'quote'})
4576 string = """Namespace(a=1, **{'"': 'quote'})"""
4577 self.assertStringEqual(ns, string)
4578
4579 def test_namespace_starkwargs_identifier(self):
4580 ns = argparse.Namespace(**{'valid': True})
4581 string = "Namespace(valid=True)"
4582 self.assertStringEqual(ns, string)
4583
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004584 def test_parser(self):
4585 parser = argparse.ArgumentParser(prog='PROG')
4586 string = (
4587 "ArgumentParser(prog='PROG', usage=None, description=None, "
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004588 "formatter_class=%r, conflict_handler='error', "
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004589 "add_help=True)" % argparse.HelpFormatter)
4590 self.assertStringEqual(parser, string)
4591
4592# ===============
4593# Namespace tests
4594# ===============
4595
4596class TestNamespace(TestCase):
4597
4598 def test_constructor(self):
4599 ns = argparse.Namespace()
4600 self.assertRaises(AttributeError, getattr, ns, 'x')
4601
4602 ns = argparse.Namespace(a=42, b='spam')
4603 self.assertEqual(ns.a, 42)
4604 self.assertEqual(ns.b, 'spam')
4605
4606 def test_equality(self):
4607 ns1 = argparse.Namespace(a=1, b=2)
4608 ns2 = argparse.Namespace(b=2, a=1)
4609 ns3 = argparse.Namespace(a=1)
4610 ns4 = argparse.Namespace(b=2)
4611
4612 self.assertEqual(ns1, ns2)
4613 self.assertNotEqual(ns1, ns3)
4614 self.assertNotEqual(ns1, ns4)
4615 self.assertNotEqual(ns2, ns3)
4616 self.assertNotEqual(ns2, ns4)
4617 self.assertTrue(ns1 != ns3)
4618 self.assertTrue(ns1 != ns4)
4619 self.assertTrue(ns2 != ns3)
4620 self.assertTrue(ns2 != ns4)
4621
Berker Peksagc16387b2016-09-28 17:21:52 +03004622 def test_equality_returns_notimplemented(self):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07004623 # See issue 21481
4624 ns = argparse.Namespace(a=1, b=2)
4625 self.assertIs(ns.__eq__(None), NotImplemented)
4626 self.assertIs(ns.__ne__(None), NotImplemented)
4627
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004628
4629# ===================
4630# File encoding tests
4631# ===================
4632
4633class TestEncoding(TestCase):
4634
4635 def _test_module_encoding(self, path):
4636 path, _ = os.path.splitext(path)
4637 path += ".py"
Victor Stinner272d8882017-06-16 08:59:01 +02004638 with open(path, 'r', encoding='utf-8') as f:
Antoine Pitroub86680e2010-10-14 21:15:17 +00004639 f.read()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004640
4641 def test_argparse_module_encoding(self):
4642 self._test_module_encoding(argparse.__file__)
4643
4644 def test_test_argparse_module_encoding(self):
4645 self._test_module_encoding(__file__)
4646
4647# ===================
4648# ArgumentError tests
4649# ===================
4650
4651class TestArgumentError(TestCase):
4652
4653 def test_argument_error(self):
4654 msg = "my error here"
4655 error = argparse.ArgumentError(None, msg)
4656 self.assertEqual(str(error), msg)
4657
4658# =======================
4659# ArgumentTypeError tests
4660# =======================
4661
R. David Murray722b5fd2010-11-20 03:48:58 +00004662class TestArgumentTypeError(TestCase):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004663
4664 def test_argument_type_error(self):
4665
4666 def spam(string):
4667 raise argparse.ArgumentTypeError('spam!')
4668
4669 parser = ErrorRaisingArgumentParser(prog='PROG', add_help=False)
4670 parser.add_argument('x', type=spam)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004671 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004672 parser.parse_args(['XXX'])
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004673 self.assertEqual('usage: PROG x\nPROG: error: argument x: spam!\n',
4674 cm.exception.stderr)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004675
R David Murrayf97c59a2011-06-09 12:34:07 -04004676# =========================
4677# MessageContentError tests
4678# =========================
4679
4680class TestMessageContentError(TestCase):
4681
4682 def test_missing_argument_name_in_message(self):
4683 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4684 parser.add_argument('req_pos', type=str)
4685 parser.add_argument('-req_opt', type=int, required=True)
4686 parser.add_argument('need_one', type=str, nargs='+')
4687
4688 with self.assertRaises(ArgumentParserError) as cm:
4689 parser.parse_args([])
4690 msg = str(cm.exception)
4691 self.assertRegex(msg, 'req_pos')
4692 self.assertRegex(msg, 'req_opt')
4693 self.assertRegex(msg, 'need_one')
4694 with self.assertRaises(ArgumentParserError) as cm:
4695 parser.parse_args(['myXargument'])
4696 msg = str(cm.exception)
4697 self.assertNotIn(msg, 'req_pos')
4698 self.assertRegex(msg, 'req_opt')
4699 self.assertRegex(msg, 'need_one')
4700 with self.assertRaises(ArgumentParserError) as cm:
4701 parser.parse_args(['myXargument', '-req_opt=1'])
4702 msg = str(cm.exception)
4703 self.assertNotIn(msg, 'req_pos')
4704 self.assertNotIn(msg, 'req_opt')
4705 self.assertRegex(msg, 'need_one')
4706
4707 def test_optional_optional_not_in_message(self):
4708 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4709 parser.add_argument('req_pos', type=str)
4710 parser.add_argument('--req_opt', type=int, required=True)
4711 parser.add_argument('--opt_opt', type=bool, nargs='?',
4712 default=True)
4713 with self.assertRaises(ArgumentParserError) as cm:
4714 parser.parse_args([])
4715 msg = str(cm.exception)
4716 self.assertRegex(msg, 'req_pos')
4717 self.assertRegex(msg, 'req_opt')
4718 self.assertNotIn(msg, 'opt_opt')
4719 with self.assertRaises(ArgumentParserError) as cm:
4720 parser.parse_args(['--req_opt=1'])
4721 msg = str(cm.exception)
4722 self.assertRegex(msg, 'req_pos')
4723 self.assertNotIn(msg, 'req_opt')
4724 self.assertNotIn(msg, 'opt_opt')
4725
4726 def test_optional_positional_not_in_message(self):
4727 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4728 parser.add_argument('req_pos')
4729 parser.add_argument('optional_positional', nargs='?', default='eggs')
4730 with self.assertRaises(ArgumentParserError) as cm:
4731 parser.parse_args([])
4732 msg = str(cm.exception)
4733 self.assertRegex(msg, 'req_pos')
4734 self.assertNotIn(msg, 'optional_positional')
4735
4736
R David Murray6fb8fb12012-08-31 22:45:20 -04004737# ================================================
4738# Check that the type function is called only once
4739# ================================================
4740
4741class TestTypeFunctionCallOnlyOnce(TestCase):
4742
4743 def test_type_function_call_only_once(self):
4744 def spam(string_to_convert):
4745 self.assertEqual(string_to_convert, 'spam!')
4746 return 'foo_converted'
4747
4748 parser = argparse.ArgumentParser()
4749 parser.add_argument('--foo', type=spam, default='bar')
4750 args = parser.parse_args('--foo spam!'.split())
4751 self.assertEqual(NS(foo='foo_converted'), args)
4752
Barry Warsaweaae1b72012-09-12 14:34:50 -04004753# ==================================================================
4754# Check semantics regarding the default argument and type conversion
4755# ==================================================================
R David Murray6fb8fb12012-08-31 22:45:20 -04004756
Barry Warsaweaae1b72012-09-12 14:34:50 -04004757class TestTypeFunctionCalledOnDefault(TestCase):
R David Murray6fb8fb12012-08-31 22:45:20 -04004758
4759 def test_type_function_call_with_non_string_default(self):
4760 def spam(int_to_convert):
4761 self.assertEqual(int_to_convert, 0)
4762 return 'foo_converted'
4763
4764 parser = argparse.ArgumentParser()
4765 parser.add_argument('--foo', type=spam, default=0)
4766 args = parser.parse_args([])
Barry Warsaweaae1b72012-09-12 14:34:50 -04004767 # foo should *not* be converted because its default is not a string.
4768 self.assertEqual(NS(foo=0), args)
4769
4770 def test_type_function_call_with_string_default(self):
4771 def spam(int_to_convert):
4772 return 'foo_converted'
4773
4774 parser = argparse.ArgumentParser()
4775 parser.add_argument('--foo', type=spam, default='0')
4776 args = parser.parse_args([])
4777 # foo is converted because its default is a string.
R David Murray6fb8fb12012-08-31 22:45:20 -04004778 self.assertEqual(NS(foo='foo_converted'), args)
4779
Barry Warsaweaae1b72012-09-12 14:34:50 -04004780 def test_no_double_type_conversion_of_default(self):
4781 def extend(str_to_convert):
4782 return str_to_convert + '*'
4783
4784 parser = argparse.ArgumentParser()
4785 parser.add_argument('--test', type=extend, default='*')
4786 args = parser.parse_args([])
4787 # The test argument will be two stars, one coming from the default
4788 # value and one coming from the type conversion being called exactly
4789 # once.
4790 self.assertEqual(NS(test='**'), args)
4791
Barry Warsaw4b2f9e92012-09-11 22:38:47 -04004792 def test_issue_15906(self):
4793 # Issue #15906: When action='append', type=str, default=[] are
4794 # providing, the dest value was the string representation "[]" when it
4795 # should have been an empty list.
4796 parser = argparse.ArgumentParser()
4797 parser.add_argument('--test', dest='test', type=str,
4798 default=[], action='append')
4799 args = parser.parse_args([])
4800 self.assertEqual(args.test, [])
4801
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004802# ======================
4803# parse_known_args tests
4804# ======================
4805
4806class TestParseKnownArgs(TestCase):
4807
R David Murrayb5228282012-09-08 12:08:01 -04004808 def test_arguments_tuple(self):
4809 parser = argparse.ArgumentParser()
4810 parser.parse_args(())
4811
4812 def test_arguments_list(self):
4813 parser = argparse.ArgumentParser()
4814 parser.parse_args([])
4815
4816 def test_arguments_tuple_positional(self):
4817 parser = argparse.ArgumentParser()
4818 parser.add_argument('x')
4819 parser.parse_args(('x',))
4820
4821 def test_arguments_list_positional(self):
4822 parser = argparse.ArgumentParser()
4823 parser.add_argument('x')
4824 parser.parse_args(['x'])
4825
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004826 def test_optionals(self):
4827 parser = argparse.ArgumentParser()
4828 parser.add_argument('--foo')
4829 args, extras = parser.parse_known_args('--foo F --bar --baz'.split())
4830 self.assertEqual(NS(foo='F'), args)
4831 self.assertEqual(['--bar', '--baz'], extras)
4832
4833 def test_mixed(self):
4834 parser = argparse.ArgumentParser()
4835 parser.add_argument('-v', nargs='?', const=1, type=int)
4836 parser.add_argument('--spam', action='store_false')
4837 parser.add_argument('badger')
4838
4839 argv = ["B", "C", "--foo", "-v", "3", "4"]
4840 args, extras = parser.parse_known_args(argv)
4841 self.assertEqual(NS(v=3, spam=True, badger="B"), args)
4842 self.assertEqual(["C", "--foo", "4"], extras)
4843
R. David Murray0f6b9d22017-09-06 20:25:40 -04004844# ===========================
4845# parse_intermixed_args tests
4846# ===========================
4847
4848class TestIntermixedArgs(TestCase):
4849 def test_basic(self):
4850 # test parsing intermixed optionals and positionals
4851 parser = argparse.ArgumentParser(prog='PROG')
4852 parser.add_argument('--foo', dest='foo')
4853 bar = parser.add_argument('--bar', dest='bar', required=True)
4854 parser.add_argument('cmd')
4855 parser.add_argument('rest', nargs='*', type=int)
4856 argv = 'cmd --foo x 1 --bar y 2 3'.split()
4857 args = parser.parse_intermixed_args(argv)
4858 # rest gets [1,2,3] despite the foo and bar strings
4859 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args)
4860
4861 args, extras = parser.parse_known_args(argv)
4862 # cannot parse the '1,2,3'
4863 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[]), args)
4864 self.assertEqual(["1", "2", "3"], extras)
4865
4866 argv = 'cmd --foo x 1 --error 2 --bar y 3'.split()
4867 args, extras = parser.parse_known_intermixed_args(argv)
4868 # unknown optionals go into extras
4869 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1]), args)
4870 self.assertEqual(['--error', '2', '3'], extras)
4871
4872 # restores attributes that were temporarily changed
4873 self.assertIsNone(parser.usage)
4874 self.assertEqual(bar.required, True)
4875
4876 def test_remainder(self):
4877 # Intermixed and remainder are incompatible
4878 parser = ErrorRaisingArgumentParser(prog='PROG')
4879 parser.add_argument('-z')
4880 parser.add_argument('x')
4881 parser.add_argument('y', nargs='...')
4882 argv = 'X A B -z Z'.split()
4883 # intermixed fails with '...' (also 'A...')
4884 # self.assertRaises(TypeError, parser.parse_intermixed_args, argv)
4885 with self.assertRaises(TypeError) as cm:
4886 parser.parse_intermixed_args(argv)
4887 self.assertRegex(str(cm.exception), r'\.\.\.')
4888
4889 def test_exclusive(self):
4890 # mutually exclusive group; intermixed works fine
4891 parser = ErrorRaisingArgumentParser(prog='PROG')
4892 group = parser.add_mutually_exclusive_group(required=True)
4893 group.add_argument('--foo', action='store_true', help='FOO')
4894 group.add_argument('--spam', help='SPAM')
4895 parser.add_argument('badger', nargs='*', default='X', help='BADGER')
4896 args = parser.parse_intermixed_args('1 --foo 2'.split())
4897 self.assertEqual(NS(badger=['1', '2'], foo=True, spam=None), args)
4898 self.assertRaises(ArgumentParserError, parser.parse_intermixed_args, '1 2'.split())
4899 self.assertEqual(group.required, True)
4900
4901 def test_exclusive_incompatible(self):
4902 # mutually exclusive group including positional - fail
4903 parser = ErrorRaisingArgumentParser(prog='PROG')
4904 group = parser.add_mutually_exclusive_group(required=True)
4905 group.add_argument('--foo', action='store_true', help='FOO')
4906 group.add_argument('--spam', help='SPAM')
4907 group.add_argument('badger', nargs='*', default='X', help='BADGER')
4908 self.assertRaises(TypeError, parser.parse_intermixed_args, [])
4909 self.assertEqual(group.required, True)
4910
4911class TestIntermixedMessageContentError(TestCase):
4912 # case where Intermixed gives different error message
4913 # error is raised by 1st parsing step
4914 def test_missing_argument_name_in_message(self):
4915 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4916 parser.add_argument('req_pos', type=str)
4917 parser.add_argument('-req_opt', type=int, required=True)
4918
4919 with self.assertRaises(ArgumentParserError) as cm:
4920 parser.parse_args([])
4921 msg = str(cm.exception)
4922 self.assertRegex(msg, 'req_pos')
4923 self.assertRegex(msg, 'req_opt')
4924
4925 with self.assertRaises(ArgumentParserError) as cm:
4926 parser.parse_intermixed_args([])
4927 msg = str(cm.exception)
4928 self.assertNotRegex(msg, 'req_pos')
4929 self.assertRegex(msg, 'req_opt')
4930
Steven Bethard8d9a4622011-03-26 17:33:56 +01004931# ==========================
4932# add_argument metavar tests
4933# ==========================
4934
4935class TestAddArgumentMetavar(TestCase):
4936
4937 EXPECTED_MESSAGE = "length of metavar tuple does not match nargs"
4938
4939 def do_test_no_exception(self, nargs, metavar):
4940 parser = argparse.ArgumentParser()
4941 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
4942
4943 def do_test_exception(self, nargs, metavar):
4944 parser = argparse.ArgumentParser()
4945 with self.assertRaises(ValueError) as cm:
4946 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
4947 self.assertEqual(cm.exception.args[0], self.EXPECTED_MESSAGE)
4948
4949 # Unit tests for different values of metavar when nargs=None
4950
4951 def test_nargs_None_metavar_string(self):
4952 self.do_test_no_exception(nargs=None, metavar="1")
4953
4954 def test_nargs_None_metavar_length0(self):
4955 self.do_test_exception(nargs=None, metavar=tuple())
4956
4957 def test_nargs_None_metavar_length1(self):
Miss Islington (bot)842985f2018-06-08 04:33:50 -07004958 self.do_test_no_exception(nargs=None, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01004959
4960 def test_nargs_None_metavar_length2(self):
4961 self.do_test_exception(nargs=None, metavar=("1", "2"))
4962
4963 def test_nargs_None_metavar_length3(self):
4964 self.do_test_exception(nargs=None, metavar=("1", "2", "3"))
4965
4966 # Unit tests for different values of metavar when nargs=?
4967
4968 def test_nargs_optional_metavar_string(self):
4969 self.do_test_no_exception(nargs="?", metavar="1")
4970
4971 def test_nargs_optional_metavar_length0(self):
4972 self.do_test_exception(nargs="?", metavar=tuple())
4973
4974 def test_nargs_optional_metavar_length1(self):
Miss Islington (bot)842985f2018-06-08 04:33:50 -07004975 self.do_test_no_exception(nargs="?", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01004976
4977 def test_nargs_optional_metavar_length2(self):
4978 self.do_test_exception(nargs="?", metavar=("1", "2"))
4979
4980 def test_nargs_optional_metavar_length3(self):
4981 self.do_test_exception(nargs="?", metavar=("1", "2", "3"))
4982
4983 # Unit tests for different values of metavar when nargs=*
4984
4985 def test_nargs_zeroormore_metavar_string(self):
4986 self.do_test_no_exception(nargs="*", metavar="1")
4987
4988 def test_nargs_zeroormore_metavar_length0(self):
4989 self.do_test_exception(nargs="*", metavar=tuple())
4990
4991 def test_nargs_zeroormore_metavar_length1(self):
Miss Islington (bot)842985f2018-06-08 04:33:50 -07004992 self.do_test_exception(nargs="*", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01004993
4994 def test_nargs_zeroormore_metavar_length2(self):
4995 self.do_test_no_exception(nargs="*", metavar=("1", "2"))
4996
4997 def test_nargs_zeroormore_metavar_length3(self):
4998 self.do_test_exception(nargs="*", metavar=("1", "2", "3"))
4999
5000 # Unit tests for different values of metavar when nargs=+
5001
5002 def test_nargs_oneormore_metavar_string(self):
5003 self.do_test_no_exception(nargs="+", metavar="1")
5004
5005 def test_nargs_oneormore_metavar_length0(self):
5006 self.do_test_exception(nargs="+", metavar=tuple())
5007
5008 def test_nargs_oneormore_metavar_length1(self):
Miss Islington (bot)842985f2018-06-08 04:33:50 -07005009 self.do_test_exception(nargs="+", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005010
5011 def test_nargs_oneormore_metavar_length2(self):
5012 self.do_test_no_exception(nargs="+", metavar=("1", "2"))
5013
5014 def test_nargs_oneormore_metavar_length3(self):
5015 self.do_test_exception(nargs="+", metavar=("1", "2", "3"))
5016
5017 # Unit tests for different values of metavar when nargs=...
5018
5019 def test_nargs_remainder_metavar_string(self):
5020 self.do_test_no_exception(nargs="...", metavar="1")
5021
5022 def test_nargs_remainder_metavar_length0(self):
5023 self.do_test_no_exception(nargs="...", metavar=tuple())
5024
5025 def test_nargs_remainder_metavar_length1(self):
Miss Islington (bot)842985f2018-06-08 04:33:50 -07005026 self.do_test_no_exception(nargs="...", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005027
5028 def test_nargs_remainder_metavar_length2(self):
5029 self.do_test_no_exception(nargs="...", metavar=("1", "2"))
5030
5031 def test_nargs_remainder_metavar_length3(self):
5032 self.do_test_no_exception(nargs="...", metavar=("1", "2", "3"))
5033
5034 # Unit tests for different values of metavar when nargs=A...
5035
5036 def test_nargs_parser_metavar_string(self):
5037 self.do_test_no_exception(nargs="A...", metavar="1")
5038
5039 def test_nargs_parser_metavar_length0(self):
5040 self.do_test_exception(nargs="A...", metavar=tuple())
5041
5042 def test_nargs_parser_metavar_length1(self):
Miss Islington (bot)842985f2018-06-08 04:33:50 -07005043 self.do_test_no_exception(nargs="A...", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005044
5045 def test_nargs_parser_metavar_length2(self):
5046 self.do_test_exception(nargs="A...", metavar=("1", "2"))
5047
5048 def test_nargs_parser_metavar_length3(self):
5049 self.do_test_exception(nargs="A...", metavar=("1", "2", "3"))
5050
5051 # Unit tests for different values of metavar when nargs=1
5052
5053 def test_nargs_1_metavar_string(self):
5054 self.do_test_no_exception(nargs=1, metavar="1")
5055
5056 def test_nargs_1_metavar_length0(self):
5057 self.do_test_exception(nargs=1, metavar=tuple())
5058
5059 def test_nargs_1_metavar_length1(self):
Miss Islington (bot)842985f2018-06-08 04:33:50 -07005060 self.do_test_no_exception(nargs=1, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005061
5062 def test_nargs_1_metavar_length2(self):
5063 self.do_test_exception(nargs=1, metavar=("1", "2"))
5064
5065 def test_nargs_1_metavar_length3(self):
5066 self.do_test_exception(nargs=1, metavar=("1", "2", "3"))
5067
5068 # Unit tests for different values of metavar when nargs=2
5069
5070 def test_nargs_2_metavar_string(self):
5071 self.do_test_no_exception(nargs=2, metavar="1")
5072
5073 def test_nargs_2_metavar_length0(self):
5074 self.do_test_exception(nargs=2, metavar=tuple())
5075
5076 def test_nargs_2_metavar_length1(self):
Miss Islington (bot)842985f2018-06-08 04:33:50 -07005077 self.do_test_exception(nargs=2, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005078
5079 def test_nargs_2_metavar_length2(self):
5080 self.do_test_no_exception(nargs=2, metavar=("1", "2"))
5081
5082 def test_nargs_2_metavar_length3(self):
5083 self.do_test_exception(nargs=2, metavar=("1", "2", "3"))
5084
5085 # Unit tests for different values of metavar when nargs=3
5086
5087 def test_nargs_3_metavar_string(self):
5088 self.do_test_no_exception(nargs=3, metavar="1")
5089
5090 def test_nargs_3_metavar_length0(self):
5091 self.do_test_exception(nargs=3, metavar=tuple())
5092
5093 def test_nargs_3_metavar_length1(self):
Miss Islington (bot)842985f2018-06-08 04:33:50 -07005094 self.do_test_exception(nargs=3, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005095
5096 def test_nargs_3_metavar_length2(self):
5097 self.do_test_exception(nargs=3, metavar=("1", "2"))
5098
5099 def test_nargs_3_metavar_length3(self):
5100 self.do_test_no_exception(nargs=3, metavar=("1", "2", "3"))
5101
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005102# ============================
5103# from argparse import * tests
5104# ============================
5105
5106class TestImportStar(TestCase):
5107
5108 def test(self):
5109 for name in argparse.__all__:
5110 self.assertTrue(hasattr(argparse, name))
5111
Steven Bethard72c55382010-11-01 15:23:12 +00005112 def test_all_exports_everything_but_modules(self):
5113 items = [
5114 name
5115 for name, value in vars(argparse).items()
Éric Araujo12159152010-12-04 17:31:49 +00005116 if not (name.startswith("_") or name == 'ngettext')
Steven Bethard72c55382010-11-01 15:23:12 +00005117 if not inspect.ismodule(value)
5118 ]
5119 self.assertEqual(sorted(items), sorted(argparse.__all__))
5120
Miss Islington (bot)842985f2018-06-08 04:33:50 -07005121
5122class TestWrappingMetavar(TestCase):
5123
5124 def setUp(self):
5125 self.parser = ErrorRaisingArgumentParser(
5126 'this_is_spammy_prog_with_a_long_name_sorry_about_the_name'
5127 )
5128 # this metavar was triggering library assertion errors due to usage
5129 # message formatting incorrectly splitting on the ] chars within
5130 metavar = '<http[s]://example:1234>'
5131 self.parser.add_argument('--proxy', metavar=metavar)
5132
5133 def test_help_with_metavar(self):
5134 help_text = self.parser.format_help()
5135 self.assertEqual(help_text, textwrap.dedent('''\
5136 usage: this_is_spammy_prog_with_a_long_name_sorry_about_the_name
5137 [-h] [--proxy <http[s]://example:1234>]
5138
5139 optional arguments:
5140 -h, --help show this help message and exit
5141 --proxy <http[s]://example:1234>
5142 '''))
5143
5144
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005145def test_main():
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02005146 support.run_unittest(__name__)
Benjamin Peterson4fd181c2010-03-02 23:46:42 +00005147 # Remove global references to avoid looking like we have refleaks.
5148 RFile.seen = {}
5149 WFile.seen = set()
5150
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005151
5152
5153if __name__ == '__main__':
5154 test_main()