blob: c4440e4df7c15b680a0473b3f86ec573fec62bf7 [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')
1935 self._test_required_subparsers(parser)
1936
1937 def test_optional_subparsers(self):
1938 parser = ErrorRaisingArgumentParser()
1939 subparsers = parser.add_subparsers(dest='command', required=False)
1940 subparsers.add_parser('run')
1941 # No error here
1942 ret = parser.parse_args(())
1943 self.assertIsNone(ret.command)
1944
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001945 def test_help(self):
1946 self.assertEqual(self.parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01001947 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001948 self.assertEqual(self.parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01001949 usage: PROG [-h] [--foo] bar {1,2,3} ...
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001950
1951 main description
1952
1953 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01001954 bar bar help
1955 {1,2,3} command help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001956
1957 optional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01001958 -h, --help show this help message and exit
1959 --foo foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001960 '''))
1961
R. David Murray88c49fe2010-08-03 17:56:09 +00001962 def test_help_extra_prefix_chars(self):
1963 # Make sure - is still used for help if it is a non-first prefix char
1964 parser = self._get_parser(prefix_chars='+:-')
1965 self.assertEqual(parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01001966 'usage: PROG [-h] [++foo] bar {1,2,3} ...\n')
R. David Murray88c49fe2010-08-03 17:56:09 +00001967 self.assertEqual(parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01001968 usage: PROG [-h] [++foo] bar {1,2,3} ...
R. David Murray88c49fe2010-08-03 17:56:09 +00001969
1970 main description
1971
1972 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01001973 bar bar help
1974 {1,2,3} command help
R. David Murray88c49fe2010-08-03 17:56:09 +00001975
1976 optional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01001977 -h, --help show this help message and exit
1978 ++foo foo help
R. David Murray88c49fe2010-08-03 17:56:09 +00001979 '''))
1980
Xiang Zhang7fe28ad2017-01-22 14:37:22 +08001981 def test_help_non_breaking_spaces(self):
1982 parser = ErrorRaisingArgumentParser(
1983 prog='PROG', description='main description')
1984 parser.add_argument(
1985 "--non-breaking", action='store_false',
1986 help='help message containing non-breaking spaces shall not '
1987 'wrap\N{NO-BREAK SPACE}at non-breaking spaces')
1988 self.assertEqual(parser.format_help(), textwrap.dedent('''\
1989 usage: PROG [-h] [--non-breaking]
1990
1991 main description
1992
1993 optional arguments:
1994 -h, --help show this help message and exit
1995 --non-breaking help message containing non-breaking spaces shall not
1996 wrap\N{NO-BREAK SPACE}at non-breaking spaces
1997 '''))
R. David Murray88c49fe2010-08-03 17:56:09 +00001998
1999 def test_help_alternate_prefix_chars(self):
2000 parser = self._get_parser(prefix_chars='+:/')
2001 self.assertEqual(parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002002 'usage: PROG [+h] [++foo] bar {1,2,3} ...\n')
R. David Murray88c49fe2010-08-03 17:56:09 +00002003 self.assertEqual(parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002004 usage: PROG [+h] [++foo] bar {1,2,3} ...
R. David Murray88c49fe2010-08-03 17:56:09 +00002005
2006 main description
2007
2008 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002009 bar bar help
2010 {1,2,3} command help
R. David Murray88c49fe2010-08-03 17:56:09 +00002011
2012 optional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002013 +h, ++help show this help message and exit
2014 ++foo foo help
R. David Murray88c49fe2010-08-03 17:56:09 +00002015 '''))
2016
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002017 def test_parser_command_help(self):
2018 self.assertEqual(self.command_help_parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002019 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002020 self.assertEqual(self.command_help_parser.format_help(),
2021 textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002022 usage: PROG [-h] [--foo] bar {1,2,3} ...
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002023
2024 main description
2025
2026 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002027 bar bar help
2028 {1,2,3} command help
2029 1 1 help
2030 2 2 help
2031 3 3 help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002032
2033 optional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002034 -h, --help show this help message and exit
2035 --foo foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002036 '''))
2037
2038 def test_subparser_title_help(self):
2039 parser = ErrorRaisingArgumentParser(prog='PROG',
2040 description='main description')
2041 parser.add_argument('--foo', action='store_true', help='foo help')
2042 parser.add_argument('bar', help='bar help')
2043 subparsers = parser.add_subparsers(title='subcommands',
2044 description='command help',
2045 help='additional text')
2046 parser1 = subparsers.add_parser('1')
2047 parser2 = subparsers.add_parser('2')
2048 self.assertEqual(parser.format_usage(),
2049 'usage: PROG [-h] [--foo] bar {1,2} ...\n')
2050 self.assertEqual(parser.format_help(), textwrap.dedent('''\
2051 usage: PROG [-h] [--foo] bar {1,2} ...
2052
2053 main description
2054
2055 positional arguments:
2056 bar bar help
2057
2058 optional arguments:
2059 -h, --help show this help message and exit
2060 --foo foo help
2061
2062 subcommands:
2063 command help
2064
2065 {1,2} additional text
2066 '''))
2067
2068 def _test_subparser_help(self, args_str, expected_help):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002069 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002070 self.parser.parse_args(args_str.split())
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002071 self.assertEqual(expected_help, cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002072
2073 def test_subparser1_help(self):
2074 self._test_subparser_help('5.0 1 -h', textwrap.dedent('''\
2075 usage: PROG bar 1 [-h] [-w W] {a,b,c}
2076
2077 1 description
2078
2079 positional arguments:
2080 {a,b,c} x help
2081
2082 optional arguments:
2083 -h, --help show this help message and exit
2084 -w W w help
2085 '''))
2086
2087 def test_subparser2_help(self):
2088 self._test_subparser_help('5.0 2 -h', textwrap.dedent('''\
2089 usage: PROG bar 2 [-h] [-y {1,2,3}] [z [z ...]]
2090
2091 2 description
2092
2093 positional arguments:
2094 z z help
2095
2096 optional arguments:
2097 -h, --help show this help message and exit
2098 -y {1,2,3} y help
2099 '''))
2100
Steven Bethardfd311a72010-12-18 11:19:23 +00002101 def test_alias_invocation(self):
2102 parser = self._get_parser(aliases=True)
2103 self.assertEqual(
2104 parser.parse_known_args('0.5 1alias1 b'.split()),
2105 (NS(foo=False, bar=0.5, w=None, x='b'), []),
2106 )
2107 self.assertEqual(
2108 parser.parse_known_args('0.5 1alias2 b'.split()),
2109 (NS(foo=False, bar=0.5, w=None, x='b'), []),
2110 )
2111
2112 def test_error_alias_invocation(self):
2113 parser = self._get_parser(aliases=True)
2114 self.assertArgumentParserError(parser.parse_args,
2115 '0.5 1alias3 b'.split())
2116
2117 def test_alias_help(self):
2118 parser = self._get_parser(aliases=True, subparser_help=True)
2119 self.maxDiff = None
2120 self.assertEqual(parser.format_help(), textwrap.dedent("""\
2121 usage: PROG [-h] [--foo] bar COMMAND ...
2122
2123 main description
2124
2125 positional arguments:
2126 bar bar help
2127
2128 optional arguments:
2129 -h, --help show this help message and exit
2130 --foo foo help
2131
2132 commands:
2133 COMMAND
2134 1 (1alias1, 1alias2)
2135 1 help
2136 2 2 help
R David Murray00528e82012-07-21 22:48:35 -04002137 3 3 help
Steven Bethardfd311a72010-12-18 11:19:23 +00002138 """))
2139
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002140# ============
2141# Groups tests
2142# ============
2143
2144class TestPositionalsGroups(TestCase):
2145 """Tests that order of group positionals matches construction order"""
2146
2147 def test_nongroup_first(self):
2148 parser = ErrorRaisingArgumentParser()
2149 parser.add_argument('foo')
2150 group = parser.add_argument_group('g')
2151 group.add_argument('bar')
2152 parser.add_argument('baz')
2153 expected = NS(foo='1', bar='2', baz='3')
2154 result = parser.parse_args('1 2 3'.split())
2155 self.assertEqual(expected, result)
2156
2157 def test_group_first(self):
2158 parser = ErrorRaisingArgumentParser()
2159 group = parser.add_argument_group('xxx')
2160 group.add_argument('foo')
2161 parser.add_argument('bar')
2162 parser.add_argument('baz')
2163 expected = NS(foo='1', bar='2', baz='3')
2164 result = parser.parse_args('1 2 3'.split())
2165 self.assertEqual(expected, result)
2166
2167 def test_interleaved_groups(self):
2168 parser = ErrorRaisingArgumentParser()
2169 group = parser.add_argument_group('xxx')
2170 parser.add_argument('foo')
2171 group.add_argument('bar')
2172 parser.add_argument('baz')
2173 group = parser.add_argument_group('yyy')
2174 group.add_argument('frell')
2175 expected = NS(foo='1', bar='2', baz='3', frell='4')
2176 result = parser.parse_args('1 2 3 4'.split())
2177 self.assertEqual(expected, result)
2178
2179# ===================
2180# Parent parser tests
2181# ===================
2182
2183class TestParentParsers(TestCase):
2184 """Tests that parsers can be created with parent parsers"""
2185
2186 def assertArgumentParserError(self, *args, **kwargs):
2187 self.assertRaises(ArgumentParserError, *args, **kwargs)
2188
2189 def setUp(self):
Steven Bethard1f1c2472010-11-01 13:56:09 +00002190 super().setUp()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002191 self.wxyz_parent = ErrorRaisingArgumentParser(add_help=False)
2192 self.wxyz_parent.add_argument('--w')
2193 x_group = self.wxyz_parent.add_argument_group('x')
2194 x_group.add_argument('-y')
2195 self.wxyz_parent.add_argument('z')
2196
2197 self.abcd_parent = ErrorRaisingArgumentParser(add_help=False)
2198 self.abcd_parent.add_argument('a')
2199 self.abcd_parent.add_argument('-b')
2200 c_group = self.abcd_parent.add_argument_group('c')
2201 c_group.add_argument('--d')
2202
2203 self.w_parent = ErrorRaisingArgumentParser(add_help=False)
2204 self.w_parent.add_argument('--w')
2205
2206 self.z_parent = ErrorRaisingArgumentParser(add_help=False)
2207 self.z_parent.add_argument('z')
2208
2209 # parents with mutually exclusive groups
2210 self.ab_mutex_parent = ErrorRaisingArgumentParser(add_help=False)
2211 group = self.ab_mutex_parent.add_mutually_exclusive_group()
2212 group.add_argument('-a', action='store_true')
2213 group.add_argument('-b', action='store_true')
2214
2215 self.main_program = os.path.basename(sys.argv[0])
2216
2217 def test_single_parent(self):
2218 parser = ErrorRaisingArgumentParser(parents=[self.wxyz_parent])
2219 self.assertEqual(parser.parse_args('-y 1 2 --w 3'.split()),
2220 NS(w='3', y='1', z='2'))
2221
2222 def test_single_parent_mutex(self):
2223 self._test_mutex_ab(self.ab_mutex_parent.parse_args)
2224 parser = ErrorRaisingArgumentParser(parents=[self.ab_mutex_parent])
2225 self._test_mutex_ab(parser.parse_args)
2226
2227 def test_single_granparent_mutex(self):
2228 parents = [self.ab_mutex_parent]
2229 parser = ErrorRaisingArgumentParser(add_help=False, parents=parents)
2230 parser = ErrorRaisingArgumentParser(parents=[parser])
2231 self._test_mutex_ab(parser.parse_args)
2232
2233 def _test_mutex_ab(self, parse_args):
2234 self.assertEqual(parse_args([]), NS(a=False, b=False))
2235 self.assertEqual(parse_args(['-a']), NS(a=True, b=False))
2236 self.assertEqual(parse_args(['-b']), NS(a=False, b=True))
2237 self.assertArgumentParserError(parse_args, ['-a', '-b'])
2238 self.assertArgumentParserError(parse_args, ['-b', '-a'])
2239 self.assertArgumentParserError(parse_args, ['-c'])
2240 self.assertArgumentParserError(parse_args, ['-a', '-c'])
2241 self.assertArgumentParserError(parse_args, ['-b', '-c'])
2242
2243 def test_multiple_parents(self):
2244 parents = [self.abcd_parent, self.wxyz_parent]
2245 parser = ErrorRaisingArgumentParser(parents=parents)
2246 self.assertEqual(parser.parse_args('--d 1 --w 2 3 4'.split()),
2247 NS(a='3', b=None, d='1', w='2', y=None, z='4'))
2248
2249 def test_multiple_parents_mutex(self):
2250 parents = [self.ab_mutex_parent, self.wxyz_parent]
2251 parser = ErrorRaisingArgumentParser(parents=parents)
2252 self.assertEqual(parser.parse_args('-a --w 2 3'.split()),
2253 NS(a=True, b=False, w='2', y=None, z='3'))
2254 self.assertArgumentParserError(
2255 parser.parse_args, '-a --w 2 3 -b'.split())
2256 self.assertArgumentParserError(
2257 parser.parse_args, '-a -b --w 2 3'.split())
2258
2259 def test_conflicting_parents(self):
2260 self.assertRaises(
2261 argparse.ArgumentError,
2262 argparse.ArgumentParser,
2263 parents=[self.w_parent, self.wxyz_parent])
2264
2265 def test_conflicting_parents_mutex(self):
2266 self.assertRaises(
2267 argparse.ArgumentError,
2268 argparse.ArgumentParser,
2269 parents=[self.abcd_parent, self.ab_mutex_parent])
2270
2271 def test_same_argument_name_parents(self):
2272 parents = [self.wxyz_parent, self.z_parent]
2273 parser = ErrorRaisingArgumentParser(parents=parents)
2274 self.assertEqual(parser.parse_args('1 2'.split()),
2275 NS(w=None, y=None, z='2'))
2276
2277 def test_subparser_parents(self):
2278 parser = ErrorRaisingArgumentParser()
2279 subparsers = parser.add_subparsers()
2280 abcde_parser = subparsers.add_parser('bar', parents=[self.abcd_parent])
2281 abcde_parser.add_argument('e')
2282 self.assertEqual(parser.parse_args('bar -b 1 --d 2 3 4'.split()),
2283 NS(a='3', b='1', d='2', e='4'))
2284
2285 def test_subparser_parents_mutex(self):
2286 parser = ErrorRaisingArgumentParser()
2287 subparsers = parser.add_subparsers()
2288 parents = [self.ab_mutex_parent]
2289 abc_parser = subparsers.add_parser('foo', parents=parents)
2290 c_group = abc_parser.add_argument_group('c_group')
2291 c_group.add_argument('c')
2292 parents = [self.wxyz_parent, self.ab_mutex_parent]
2293 wxyzabe_parser = subparsers.add_parser('bar', parents=parents)
2294 wxyzabe_parser.add_argument('e')
2295 self.assertEqual(parser.parse_args('foo -a 4'.split()),
2296 NS(a=True, b=False, c='4'))
2297 self.assertEqual(parser.parse_args('bar -b --w 2 3 4'.split()),
2298 NS(a=False, b=True, w='2', y=None, z='3', e='4'))
2299 self.assertArgumentParserError(
2300 parser.parse_args, 'foo -a -b 4'.split())
2301 self.assertArgumentParserError(
2302 parser.parse_args, 'bar -b -a 4'.split())
2303
2304 def test_parent_help(self):
2305 parents = [self.abcd_parent, self.wxyz_parent]
2306 parser = ErrorRaisingArgumentParser(parents=parents)
2307 parser_help = parser.format_help()
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002308 progname = self.main_program
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002309 self.assertEqual(parser_help, textwrap.dedent('''\
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002310 usage: {}{}[-h] [-b B] [--d D] [--w W] [-y Y] a z
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002311
2312 positional arguments:
2313 a
2314 z
2315
2316 optional arguments:
2317 -h, --help show this help message and exit
2318 -b B
2319 --w W
2320
2321 c:
2322 --d D
2323
2324 x:
2325 -y Y
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002326 '''.format(progname, ' ' if progname else '' )))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002327
2328 def test_groups_parents(self):
2329 parent = ErrorRaisingArgumentParser(add_help=False)
2330 g = parent.add_argument_group(title='g', description='gd')
2331 g.add_argument('-w')
2332 g.add_argument('-x')
2333 m = parent.add_mutually_exclusive_group()
2334 m.add_argument('-y')
2335 m.add_argument('-z')
2336 parser = ErrorRaisingArgumentParser(parents=[parent])
2337
2338 self.assertRaises(ArgumentParserError, parser.parse_args,
2339 ['-y', 'Y', '-z', 'Z'])
2340
2341 parser_help = parser.format_help()
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002342 progname = self.main_program
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002343 self.assertEqual(parser_help, textwrap.dedent('''\
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002344 usage: {}{}[-h] [-w W] [-x X] [-y Y | -z Z]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002345
2346 optional arguments:
2347 -h, --help show this help message and exit
2348 -y Y
2349 -z Z
2350
2351 g:
2352 gd
2353
2354 -w W
2355 -x X
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002356 '''.format(progname, ' ' if progname else '' )))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002357
2358# ==============================
2359# Mutually exclusive group tests
2360# ==============================
2361
2362class TestMutuallyExclusiveGroupErrors(TestCase):
2363
2364 def test_invalid_add_argument_group(self):
2365 parser = ErrorRaisingArgumentParser()
2366 raises = self.assertRaises
2367 raises(TypeError, parser.add_mutually_exclusive_group, title='foo')
2368
2369 def test_invalid_add_argument(self):
2370 parser = ErrorRaisingArgumentParser()
2371 group = parser.add_mutually_exclusive_group()
2372 add_argument = group.add_argument
2373 raises = self.assertRaises
2374 raises(ValueError, add_argument, '--foo', required=True)
2375 raises(ValueError, add_argument, 'bar')
2376 raises(ValueError, add_argument, 'bar', nargs='+')
2377 raises(ValueError, add_argument, 'bar', nargs=1)
2378 raises(ValueError, add_argument, 'bar', nargs=argparse.PARSER)
2379
Steven Bethard49998ee2010-11-01 16:29:26 +00002380 def test_help(self):
2381 parser = ErrorRaisingArgumentParser(prog='PROG')
2382 group1 = parser.add_mutually_exclusive_group()
2383 group1.add_argument('--foo', action='store_true')
2384 group1.add_argument('--bar', action='store_false')
2385 group2 = parser.add_mutually_exclusive_group()
2386 group2.add_argument('--soup', action='store_true')
2387 group2.add_argument('--nuts', action='store_false')
2388 expected = '''\
2389 usage: PROG [-h] [--foo | --bar] [--soup | --nuts]
2390
2391 optional arguments:
2392 -h, --help show this help message and exit
2393 --foo
2394 --bar
2395 --soup
2396 --nuts
2397 '''
2398 self.assertEqual(parser.format_help(), textwrap.dedent(expected))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002399
2400class MEMixin(object):
2401
2402 def test_failures_when_not_required(self):
2403 parse_args = self.get_parser(required=False).parse_args
2404 error = ArgumentParserError
2405 for args_string in self.failures:
2406 self.assertRaises(error, parse_args, args_string.split())
2407
2408 def test_failures_when_required(self):
2409 parse_args = self.get_parser(required=True).parse_args
2410 error = ArgumentParserError
2411 for args_string in self.failures + ['']:
2412 self.assertRaises(error, parse_args, args_string.split())
2413
2414 def test_successes_when_not_required(self):
2415 parse_args = self.get_parser(required=False).parse_args
2416 successes = self.successes + self.successes_when_not_required
2417 for args_string, expected_ns in successes:
2418 actual_ns = parse_args(args_string.split())
2419 self.assertEqual(actual_ns, expected_ns)
2420
2421 def test_successes_when_required(self):
2422 parse_args = self.get_parser(required=True).parse_args
2423 for args_string, expected_ns in self.successes:
2424 actual_ns = parse_args(args_string.split())
2425 self.assertEqual(actual_ns, expected_ns)
2426
2427 def test_usage_when_not_required(self):
2428 format_usage = self.get_parser(required=False).format_usage
2429 expected_usage = self.usage_when_not_required
2430 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))
2431
2432 def test_usage_when_required(self):
2433 format_usage = self.get_parser(required=True).format_usage
2434 expected_usage = self.usage_when_required
2435 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))
2436
2437 def test_help_when_not_required(self):
2438 format_help = self.get_parser(required=False).format_help
2439 help = self.usage_when_not_required + self.help
2440 self.assertEqual(format_help(), textwrap.dedent(help))
2441
2442 def test_help_when_required(self):
2443 format_help = self.get_parser(required=True).format_help
2444 help = self.usage_when_required + self.help
2445 self.assertEqual(format_help(), textwrap.dedent(help))
2446
2447
2448class TestMutuallyExclusiveSimple(MEMixin, TestCase):
2449
2450 def get_parser(self, required=None):
2451 parser = ErrorRaisingArgumentParser(prog='PROG')
2452 group = parser.add_mutually_exclusive_group(required=required)
2453 group.add_argument('--bar', help='bar help')
2454 group.add_argument('--baz', nargs='?', const='Z', help='baz help')
2455 return parser
2456
2457 failures = ['--bar X --baz Y', '--bar X --baz']
2458 successes = [
2459 ('--bar X', NS(bar='X', baz=None)),
2460 ('--bar X --bar Z', NS(bar='Z', baz=None)),
2461 ('--baz Y', NS(bar=None, baz='Y')),
2462 ('--baz', NS(bar=None, baz='Z')),
2463 ]
2464 successes_when_not_required = [
2465 ('', NS(bar=None, baz=None)),
2466 ]
2467
2468 usage_when_not_required = '''\
2469 usage: PROG [-h] [--bar BAR | --baz [BAZ]]
2470 '''
2471 usage_when_required = '''\
2472 usage: PROG [-h] (--bar BAR | --baz [BAZ])
2473 '''
2474 help = '''\
2475
2476 optional arguments:
2477 -h, --help show this help message and exit
2478 --bar BAR bar help
2479 --baz [BAZ] baz help
2480 '''
2481
2482
2483class TestMutuallyExclusiveLong(MEMixin, TestCase):
2484
2485 def get_parser(self, required=None):
2486 parser = ErrorRaisingArgumentParser(prog='PROG')
2487 parser.add_argument('--abcde', help='abcde help')
2488 parser.add_argument('--fghij', help='fghij help')
2489 group = parser.add_mutually_exclusive_group(required=required)
2490 group.add_argument('--klmno', help='klmno help')
2491 group.add_argument('--pqrst', help='pqrst help')
2492 return parser
2493
2494 failures = ['--klmno X --pqrst Y']
2495 successes = [
2496 ('--klmno X', NS(abcde=None, fghij=None, klmno='X', pqrst=None)),
2497 ('--abcde Y --klmno X',
2498 NS(abcde='Y', fghij=None, klmno='X', pqrst=None)),
2499 ('--pqrst X', NS(abcde=None, fghij=None, klmno=None, pqrst='X')),
2500 ('--pqrst X --fghij Y',
2501 NS(abcde=None, fghij='Y', klmno=None, pqrst='X')),
2502 ]
2503 successes_when_not_required = [
2504 ('', NS(abcde=None, fghij=None, klmno=None, pqrst=None)),
2505 ]
2506
2507 usage_when_not_required = '''\
2508 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]
2509 [--klmno KLMNO | --pqrst PQRST]
2510 '''
2511 usage_when_required = '''\
2512 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]
2513 (--klmno KLMNO | --pqrst PQRST)
2514 '''
2515 help = '''\
2516
2517 optional arguments:
2518 -h, --help show this help message and exit
2519 --abcde ABCDE abcde help
2520 --fghij FGHIJ fghij help
2521 --klmno KLMNO klmno help
2522 --pqrst PQRST pqrst help
2523 '''
2524
2525
2526class TestMutuallyExclusiveFirstSuppressed(MEMixin, TestCase):
2527
2528 def get_parser(self, required):
2529 parser = ErrorRaisingArgumentParser(prog='PROG')
2530 group = parser.add_mutually_exclusive_group(required=required)
2531 group.add_argument('-x', help=argparse.SUPPRESS)
2532 group.add_argument('-y', action='store_false', help='y help')
2533 return parser
2534
2535 failures = ['-x X -y']
2536 successes = [
2537 ('-x X', NS(x='X', y=True)),
2538 ('-x X -x Y', NS(x='Y', y=True)),
2539 ('-y', NS(x=None, y=False)),
2540 ]
2541 successes_when_not_required = [
2542 ('', NS(x=None, y=True)),
2543 ]
2544
2545 usage_when_not_required = '''\
2546 usage: PROG [-h] [-y]
2547 '''
2548 usage_when_required = '''\
2549 usage: PROG [-h] -y
2550 '''
2551 help = '''\
2552
2553 optional arguments:
2554 -h, --help show this help message and exit
2555 -y y help
2556 '''
2557
2558
2559class TestMutuallyExclusiveManySuppressed(MEMixin, TestCase):
2560
2561 def get_parser(self, required):
2562 parser = ErrorRaisingArgumentParser(prog='PROG')
2563 group = parser.add_mutually_exclusive_group(required=required)
2564 add = group.add_argument
2565 add('--spam', action='store_true', help=argparse.SUPPRESS)
2566 add('--badger', action='store_false', help=argparse.SUPPRESS)
2567 add('--bladder', help=argparse.SUPPRESS)
2568 return parser
2569
2570 failures = [
2571 '--spam --badger',
2572 '--badger --bladder B',
2573 '--bladder B --spam',
2574 ]
2575 successes = [
2576 ('--spam', NS(spam=True, badger=True, bladder=None)),
2577 ('--badger', NS(spam=False, badger=False, bladder=None)),
2578 ('--bladder B', NS(spam=False, badger=True, bladder='B')),
2579 ('--spam --spam', NS(spam=True, badger=True, bladder=None)),
2580 ]
2581 successes_when_not_required = [
2582 ('', NS(spam=False, badger=True, bladder=None)),
2583 ]
2584
2585 usage_when_required = usage_when_not_required = '''\
2586 usage: PROG [-h]
2587 '''
2588 help = '''\
2589
2590 optional arguments:
2591 -h, --help show this help message and exit
2592 '''
2593
2594
2595class TestMutuallyExclusiveOptionalAndPositional(MEMixin, TestCase):
2596
2597 def get_parser(self, required):
2598 parser = ErrorRaisingArgumentParser(prog='PROG')
2599 group = parser.add_mutually_exclusive_group(required=required)
2600 group.add_argument('--foo', action='store_true', help='FOO')
2601 group.add_argument('--spam', help='SPAM')
2602 group.add_argument('badger', nargs='*', default='X', help='BADGER')
2603 return parser
2604
2605 failures = [
2606 '--foo --spam S',
2607 '--spam S X',
2608 'X --foo',
2609 'X Y Z --spam S',
2610 '--foo X Y',
2611 ]
2612 successes = [
2613 ('--foo', NS(foo=True, spam=None, badger='X')),
2614 ('--spam S', NS(foo=False, spam='S', badger='X')),
2615 ('X', NS(foo=False, spam=None, badger=['X'])),
2616 ('X Y Z', NS(foo=False, spam=None, badger=['X', 'Y', 'Z'])),
2617 ]
2618 successes_when_not_required = [
2619 ('', NS(foo=False, spam=None, badger='X')),
2620 ]
2621
2622 usage_when_not_required = '''\
2623 usage: PROG [-h] [--foo | --spam SPAM | badger [badger ...]]
2624 '''
2625 usage_when_required = '''\
2626 usage: PROG [-h] (--foo | --spam SPAM | badger [badger ...])
2627 '''
2628 help = '''\
2629
2630 positional arguments:
2631 badger BADGER
2632
2633 optional arguments:
2634 -h, --help show this help message and exit
2635 --foo FOO
2636 --spam SPAM SPAM
2637 '''
2638
2639
2640class TestMutuallyExclusiveOptionalsMixed(MEMixin, TestCase):
2641
2642 def get_parser(self, required):
2643 parser = ErrorRaisingArgumentParser(prog='PROG')
2644 parser.add_argument('-x', action='store_true', help='x help')
2645 group = parser.add_mutually_exclusive_group(required=required)
2646 group.add_argument('-a', action='store_true', help='a help')
2647 group.add_argument('-b', action='store_true', help='b help')
2648 parser.add_argument('-y', action='store_true', help='y help')
2649 group.add_argument('-c', action='store_true', help='c help')
2650 return parser
2651
2652 failures = ['-a -b', '-b -c', '-a -c', '-a -b -c']
2653 successes = [
2654 ('-a', NS(a=True, b=False, c=False, x=False, y=False)),
2655 ('-b', NS(a=False, b=True, c=False, x=False, y=False)),
2656 ('-c', NS(a=False, b=False, c=True, x=False, y=False)),
2657 ('-a -x', NS(a=True, b=False, c=False, x=True, y=False)),
2658 ('-y -b', NS(a=False, b=True, c=False, x=False, y=True)),
2659 ('-x -y -c', NS(a=False, b=False, c=True, x=True, y=True)),
2660 ]
2661 successes_when_not_required = [
2662 ('', NS(a=False, b=False, c=False, x=False, y=False)),
2663 ('-x', NS(a=False, b=False, c=False, x=True, y=False)),
2664 ('-y', NS(a=False, b=False, c=False, x=False, y=True)),
2665 ]
2666
2667 usage_when_required = usage_when_not_required = '''\
2668 usage: PROG [-h] [-x] [-a] [-b] [-y] [-c]
2669 '''
2670 help = '''\
2671
2672 optional arguments:
2673 -h, --help show this help message and exit
2674 -x x help
2675 -a a help
2676 -b b help
2677 -y y help
2678 -c c help
2679 '''
2680
2681
Georg Brandl0f6b47a2011-01-30 12:19:35 +00002682class TestMutuallyExclusiveInGroup(MEMixin, TestCase):
2683
2684 def get_parser(self, required=None):
2685 parser = ErrorRaisingArgumentParser(prog='PROG')
2686 titled_group = parser.add_argument_group(
2687 title='Titled group', description='Group description')
2688 mutex_group = \
2689 titled_group.add_mutually_exclusive_group(required=required)
2690 mutex_group.add_argument('--bar', help='bar help')
2691 mutex_group.add_argument('--baz', help='baz help')
2692 return parser
2693
2694 failures = ['--bar X --baz Y', '--baz X --bar Y']
2695 successes = [
2696 ('--bar X', NS(bar='X', baz=None)),
2697 ('--baz Y', NS(bar=None, baz='Y')),
2698 ]
2699 successes_when_not_required = [
2700 ('', NS(bar=None, baz=None)),
2701 ]
2702
2703 usage_when_not_required = '''\
2704 usage: PROG [-h] [--bar BAR | --baz BAZ]
2705 '''
2706 usage_when_required = '''\
2707 usage: PROG [-h] (--bar BAR | --baz BAZ)
2708 '''
2709 help = '''\
2710
2711 optional arguments:
2712 -h, --help show this help message and exit
2713
2714 Titled group:
2715 Group description
2716
2717 --bar BAR bar help
2718 --baz BAZ baz help
2719 '''
2720
2721
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002722class TestMutuallyExclusiveOptionalsAndPositionalsMixed(MEMixin, TestCase):
2723
2724 def get_parser(self, required):
2725 parser = ErrorRaisingArgumentParser(prog='PROG')
2726 parser.add_argument('x', help='x help')
2727 parser.add_argument('-y', action='store_true', help='y help')
2728 group = parser.add_mutually_exclusive_group(required=required)
2729 group.add_argument('a', nargs='?', help='a help')
2730 group.add_argument('-b', action='store_true', help='b help')
2731 group.add_argument('-c', action='store_true', help='c help')
2732 return parser
2733
2734 failures = ['X A -b', '-b -c', '-c X A']
2735 successes = [
2736 ('X A', NS(a='A', b=False, c=False, x='X', y=False)),
2737 ('X -b', NS(a=None, b=True, c=False, x='X', y=False)),
2738 ('X -c', NS(a=None, b=False, c=True, x='X', y=False)),
2739 ('X A -y', NS(a='A', b=False, c=False, x='X', y=True)),
2740 ('X -y -b', NS(a=None, b=True, c=False, x='X', y=True)),
2741 ]
2742 successes_when_not_required = [
2743 ('X', NS(a=None, b=False, c=False, x='X', y=False)),
2744 ('X -y', NS(a=None, b=False, c=False, x='X', y=True)),
2745 ]
2746
2747 usage_when_required = usage_when_not_required = '''\
2748 usage: PROG [-h] [-y] [-b] [-c] x [a]
2749 '''
2750 help = '''\
2751
2752 positional arguments:
2753 x x help
2754 a a help
2755
2756 optional arguments:
2757 -h, --help show this help message and exit
2758 -y y help
2759 -b b help
2760 -c c help
2761 '''
2762
2763# =================================================
2764# Mutually exclusive group in parent parser tests
2765# =================================================
2766
2767class MEPBase(object):
2768
2769 def get_parser(self, required=None):
2770 parent = super(MEPBase, self).get_parser(required=required)
2771 parser = ErrorRaisingArgumentParser(
2772 prog=parent.prog, add_help=False, parents=[parent])
2773 return parser
2774
2775
2776class TestMutuallyExclusiveGroupErrorsParent(
2777 MEPBase, TestMutuallyExclusiveGroupErrors):
2778 pass
2779
2780
2781class TestMutuallyExclusiveSimpleParent(
2782 MEPBase, TestMutuallyExclusiveSimple):
2783 pass
2784
2785
2786class TestMutuallyExclusiveLongParent(
2787 MEPBase, TestMutuallyExclusiveLong):
2788 pass
2789
2790
2791class TestMutuallyExclusiveFirstSuppressedParent(
2792 MEPBase, TestMutuallyExclusiveFirstSuppressed):
2793 pass
2794
2795
2796class TestMutuallyExclusiveManySuppressedParent(
2797 MEPBase, TestMutuallyExclusiveManySuppressed):
2798 pass
2799
2800
2801class TestMutuallyExclusiveOptionalAndPositionalParent(
2802 MEPBase, TestMutuallyExclusiveOptionalAndPositional):
2803 pass
2804
2805
2806class TestMutuallyExclusiveOptionalsMixedParent(
2807 MEPBase, TestMutuallyExclusiveOptionalsMixed):
2808 pass
2809
2810
2811class TestMutuallyExclusiveOptionalsAndPositionalsMixedParent(
2812 MEPBase, TestMutuallyExclusiveOptionalsAndPositionalsMixed):
2813 pass
2814
2815# =================
2816# Set default tests
2817# =================
2818
2819class TestSetDefaults(TestCase):
2820
2821 def test_set_defaults_no_args(self):
2822 parser = ErrorRaisingArgumentParser()
2823 parser.set_defaults(x='foo')
2824 parser.set_defaults(y='bar', z=1)
2825 self.assertEqual(NS(x='foo', y='bar', z=1),
2826 parser.parse_args([]))
2827 self.assertEqual(NS(x='foo', y='bar', z=1),
2828 parser.parse_args([], NS()))
2829 self.assertEqual(NS(x='baz', y='bar', z=1),
2830 parser.parse_args([], NS(x='baz')))
2831 self.assertEqual(NS(x='baz', y='bar', z=2),
2832 parser.parse_args([], NS(x='baz', z=2)))
2833
2834 def test_set_defaults_with_args(self):
2835 parser = ErrorRaisingArgumentParser()
2836 parser.set_defaults(x='foo', y='bar')
2837 parser.add_argument('-x', default='xfoox')
2838 self.assertEqual(NS(x='xfoox', y='bar'),
2839 parser.parse_args([]))
2840 self.assertEqual(NS(x='xfoox', y='bar'),
2841 parser.parse_args([], NS()))
2842 self.assertEqual(NS(x='baz', y='bar'),
2843 parser.parse_args([], NS(x='baz')))
2844 self.assertEqual(NS(x='1', y='bar'),
2845 parser.parse_args('-x 1'.split()))
2846 self.assertEqual(NS(x='1', y='bar'),
2847 parser.parse_args('-x 1'.split(), NS()))
2848 self.assertEqual(NS(x='1', y='bar'),
2849 parser.parse_args('-x 1'.split(), NS(x='baz')))
2850
2851 def test_set_defaults_subparsers(self):
2852 parser = ErrorRaisingArgumentParser()
2853 parser.set_defaults(x='foo')
2854 subparsers = parser.add_subparsers()
2855 parser_a = subparsers.add_parser('a')
2856 parser_a.set_defaults(y='bar')
2857 self.assertEqual(NS(x='foo', y='bar'),
2858 parser.parse_args('a'.split()))
2859
2860 def test_set_defaults_parents(self):
2861 parent = ErrorRaisingArgumentParser(add_help=False)
2862 parent.set_defaults(x='foo')
2863 parser = ErrorRaisingArgumentParser(parents=[parent])
2864 self.assertEqual(NS(x='foo'), parser.parse_args([]))
2865
R David Murray7570cbd2014-10-17 19:55:11 -04002866 def test_set_defaults_on_parent_and_subparser(self):
2867 parser = argparse.ArgumentParser()
2868 xparser = parser.add_subparsers().add_parser('X')
2869 parser.set_defaults(foo=1)
2870 xparser.set_defaults(foo=2)
2871 self.assertEqual(NS(foo=2), parser.parse_args(['X']))
2872
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002873 def test_set_defaults_same_as_add_argument(self):
2874 parser = ErrorRaisingArgumentParser()
2875 parser.set_defaults(w='W', x='X', y='Y', z='Z')
2876 parser.add_argument('-w')
2877 parser.add_argument('-x', default='XX')
2878 parser.add_argument('y', nargs='?')
2879 parser.add_argument('z', nargs='?', default='ZZ')
2880
2881 # defaults set previously
2882 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
2883 parser.parse_args([]))
2884
2885 # reset defaults
2886 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
2887 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
2888 parser.parse_args([]))
2889
2890 def test_set_defaults_same_as_add_argument_group(self):
2891 parser = ErrorRaisingArgumentParser()
2892 parser.set_defaults(w='W', x='X', y='Y', z='Z')
2893 group = parser.add_argument_group('foo')
2894 group.add_argument('-w')
2895 group.add_argument('-x', default='XX')
2896 group.add_argument('y', nargs='?')
2897 group.add_argument('z', nargs='?', default='ZZ')
2898
2899
2900 # defaults set previously
2901 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
2902 parser.parse_args([]))
2903
2904 # reset defaults
2905 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
2906 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
2907 parser.parse_args([]))
2908
2909# =================
2910# Get default tests
2911# =================
2912
2913class TestGetDefault(TestCase):
2914
2915 def test_get_default(self):
2916 parser = ErrorRaisingArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002917 self.assertIsNone(parser.get_default("foo"))
2918 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002919
2920 parser.add_argument("--foo")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002921 self.assertIsNone(parser.get_default("foo"))
2922 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002923
2924 parser.add_argument("--bar", type=int, default=42)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002925 self.assertIsNone(parser.get_default("foo"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002926 self.assertEqual(42, parser.get_default("bar"))
2927
2928 parser.set_defaults(foo="badger")
2929 self.assertEqual("badger", parser.get_default("foo"))
2930 self.assertEqual(42, parser.get_default("bar"))
2931
2932# ==========================
2933# Namespace 'contains' tests
2934# ==========================
2935
2936class TestNamespaceContainsSimple(TestCase):
2937
2938 def test_empty(self):
2939 ns = argparse.Namespace()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002940 self.assertNotIn('', ns)
2941 self.assertNotIn('x', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002942
2943 def test_non_empty(self):
2944 ns = argparse.Namespace(x=1, y=2)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002945 self.assertNotIn('', ns)
2946 self.assertIn('x', ns)
2947 self.assertIn('y', ns)
2948 self.assertNotIn('xx', ns)
2949 self.assertNotIn('z', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002950
2951# =====================
2952# Help formatting tests
2953# =====================
2954
2955class TestHelpFormattingMetaclass(type):
2956
2957 def __init__(cls, name, bases, bodydict):
2958 if name == 'HelpTestCase':
2959 return
2960
2961 class AddTests(object):
2962
2963 def __init__(self, test_class, func_suffix, std_name):
2964 self.func_suffix = func_suffix
2965 self.std_name = std_name
2966
2967 for test_func in [self.test_format,
2968 self.test_print,
2969 self.test_print_file]:
2970 test_name = '%s_%s' % (test_func.__name__, func_suffix)
2971
2972 def test_wrapper(self, test_func=test_func):
2973 test_func(self)
2974 try:
2975 test_wrapper.__name__ = test_name
2976 except TypeError:
2977 pass
2978 setattr(test_class, test_name, test_wrapper)
2979
2980 def _get_parser(self, tester):
2981 parser = argparse.ArgumentParser(
2982 *tester.parser_signature.args,
2983 **tester.parser_signature.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02002984 for argument_sig in getattr(tester, 'argument_signatures', []):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002985 parser.add_argument(*argument_sig.args,
2986 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02002987 group_sigs = getattr(tester, 'argument_group_signatures', [])
2988 for group_sig, argument_sigs in group_sigs:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002989 group = parser.add_argument_group(*group_sig.args,
2990 **group_sig.kwargs)
2991 for argument_sig in argument_sigs:
2992 group.add_argument(*argument_sig.args,
2993 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02002994 subparsers_sigs = getattr(tester, 'subparsers_signatures', [])
2995 if subparsers_sigs:
2996 subparsers = parser.add_subparsers()
2997 for subparser_sig in subparsers_sigs:
2998 subparsers.add_parser(*subparser_sig.args,
2999 **subparser_sig.kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003000 return parser
3001
3002 def _test(self, tester, parser_text):
3003 expected_text = getattr(tester, self.func_suffix)
3004 expected_text = textwrap.dedent(expected_text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003005 tester.assertEqual(expected_text, parser_text)
3006
3007 def test_format(self, tester):
3008 parser = self._get_parser(tester)
3009 format = getattr(parser, 'format_%s' % self.func_suffix)
3010 self._test(tester, format())
3011
3012 def test_print(self, tester):
3013 parser = self._get_parser(tester)
3014 print_ = getattr(parser, 'print_%s' % self.func_suffix)
3015 old_stream = getattr(sys, self.std_name)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003016 setattr(sys, self.std_name, StdIOBuffer())
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003017 try:
3018 print_()
3019 parser_text = getattr(sys, self.std_name).getvalue()
3020 finally:
3021 setattr(sys, self.std_name, old_stream)
3022 self._test(tester, parser_text)
3023
3024 def test_print_file(self, tester):
3025 parser = self._get_parser(tester)
3026 print_ = getattr(parser, 'print_%s' % self.func_suffix)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003027 sfile = StdIOBuffer()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003028 print_(sfile)
3029 parser_text = sfile.getvalue()
3030 self._test(tester, parser_text)
3031
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003032 # add tests for {format,print}_{usage,help}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003033 for func_suffix, std_name in [('usage', 'stdout'),
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003034 ('help', 'stdout')]:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003035 AddTests(cls, func_suffix, std_name)
3036
3037bases = TestCase,
3038HelpTestCase = TestHelpFormattingMetaclass('HelpTestCase', bases, {})
3039
3040
3041class TestHelpBiggerOptionals(HelpTestCase):
3042 """Make sure that argument help aligns when options are longer"""
3043
3044 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003045 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003046 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003047 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003048 Sig('-x', action='store_true', help='X HELP'),
3049 Sig('--y', help='Y HELP'),
3050 Sig('foo', help='FOO HELP'),
3051 Sig('bar', help='BAR HELP'),
3052 ]
3053 argument_group_signatures = []
3054 usage = '''\
3055 usage: PROG [-h] [-v] [-x] [--y Y] foo bar
3056 '''
3057 help = usage + '''\
3058
3059 DESCRIPTION
3060
3061 positional arguments:
3062 foo FOO HELP
3063 bar BAR HELP
3064
3065 optional arguments:
3066 -h, --help show this help message and exit
3067 -v, --version show program's version number and exit
3068 -x X HELP
3069 --y Y Y HELP
3070
3071 EPILOG
3072 '''
3073 version = '''\
3074 0.1
3075 '''
3076
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003077class TestShortColumns(HelpTestCase):
3078 '''Test extremely small number of columns.
3079
3080 TestCase prevents "COLUMNS" from being too small in the tests themselves,
Martin Panter2e4571a2015-11-14 01:07:43 +00003081 but we don't want any exceptions thrown in such cases. Only ugly representation.
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003082 '''
3083 def setUp(self):
3084 env = support.EnvironmentVarGuard()
3085 env.set("COLUMNS", '15')
3086 self.addCleanup(env.__exit__)
3087
3088 parser_signature = TestHelpBiggerOptionals.parser_signature
3089 argument_signatures = TestHelpBiggerOptionals.argument_signatures
3090 argument_group_signatures = TestHelpBiggerOptionals.argument_group_signatures
3091 usage = '''\
3092 usage: PROG
3093 [-h]
3094 [-v]
3095 [-x]
3096 [--y Y]
3097 foo
3098 bar
3099 '''
3100 help = usage + '''\
3101
3102 DESCRIPTION
3103
3104 positional arguments:
3105 foo
3106 FOO HELP
3107 bar
3108 BAR HELP
3109
3110 optional arguments:
3111 -h, --help
3112 show this
3113 help
3114 message and
3115 exit
3116 -v, --version
3117 show
3118 program's
3119 version
3120 number and
3121 exit
3122 -x
3123 X HELP
3124 --y Y
3125 Y HELP
3126
3127 EPILOG
3128 '''
3129 version = TestHelpBiggerOptionals.version
3130
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003131
3132class TestHelpBiggerOptionalGroups(HelpTestCase):
3133 """Make sure that argument help aligns when options are longer"""
3134
3135 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003136 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003137 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003138 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003139 Sig('-x', action='store_true', help='X HELP'),
3140 Sig('--y', help='Y HELP'),
3141 Sig('foo', help='FOO HELP'),
3142 Sig('bar', help='BAR HELP'),
3143 ]
3144 argument_group_signatures = [
3145 (Sig('GROUP TITLE', description='GROUP DESCRIPTION'), [
3146 Sig('baz', help='BAZ HELP'),
3147 Sig('-z', nargs='+', help='Z HELP')]),
3148 ]
3149 usage = '''\
3150 usage: PROG [-h] [-v] [-x] [--y Y] [-z Z [Z ...]] foo bar baz
3151 '''
3152 help = usage + '''\
3153
3154 DESCRIPTION
3155
3156 positional arguments:
3157 foo FOO HELP
3158 bar BAR HELP
3159
3160 optional arguments:
3161 -h, --help show this help message and exit
3162 -v, --version show program's version number and exit
3163 -x X HELP
3164 --y Y Y HELP
3165
3166 GROUP TITLE:
3167 GROUP DESCRIPTION
3168
3169 baz BAZ HELP
3170 -z Z [Z ...] Z HELP
3171
3172 EPILOG
3173 '''
3174 version = '''\
3175 0.1
3176 '''
3177
3178
3179class TestHelpBiggerPositionals(HelpTestCase):
3180 """Make sure that help aligns when arguments are longer"""
3181
3182 parser_signature = Sig(usage='USAGE', description='DESCRIPTION')
3183 argument_signatures = [
3184 Sig('-x', action='store_true', help='X HELP'),
3185 Sig('--y', help='Y HELP'),
3186 Sig('ekiekiekifekang', help='EKI HELP'),
3187 Sig('bar', help='BAR HELP'),
3188 ]
3189 argument_group_signatures = []
3190 usage = '''\
3191 usage: USAGE
3192 '''
3193 help = usage + '''\
3194
3195 DESCRIPTION
3196
3197 positional arguments:
3198 ekiekiekifekang EKI HELP
3199 bar BAR HELP
3200
3201 optional arguments:
3202 -h, --help show this help message and exit
3203 -x X HELP
3204 --y Y Y HELP
3205 '''
3206
3207 version = ''
3208
3209
3210class TestHelpReformatting(HelpTestCase):
3211 """Make sure that text after short names starts on the first line"""
3212
3213 parser_signature = Sig(
3214 prog='PROG',
3215 description=' oddly formatted\n'
3216 'description\n'
3217 '\n'
3218 'that is so long that it should go onto multiple '
3219 'lines when wrapped')
3220 argument_signatures = [
3221 Sig('-x', metavar='XX', help='oddly\n'
3222 ' formatted -x help'),
3223 Sig('y', metavar='yyy', help='normal y help'),
3224 ]
3225 argument_group_signatures = [
3226 (Sig('title', description='\n'
3227 ' oddly formatted group\n'
3228 '\n'
3229 'description'),
3230 [Sig('-a', action='store_true',
3231 help=' oddly \n'
3232 'formatted -a help \n'
3233 ' again, so long that it should be wrapped over '
3234 'multiple lines')]),
3235 ]
3236 usage = '''\
3237 usage: PROG [-h] [-x XX] [-a] yyy
3238 '''
3239 help = usage + '''\
3240
3241 oddly formatted description that is so long that it should go onto \
3242multiple
3243 lines when wrapped
3244
3245 positional arguments:
3246 yyy normal y help
3247
3248 optional arguments:
3249 -h, --help show this help message and exit
3250 -x XX oddly formatted -x help
3251
3252 title:
3253 oddly formatted group description
3254
3255 -a oddly formatted -a help again, so long that it should \
3256be wrapped
3257 over multiple lines
3258 '''
3259 version = ''
3260
3261
3262class TestHelpWrappingShortNames(HelpTestCase):
3263 """Make sure that text after short names starts on the first line"""
3264
3265 parser_signature = Sig(prog='PROG', description= 'D\nD' * 30)
3266 argument_signatures = [
3267 Sig('-x', metavar='XX', help='XHH HX' * 20),
3268 Sig('y', metavar='yyy', help='YH YH' * 20),
3269 ]
3270 argument_group_signatures = [
3271 (Sig('ALPHAS'), [
3272 Sig('-a', action='store_true', help='AHHH HHA' * 10)]),
3273 ]
3274 usage = '''\
3275 usage: PROG [-h] [-x XX] [-a] yyy
3276 '''
3277 help = usage + '''\
3278
3279 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3280DD DD DD
3281 DD DD DD DD D
3282
3283 positional arguments:
3284 yyy YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3285YHYH YHYH
3286 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3287
3288 optional arguments:
3289 -h, --help show this help message and exit
3290 -x XX XHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH \
3291HXXHH HXXHH
3292 HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HX
3293
3294 ALPHAS:
3295 -a AHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH \
3296HHAAHHH
3297 HHAAHHH HHAAHHH HHA
3298 '''
3299 version = ''
3300
3301
3302class TestHelpWrappingLongNames(HelpTestCase):
3303 """Make sure that text after long names starts on the next line"""
3304
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003305 parser_signature = Sig(usage='USAGE', description= 'D D' * 30)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003306 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003307 Sig('-v', '--version', action='version', version='V V' * 30),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003308 Sig('-x', metavar='X' * 25, help='XH XH' * 20),
3309 Sig('y', metavar='y' * 25, help='YH YH' * 20),
3310 ]
3311 argument_group_signatures = [
3312 (Sig('ALPHAS'), [
3313 Sig('-a', metavar='A' * 25, help='AH AH' * 20),
3314 Sig('z', metavar='z' * 25, help='ZH ZH' * 20)]),
3315 ]
3316 usage = '''\
3317 usage: USAGE
3318 '''
3319 help = usage + '''\
3320
3321 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3322DD DD DD
3323 DD DD DD DD D
3324
3325 positional arguments:
3326 yyyyyyyyyyyyyyyyyyyyyyyyy
3327 YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3328YHYH YHYH
3329 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3330
3331 optional arguments:
3332 -h, --help show this help message and exit
3333 -v, --version show program's version number and exit
3334 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3335 XH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH \
3336XHXH XHXH
3337 XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XH
3338
3339 ALPHAS:
3340 -a AAAAAAAAAAAAAAAAAAAAAAAAA
3341 AH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH \
3342AHAH AHAH
3343 AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AH
3344 zzzzzzzzzzzzzzzzzzzzzzzzz
3345 ZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH \
3346ZHZH ZHZH
3347 ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZH
3348 '''
3349 version = '''\
3350 V VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV \
3351VV VV VV
3352 VV VV VV VV V
3353 '''
3354
3355
3356class TestHelpUsage(HelpTestCase):
3357 """Test basic usage messages"""
3358
3359 parser_signature = Sig(prog='PROG')
3360 argument_signatures = [
3361 Sig('-w', nargs='+', help='w'),
3362 Sig('-x', nargs='*', help='x'),
3363 Sig('a', help='a'),
3364 Sig('b', help='b', nargs=2),
3365 Sig('c', help='c', nargs='?'),
3366 ]
3367 argument_group_signatures = [
3368 (Sig('group'), [
3369 Sig('-y', nargs='?', help='y'),
3370 Sig('-z', nargs=3, help='z'),
3371 Sig('d', help='d', nargs='*'),
3372 Sig('e', help='e', nargs='+'),
3373 ])
3374 ]
3375 usage = '''\
3376 usage: PROG [-h] [-w W [W ...]] [-x [X [X ...]]] [-y [Y]] [-z Z Z Z]
3377 a b b [c] [d [d ...]] e [e ...]
3378 '''
3379 help = usage + '''\
3380
3381 positional arguments:
3382 a a
3383 b b
3384 c c
3385
3386 optional arguments:
3387 -h, --help show this help message and exit
3388 -w W [W ...] w
3389 -x [X [X ...]] x
3390
3391 group:
3392 -y [Y] y
3393 -z Z Z Z z
3394 d d
3395 e e
3396 '''
3397 version = ''
3398
3399
3400class TestHelpOnlyUserGroups(HelpTestCase):
3401 """Test basic usage messages"""
3402
3403 parser_signature = Sig(prog='PROG', add_help=False)
3404 argument_signatures = []
3405 argument_group_signatures = [
3406 (Sig('xxxx'), [
3407 Sig('-x', help='x'),
3408 Sig('a', help='a'),
3409 ]),
3410 (Sig('yyyy'), [
3411 Sig('b', help='b'),
3412 Sig('-y', help='y'),
3413 ]),
3414 ]
3415 usage = '''\
3416 usage: PROG [-x X] [-y Y] a b
3417 '''
3418 help = usage + '''\
3419
3420 xxxx:
3421 -x X x
3422 a a
3423
3424 yyyy:
3425 b b
3426 -y Y y
3427 '''
3428 version = ''
3429
3430
3431class TestHelpUsageLongProg(HelpTestCase):
3432 """Test usage messages where the prog is long"""
3433
3434 parser_signature = Sig(prog='P' * 60)
3435 argument_signatures = [
3436 Sig('-w', metavar='W'),
3437 Sig('-x', metavar='X'),
3438 Sig('a'),
3439 Sig('b'),
3440 ]
3441 argument_group_signatures = []
3442 usage = '''\
3443 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3444 [-h] [-w W] [-x X] a b
3445 '''
3446 help = usage + '''\
3447
3448 positional arguments:
3449 a
3450 b
3451
3452 optional arguments:
3453 -h, --help show this help message and exit
3454 -w W
3455 -x X
3456 '''
3457 version = ''
3458
3459
3460class TestHelpUsageLongProgOptionsWrap(HelpTestCase):
3461 """Test usage messages where the prog is long and the optionals wrap"""
3462
3463 parser_signature = Sig(prog='P' * 60)
3464 argument_signatures = [
3465 Sig('-w', metavar='W' * 25),
3466 Sig('-x', metavar='X' * 25),
3467 Sig('-y', metavar='Y' * 25),
3468 Sig('-z', metavar='Z' * 25),
3469 Sig('a'),
3470 Sig('b'),
3471 ]
3472 argument_group_signatures = []
3473 usage = '''\
3474 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3475 [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3476[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3477 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3478 a b
3479 '''
3480 help = usage + '''\
3481
3482 positional arguments:
3483 a
3484 b
3485
3486 optional arguments:
3487 -h, --help show this help message and exit
3488 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3489 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3490 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3491 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3492 '''
3493 version = ''
3494
3495
3496class TestHelpUsageLongProgPositionalsWrap(HelpTestCase):
3497 """Test usage messages where the prog is long and the positionals wrap"""
3498
3499 parser_signature = Sig(prog='P' * 60, add_help=False)
3500 argument_signatures = [
3501 Sig('a' * 25),
3502 Sig('b' * 25),
3503 Sig('c' * 25),
3504 ]
3505 argument_group_signatures = []
3506 usage = '''\
3507 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3508 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3509 ccccccccccccccccccccccccc
3510 '''
3511 help = usage + '''\
3512
3513 positional arguments:
3514 aaaaaaaaaaaaaaaaaaaaaaaaa
3515 bbbbbbbbbbbbbbbbbbbbbbbbb
3516 ccccccccccccccccccccccccc
3517 '''
3518 version = ''
3519
3520
3521class TestHelpUsageOptionalsWrap(HelpTestCase):
3522 """Test usage messages where the optionals wrap"""
3523
3524 parser_signature = Sig(prog='PROG')
3525 argument_signatures = [
3526 Sig('-w', metavar='W' * 25),
3527 Sig('-x', metavar='X' * 25),
3528 Sig('-y', metavar='Y' * 25),
3529 Sig('-z', metavar='Z' * 25),
3530 Sig('a'),
3531 Sig('b'),
3532 Sig('c'),
3533 ]
3534 argument_group_signatures = []
3535 usage = '''\
3536 usage: PROG [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3537[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3538 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] \
3539[-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3540 a b c
3541 '''
3542 help = usage + '''\
3543
3544 positional arguments:
3545 a
3546 b
3547 c
3548
3549 optional arguments:
3550 -h, --help show this help message and exit
3551 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3552 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3553 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3554 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3555 '''
3556 version = ''
3557
3558
3559class TestHelpUsagePositionalsWrap(HelpTestCase):
3560 """Test usage messages where the positionals wrap"""
3561
3562 parser_signature = Sig(prog='PROG')
3563 argument_signatures = [
3564 Sig('-x'),
3565 Sig('-y'),
3566 Sig('-z'),
3567 Sig('a' * 25),
3568 Sig('b' * 25),
3569 Sig('c' * 25),
3570 ]
3571 argument_group_signatures = []
3572 usage = '''\
3573 usage: PROG [-h] [-x X] [-y Y] [-z Z]
3574 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3575 ccccccccccccccccccccccccc
3576 '''
3577 help = usage + '''\
3578
3579 positional arguments:
3580 aaaaaaaaaaaaaaaaaaaaaaaaa
3581 bbbbbbbbbbbbbbbbbbbbbbbbb
3582 ccccccccccccccccccccccccc
3583
3584 optional arguments:
3585 -h, --help show this help message and exit
3586 -x X
3587 -y Y
3588 -z Z
3589 '''
3590 version = ''
3591
3592
3593class TestHelpUsageOptionalsPositionalsWrap(HelpTestCase):
3594 """Test usage messages where the optionals and positionals wrap"""
3595
3596 parser_signature = Sig(prog='PROG')
3597 argument_signatures = [
3598 Sig('-x', metavar='X' * 25),
3599 Sig('-y', metavar='Y' * 25),
3600 Sig('-z', metavar='Z' * 25),
3601 Sig('a' * 25),
3602 Sig('b' * 25),
3603 Sig('c' * 25),
3604 ]
3605 argument_group_signatures = []
3606 usage = '''\
3607 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3608[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3609 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3610 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3611 ccccccccccccccccccccccccc
3612 '''
3613 help = usage + '''\
3614
3615 positional arguments:
3616 aaaaaaaaaaaaaaaaaaaaaaaaa
3617 bbbbbbbbbbbbbbbbbbbbbbbbb
3618 ccccccccccccccccccccccccc
3619
3620 optional arguments:
3621 -h, --help show this help message and exit
3622 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3623 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3624 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3625 '''
3626 version = ''
3627
3628
3629class TestHelpUsageOptionalsOnlyWrap(HelpTestCase):
3630 """Test usage messages where there are only optionals and they wrap"""
3631
3632 parser_signature = Sig(prog='PROG')
3633 argument_signatures = [
3634 Sig('-x', metavar='X' * 25),
3635 Sig('-y', metavar='Y' * 25),
3636 Sig('-z', metavar='Z' * 25),
3637 ]
3638 argument_group_signatures = []
3639 usage = '''\
3640 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3641[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3642 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3643 '''
3644 help = usage + '''\
3645
3646 optional arguments:
3647 -h, --help show this help message and exit
3648 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3649 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3650 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3651 '''
3652 version = ''
3653
3654
3655class TestHelpUsagePositionalsOnlyWrap(HelpTestCase):
3656 """Test usage messages where there are only positionals and they wrap"""
3657
3658 parser_signature = Sig(prog='PROG', add_help=False)
3659 argument_signatures = [
3660 Sig('a' * 25),
3661 Sig('b' * 25),
3662 Sig('c' * 25),
3663 ]
3664 argument_group_signatures = []
3665 usage = '''\
3666 usage: PROG aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3667 ccccccccccccccccccccccccc
3668 '''
3669 help = usage + '''\
3670
3671 positional arguments:
3672 aaaaaaaaaaaaaaaaaaaaaaaaa
3673 bbbbbbbbbbbbbbbbbbbbbbbbb
3674 ccccccccccccccccccccccccc
3675 '''
3676 version = ''
3677
3678
3679class TestHelpVariableExpansion(HelpTestCase):
3680 """Test that variables are expanded properly in help messages"""
3681
3682 parser_signature = Sig(prog='PROG')
3683 argument_signatures = [
3684 Sig('-x', type=int,
3685 help='x %(prog)s %(default)s %(type)s %%'),
3686 Sig('-y', action='store_const', default=42, const='XXX',
3687 help='y %(prog)s %(default)s %(const)s'),
3688 Sig('--foo', choices='abc',
3689 help='foo %(prog)s %(default)s %(choices)s'),
3690 Sig('--bar', default='baz', choices=[1, 2], metavar='BBB',
3691 help='bar %(prog)s %(default)s %(dest)s'),
3692 Sig('spam', help='spam %(prog)s %(default)s'),
3693 Sig('badger', default=0.5, help='badger %(prog)s %(default)s'),
3694 ]
3695 argument_group_signatures = [
3696 (Sig('group'), [
3697 Sig('-a', help='a %(prog)s %(default)s'),
3698 Sig('-b', default=-1, help='b %(prog)s %(default)s'),
3699 ])
3700 ]
3701 usage = ('''\
3702 usage: PROG [-h] [-x X] [-y] [--foo {a,b,c}] [--bar BBB] [-a A] [-b B]
3703 spam badger
3704 ''')
3705 help = usage + '''\
3706
3707 positional arguments:
3708 spam spam PROG None
3709 badger badger PROG 0.5
3710
3711 optional arguments:
3712 -h, --help show this help message and exit
3713 -x X x PROG None int %
3714 -y y PROG 42 XXX
3715 --foo {a,b,c} foo PROG None a, b, c
3716 --bar BBB bar PROG baz bar
3717
3718 group:
3719 -a A a PROG None
3720 -b B b PROG -1
3721 '''
3722 version = ''
3723
3724
3725class TestHelpVariableExpansionUsageSupplied(HelpTestCase):
3726 """Test that variables are expanded properly when usage= is present"""
3727
3728 parser_signature = Sig(prog='PROG', usage='%(prog)s FOO')
3729 argument_signatures = []
3730 argument_group_signatures = []
3731 usage = ('''\
3732 usage: PROG FOO
3733 ''')
3734 help = usage + '''\
3735
3736 optional arguments:
3737 -h, --help show this help message and exit
3738 '''
3739 version = ''
3740
3741
3742class TestHelpVariableExpansionNoArguments(HelpTestCase):
3743 """Test that variables are expanded properly with no arguments"""
3744
3745 parser_signature = Sig(prog='PROG', add_help=False)
3746 argument_signatures = []
3747 argument_group_signatures = []
3748 usage = ('''\
3749 usage: PROG
3750 ''')
3751 help = usage
3752 version = ''
3753
3754
3755class TestHelpSuppressUsage(HelpTestCase):
3756 """Test that items can be suppressed in usage messages"""
3757
3758 parser_signature = Sig(prog='PROG', usage=argparse.SUPPRESS)
3759 argument_signatures = [
3760 Sig('--foo', help='foo help'),
3761 Sig('spam', help='spam help'),
3762 ]
3763 argument_group_signatures = []
3764 help = '''\
3765 positional arguments:
3766 spam spam help
3767
3768 optional arguments:
3769 -h, --help show this help message and exit
3770 --foo FOO foo help
3771 '''
3772 usage = ''
3773 version = ''
3774
3775
3776class TestHelpSuppressOptional(HelpTestCase):
3777 """Test that optional arguments can be suppressed in help messages"""
3778
3779 parser_signature = Sig(prog='PROG', add_help=False)
3780 argument_signatures = [
3781 Sig('--foo', help=argparse.SUPPRESS),
3782 Sig('spam', help='spam help'),
3783 ]
3784 argument_group_signatures = []
3785 usage = '''\
3786 usage: PROG spam
3787 '''
3788 help = usage + '''\
3789
3790 positional arguments:
3791 spam spam help
3792 '''
3793 version = ''
3794
3795
3796class TestHelpSuppressOptionalGroup(HelpTestCase):
3797 """Test that optional groups can be suppressed in help messages"""
3798
3799 parser_signature = Sig(prog='PROG')
3800 argument_signatures = [
3801 Sig('--foo', help='foo help'),
3802 Sig('spam', help='spam help'),
3803 ]
3804 argument_group_signatures = [
3805 (Sig('group'), [Sig('--bar', help=argparse.SUPPRESS)]),
3806 ]
3807 usage = '''\
3808 usage: PROG [-h] [--foo FOO] spam
3809 '''
3810 help = usage + '''\
3811
3812 positional arguments:
3813 spam spam help
3814
3815 optional arguments:
3816 -h, --help show this help message and exit
3817 --foo FOO foo help
3818 '''
3819 version = ''
3820
3821
3822class TestHelpSuppressPositional(HelpTestCase):
3823 """Test that positional arguments can be suppressed in help messages"""
3824
3825 parser_signature = Sig(prog='PROG')
3826 argument_signatures = [
3827 Sig('--foo', help='foo help'),
3828 Sig('spam', help=argparse.SUPPRESS),
3829 ]
3830 argument_group_signatures = []
3831 usage = '''\
3832 usage: PROG [-h] [--foo FOO]
3833 '''
3834 help = usage + '''\
3835
3836 optional arguments:
3837 -h, --help show this help message and exit
3838 --foo FOO foo help
3839 '''
3840 version = ''
3841
3842
3843class TestHelpRequiredOptional(HelpTestCase):
3844 """Test that required options don't look optional"""
3845
3846 parser_signature = Sig(prog='PROG')
3847 argument_signatures = [
3848 Sig('--foo', required=True, help='foo help'),
3849 ]
3850 argument_group_signatures = []
3851 usage = '''\
3852 usage: PROG [-h] --foo FOO
3853 '''
3854 help = usage + '''\
3855
3856 optional arguments:
3857 -h, --help show this help message and exit
3858 --foo FOO foo help
3859 '''
3860 version = ''
3861
3862
3863class TestHelpAlternatePrefixChars(HelpTestCase):
3864 """Test that options display with different prefix characters"""
3865
3866 parser_signature = Sig(prog='PROG', prefix_chars='^;', add_help=False)
3867 argument_signatures = [
3868 Sig('^^foo', action='store_true', help='foo help'),
3869 Sig(';b', ';;bar', help='bar help'),
3870 ]
3871 argument_group_signatures = []
3872 usage = '''\
3873 usage: PROG [^^foo] [;b BAR]
3874 '''
3875 help = usage + '''\
3876
3877 optional arguments:
3878 ^^foo foo help
3879 ;b BAR, ;;bar BAR bar help
3880 '''
3881 version = ''
3882
3883
3884class TestHelpNoHelpOptional(HelpTestCase):
3885 """Test that the --help argument can be suppressed help messages"""
3886
3887 parser_signature = Sig(prog='PROG', add_help=False)
3888 argument_signatures = [
3889 Sig('--foo', help='foo help'),
3890 Sig('spam', help='spam help'),
3891 ]
3892 argument_group_signatures = []
3893 usage = '''\
3894 usage: PROG [--foo FOO] spam
3895 '''
3896 help = usage + '''\
3897
3898 positional arguments:
3899 spam spam help
3900
3901 optional arguments:
3902 --foo FOO foo help
3903 '''
3904 version = ''
3905
3906
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003907class TestHelpNone(HelpTestCase):
3908 """Test that no errors occur if no help is specified"""
3909
3910 parser_signature = Sig(prog='PROG')
3911 argument_signatures = [
3912 Sig('--foo'),
3913 Sig('spam'),
3914 ]
3915 argument_group_signatures = []
3916 usage = '''\
3917 usage: PROG [-h] [--foo FOO] spam
3918 '''
3919 help = usage + '''\
3920
3921 positional arguments:
3922 spam
3923
3924 optional arguments:
3925 -h, --help show this help message and exit
3926 --foo FOO
3927 '''
3928 version = ''
3929
3930
3931class TestHelpTupleMetavar(HelpTestCase):
3932 """Test specifying metavar as a tuple"""
3933
3934 parser_signature = Sig(prog='PROG')
3935 argument_signatures = [
3936 Sig('-w', help='w', nargs='+', metavar=('W1', 'W2')),
3937 Sig('-x', help='x', nargs='*', metavar=('X1', 'X2')),
3938 Sig('-y', help='y', nargs=3, metavar=('Y1', 'Y2', 'Y3')),
3939 Sig('-z', help='z', nargs='?', metavar=('Z1', )),
3940 ]
3941 argument_group_signatures = []
3942 usage = '''\
3943 usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] \
3944[-z [Z1]]
3945 '''
3946 help = usage + '''\
3947
3948 optional arguments:
3949 -h, --help show this help message and exit
3950 -w W1 [W2 ...] w
3951 -x [X1 [X2 ...]] x
3952 -y Y1 Y2 Y3 y
3953 -z [Z1] z
3954 '''
3955 version = ''
3956
3957
3958class TestHelpRawText(HelpTestCase):
3959 """Test the RawTextHelpFormatter"""
3960
3961 parser_signature = Sig(
3962 prog='PROG', formatter_class=argparse.RawTextHelpFormatter,
3963 description='Keep the formatting\n'
3964 ' exactly as it is written\n'
3965 '\n'
3966 'here\n')
3967
3968 argument_signatures = [
3969 Sig('--foo', help=' foo help should also\n'
3970 'appear as given here'),
3971 Sig('spam', help='spam help'),
3972 ]
3973 argument_group_signatures = [
3974 (Sig('title', description=' This text\n'
3975 ' should be indented\n'
3976 ' exactly like it is here\n'),
3977 [Sig('--bar', help='bar help')]),
3978 ]
3979 usage = '''\
3980 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
3981 '''
3982 help = usage + '''\
3983
3984 Keep the formatting
3985 exactly as it is written
3986
3987 here
3988
3989 positional arguments:
3990 spam spam help
3991
3992 optional arguments:
3993 -h, --help show this help message and exit
3994 --foo FOO foo help should also
3995 appear as given here
3996
3997 title:
3998 This text
3999 should be indented
4000 exactly like it is here
4001
4002 --bar BAR bar help
4003 '''
4004 version = ''
4005
4006
4007class TestHelpRawDescription(HelpTestCase):
4008 """Test the RawTextHelpFormatter"""
4009
4010 parser_signature = Sig(
4011 prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter,
4012 description='Keep the formatting\n'
4013 ' exactly as it is written\n'
4014 '\n'
4015 'here\n')
4016
4017 argument_signatures = [
4018 Sig('--foo', help=' foo help should not\n'
4019 ' retain this odd formatting'),
4020 Sig('spam', help='spam help'),
4021 ]
4022 argument_group_signatures = [
4023 (Sig('title', description=' This text\n'
4024 ' should be indented\n'
4025 ' exactly like it is here\n'),
4026 [Sig('--bar', help='bar help')]),
4027 ]
4028 usage = '''\
4029 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
4030 '''
4031 help = usage + '''\
4032
4033 Keep the formatting
4034 exactly as it is written
4035
4036 here
4037
4038 positional arguments:
4039 spam spam help
4040
4041 optional arguments:
4042 -h, --help show this help message and exit
4043 --foo FOO foo help should not retain this odd formatting
4044
4045 title:
4046 This text
4047 should be indented
4048 exactly like it is here
4049
4050 --bar BAR bar help
4051 '''
4052 version = ''
4053
4054
4055class TestHelpArgumentDefaults(HelpTestCase):
4056 """Test the ArgumentDefaultsHelpFormatter"""
4057
4058 parser_signature = Sig(
4059 prog='PROG', formatter_class=argparse.ArgumentDefaultsHelpFormatter,
4060 description='description')
4061
4062 argument_signatures = [
4063 Sig('--foo', help='foo help - oh and by the way, %(default)s'),
4064 Sig('--bar', action='store_true', help='bar help'),
4065 Sig('spam', help='spam help'),
4066 Sig('badger', nargs='?', default='wooden', help='badger help'),
4067 ]
4068 argument_group_signatures = [
4069 (Sig('title', description='description'),
4070 [Sig('--baz', type=int, default=42, help='baz help')]),
4071 ]
4072 usage = '''\
4073 usage: PROG [-h] [--foo FOO] [--bar] [--baz BAZ] spam [badger]
4074 '''
4075 help = usage + '''\
4076
4077 description
4078
4079 positional arguments:
4080 spam spam help
4081 badger badger help (default: wooden)
4082
4083 optional arguments:
4084 -h, --help show this help message and exit
4085 --foo FOO foo help - oh and by the way, None
4086 --bar bar help (default: False)
4087
4088 title:
4089 description
4090
4091 --baz BAZ baz help (default: 42)
4092 '''
4093 version = ''
4094
Steven Bethard50fe5932010-05-24 03:47:38 +00004095class TestHelpVersionAction(HelpTestCase):
4096 """Test the default help for the version action"""
4097
4098 parser_signature = Sig(prog='PROG', description='description')
4099 argument_signatures = [Sig('-V', '--version', action='version', version='3.6')]
4100 argument_group_signatures = []
4101 usage = '''\
4102 usage: PROG [-h] [-V]
4103 '''
4104 help = usage + '''\
4105
4106 description
4107
4108 optional arguments:
4109 -h, --help show this help message and exit
4110 -V, --version show program's version number and exit
4111 '''
4112 version = ''
4113
Berker Peksagecb75e22015-04-10 16:11:12 +03004114
4115class TestHelpVersionActionSuppress(HelpTestCase):
4116 """Test that the --version argument can be suppressed in help messages"""
4117
4118 parser_signature = Sig(prog='PROG')
4119 argument_signatures = [
4120 Sig('-v', '--version', action='version', version='1.0',
4121 help=argparse.SUPPRESS),
4122 Sig('--foo', help='foo help'),
4123 Sig('spam', help='spam help'),
4124 ]
4125 argument_group_signatures = []
4126 usage = '''\
4127 usage: PROG [-h] [--foo FOO] spam
4128 '''
4129 help = usage + '''\
4130
4131 positional arguments:
4132 spam spam help
4133
4134 optional arguments:
4135 -h, --help show this help message and exit
4136 --foo FOO foo help
4137 '''
4138
4139
Steven Bethard8a6a1982011-03-27 13:53:53 +02004140class TestHelpSubparsersOrdering(HelpTestCase):
4141 """Test ordering of subcommands in help matches the code"""
4142 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004143 description='display some subcommands')
4144 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004145
4146 subparsers_signatures = [Sig(name=name)
4147 for name in ('a', 'b', 'c', 'd', 'e')]
4148
4149 usage = '''\
4150 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4151 '''
4152
4153 help = usage + '''\
4154
4155 display some subcommands
4156
4157 positional arguments:
4158 {a,b,c,d,e}
4159
4160 optional arguments:
4161 -h, --help show this help message and exit
4162 -v, --version show program's version number and exit
4163 '''
4164
4165 version = '''\
4166 0.1
4167 '''
4168
4169class TestHelpSubparsersWithHelpOrdering(HelpTestCase):
4170 """Test ordering of subcommands in help matches the code"""
4171 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004172 description='display some subcommands')
4173 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004174
4175 subcommand_data = (('a', 'a subcommand help'),
4176 ('b', 'b subcommand help'),
4177 ('c', 'c subcommand help'),
4178 ('d', 'd subcommand help'),
4179 ('e', 'e subcommand help'),
4180 )
4181
4182 subparsers_signatures = [Sig(name=name, help=help)
4183 for name, help in subcommand_data]
4184
4185 usage = '''\
4186 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4187 '''
4188
4189 help = usage + '''\
4190
4191 display some subcommands
4192
4193 positional arguments:
4194 {a,b,c,d,e}
4195 a a subcommand help
4196 b b subcommand help
4197 c c subcommand help
4198 d d subcommand help
4199 e e subcommand help
4200
4201 optional arguments:
4202 -h, --help show this help message and exit
4203 -v, --version show program's version number and exit
4204 '''
4205
4206 version = '''\
4207 0.1
4208 '''
4209
4210
Steven Bethard0331e902011-03-26 14:48:04 +01004211
4212class TestHelpMetavarTypeFormatter(HelpTestCase):
4213 """"""
4214
4215 def custom_type(string):
4216 return string
4217
4218 parser_signature = Sig(prog='PROG', description='description',
4219 formatter_class=argparse.MetavarTypeHelpFormatter)
4220 argument_signatures = [Sig('a', type=int),
4221 Sig('-b', type=custom_type),
4222 Sig('-c', type=float, metavar='SOME FLOAT')]
4223 argument_group_signatures = []
4224 usage = '''\
4225 usage: PROG [-h] [-b custom_type] [-c SOME FLOAT] int
4226 '''
4227 help = usage + '''\
4228
4229 description
4230
4231 positional arguments:
4232 int
4233
4234 optional arguments:
4235 -h, --help show this help message and exit
4236 -b custom_type
4237 -c SOME FLOAT
4238 '''
4239 version = ''
4240
4241
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004242# =====================================
4243# Optional/Positional constructor tests
4244# =====================================
4245
4246class TestInvalidArgumentConstructors(TestCase):
4247 """Test a bunch of invalid Argument constructors"""
4248
4249 def assertTypeError(self, *args, **kwargs):
4250 parser = argparse.ArgumentParser()
4251 self.assertRaises(TypeError, parser.add_argument,
4252 *args, **kwargs)
4253
4254 def assertValueError(self, *args, **kwargs):
4255 parser = argparse.ArgumentParser()
4256 self.assertRaises(ValueError, parser.add_argument,
4257 *args, **kwargs)
4258
4259 def test_invalid_keyword_arguments(self):
4260 self.assertTypeError('-x', bar=None)
4261 self.assertTypeError('-y', callback='foo')
4262 self.assertTypeError('-y', callback_args=())
4263 self.assertTypeError('-y', callback_kwargs={})
4264
4265 def test_missing_destination(self):
4266 self.assertTypeError()
4267 for action in ['append', 'store']:
4268 self.assertTypeError(action=action)
4269
4270 def test_invalid_option_strings(self):
4271 self.assertValueError('--')
4272 self.assertValueError('---')
4273
4274 def test_invalid_type(self):
4275 self.assertValueError('--foo', type='int')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004276 self.assertValueError('--foo', type=(int, float))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004277
4278 def test_invalid_action(self):
4279 self.assertValueError('-x', action='foo')
4280 self.assertValueError('foo', action='baz')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004281 self.assertValueError('--foo', action=('store', 'append'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004282 parser = argparse.ArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004283 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004284 parser.add_argument("--foo", action="store-true")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004285 self.assertIn('unknown action', str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004286
4287 def test_multiple_dest(self):
4288 parser = argparse.ArgumentParser()
4289 parser.add_argument(dest='foo')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004290 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004291 parser.add_argument('bar', dest='baz')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004292 self.assertIn('dest supplied twice for positional argument',
4293 str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004294
4295 def test_no_argument_actions(self):
4296 for action in ['store_const', 'store_true', 'store_false',
4297 'append_const', 'count']:
4298 for attrs in [dict(type=int), dict(nargs='+'),
4299 dict(choices='ab')]:
4300 self.assertTypeError('-x', action=action, **attrs)
4301
4302 def test_no_argument_no_const_actions(self):
4303 # options with zero arguments
4304 for action in ['store_true', 'store_false', 'count']:
4305
4306 # const is always disallowed
4307 self.assertTypeError('-x', const='foo', action=action)
4308
4309 # nargs is always disallowed
4310 self.assertTypeError('-x', nargs='*', action=action)
4311
4312 def test_more_than_one_argument_actions(self):
4313 for action in ['store', 'append']:
4314
4315 # nargs=0 is disallowed
4316 self.assertValueError('-x', nargs=0, action=action)
4317 self.assertValueError('spam', nargs=0, action=action)
4318
4319 # const is disallowed with non-optional arguments
4320 for nargs in [1, '*', '+']:
4321 self.assertValueError('-x', const='foo',
4322 nargs=nargs, action=action)
4323 self.assertValueError('spam', const='foo',
4324 nargs=nargs, action=action)
4325
4326 def test_required_const_actions(self):
4327 for action in ['store_const', 'append_const']:
4328
4329 # nargs is always disallowed
4330 self.assertTypeError('-x', nargs='+', action=action)
4331
4332 def test_parsers_action_missing_params(self):
4333 self.assertTypeError('command', action='parsers')
4334 self.assertTypeError('command', action='parsers', prog='PROG')
4335 self.assertTypeError('command', action='parsers',
4336 parser_class=argparse.ArgumentParser)
4337
4338 def test_required_positional(self):
4339 self.assertTypeError('foo', required=True)
4340
4341 def test_user_defined_action(self):
4342
4343 class Success(Exception):
4344 pass
4345
4346 class Action(object):
4347
4348 def __init__(self,
4349 option_strings,
4350 dest,
4351 const,
4352 default,
4353 required=False):
4354 if dest == 'spam':
4355 if const is Success:
4356 if default is Success:
4357 raise Success()
4358
4359 def __call__(self, *args, **kwargs):
4360 pass
4361
4362 parser = argparse.ArgumentParser()
4363 self.assertRaises(Success, parser.add_argument, '--spam',
4364 action=Action, default=Success, const=Success)
4365 self.assertRaises(Success, parser.add_argument, 'spam',
4366 action=Action, default=Success, const=Success)
4367
4368# ================================
4369# Actions returned by add_argument
4370# ================================
4371
4372class TestActionsReturned(TestCase):
4373
4374 def test_dest(self):
4375 parser = argparse.ArgumentParser()
4376 action = parser.add_argument('--foo')
4377 self.assertEqual(action.dest, 'foo')
4378 action = parser.add_argument('-b', '--bar')
4379 self.assertEqual(action.dest, 'bar')
4380 action = parser.add_argument('-x', '-y')
4381 self.assertEqual(action.dest, 'x')
4382
4383 def test_misc(self):
4384 parser = argparse.ArgumentParser()
4385 action = parser.add_argument('--foo', nargs='?', const=42,
4386 default=84, type=int, choices=[1, 2],
4387 help='FOO', metavar='BAR', dest='baz')
4388 self.assertEqual(action.nargs, '?')
4389 self.assertEqual(action.const, 42)
4390 self.assertEqual(action.default, 84)
4391 self.assertEqual(action.type, int)
4392 self.assertEqual(action.choices, [1, 2])
4393 self.assertEqual(action.help, 'FOO')
4394 self.assertEqual(action.metavar, 'BAR')
4395 self.assertEqual(action.dest, 'baz')
4396
4397
4398# ================================
4399# Argument conflict handling tests
4400# ================================
4401
4402class TestConflictHandling(TestCase):
4403
4404 def test_bad_type(self):
4405 self.assertRaises(ValueError, argparse.ArgumentParser,
4406 conflict_handler='foo')
4407
4408 def test_conflict_error(self):
4409 parser = argparse.ArgumentParser()
4410 parser.add_argument('-x')
4411 self.assertRaises(argparse.ArgumentError,
4412 parser.add_argument, '-x')
4413 parser.add_argument('--spam')
4414 self.assertRaises(argparse.ArgumentError,
4415 parser.add_argument, '--spam')
4416
4417 def test_resolve_error(self):
4418 get_parser = argparse.ArgumentParser
4419 parser = get_parser(prog='PROG', conflict_handler='resolve')
4420
4421 parser.add_argument('-x', help='OLD X')
4422 parser.add_argument('-x', help='NEW X')
4423 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4424 usage: PROG [-h] [-x X]
4425
4426 optional arguments:
4427 -h, --help show this help message and exit
4428 -x X NEW X
4429 '''))
4430
4431 parser.add_argument('--spam', metavar='OLD_SPAM')
4432 parser.add_argument('--spam', metavar='NEW_SPAM')
4433 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4434 usage: PROG [-h] [-x X] [--spam NEW_SPAM]
4435
4436 optional arguments:
4437 -h, --help show this help message and exit
4438 -x X NEW X
4439 --spam NEW_SPAM
4440 '''))
4441
4442
4443# =============================
4444# Help and Version option tests
4445# =============================
4446
4447class TestOptionalsHelpVersionActions(TestCase):
4448 """Test the help and version actions"""
4449
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004450 def assertPrintHelpExit(self, parser, args_str):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004451 with self.assertRaises(ArgumentParserError) as cm:
4452 parser.parse_args(args_str.split())
4453 self.assertEqual(parser.format_help(), cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004454
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004455 def assertArgumentParserError(self, parser, *args):
4456 self.assertRaises(ArgumentParserError, parser.parse_args, args)
4457
4458 def test_version(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004459 parser = ErrorRaisingArgumentParser()
4460 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004461 self.assertPrintHelpExit(parser, '-h')
4462 self.assertPrintHelpExit(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004463 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004464
4465 def test_version_format(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004466 parser = ErrorRaisingArgumentParser(prog='PPP')
4467 parser.add_argument('-v', '--version', action='version', version='%(prog)s 3.5')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004468 with self.assertRaises(ArgumentParserError) as cm:
4469 parser.parse_args(['-v'])
4470 self.assertEqual('PPP 3.5\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004471
4472 def test_version_no_help(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004473 parser = ErrorRaisingArgumentParser(add_help=False)
4474 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004475 self.assertArgumentParserError(parser, '-h')
4476 self.assertArgumentParserError(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004477 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004478
4479 def test_version_action(self):
4480 parser = ErrorRaisingArgumentParser(prog='XXX')
4481 parser.add_argument('-V', action='version', version='%(prog)s 3.7')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004482 with self.assertRaises(ArgumentParserError) as cm:
4483 parser.parse_args(['-V'])
4484 self.assertEqual('XXX 3.7\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004485
4486 def test_no_help(self):
4487 parser = ErrorRaisingArgumentParser(add_help=False)
4488 self.assertArgumentParserError(parser, '-h')
4489 self.assertArgumentParserError(parser, '--help')
4490 self.assertArgumentParserError(parser, '-v')
4491 self.assertArgumentParserError(parser, '--version')
4492
4493 def test_alternate_help_version(self):
4494 parser = ErrorRaisingArgumentParser()
4495 parser.add_argument('-x', action='help')
4496 parser.add_argument('-y', action='version')
4497 self.assertPrintHelpExit(parser, '-x')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004498 self.assertArgumentParserError(parser, '-v')
4499 self.assertArgumentParserError(parser, '--version')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004500 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004501
4502 def test_help_version_extra_arguments(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004503 parser = ErrorRaisingArgumentParser()
4504 parser.add_argument('--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004505 parser.add_argument('-x', action='store_true')
4506 parser.add_argument('y')
4507
4508 # try all combinations of valid prefixes and suffixes
4509 valid_prefixes = ['', '-x', 'foo', '-x bar', 'baz -x']
4510 valid_suffixes = valid_prefixes + ['--bad-option', 'foo bar baz']
4511 for prefix in valid_prefixes:
4512 for suffix in valid_suffixes:
4513 format = '%s %%s %s' % (prefix, suffix)
4514 self.assertPrintHelpExit(parser, format % '-h')
4515 self.assertPrintHelpExit(parser, format % '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004516 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004517
4518
4519# ======================
4520# str() and repr() tests
4521# ======================
4522
4523class TestStrings(TestCase):
4524 """Test str() and repr() on Optionals and Positionals"""
4525
4526 def assertStringEqual(self, obj, result_string):
4527 for func in [str, repr]:
4528 self.assertEqual(func(obj), result_string)
4529
4530 def test_optional(self):
4531 option = argparse.Action(
4532 option_strings=['--foo', '-a', '-b'],
4533 dest='b',
4534 type='int',
4535 nargs='+',
4536 default=42,
4537 choices=[1, 2, 3],
4538 help='HELP',
4539 metavar='METAVAR')
4540 string = (
4541 "Action(option_strings=['--foo', '-a', '-b'], dest='b', "
4542 "nargs='+', const=None, default=42, type='int', "
4543 "choices=[1, 2, 3], help='HELP', metavar='METAVAR')")
4544 self.assertStringEqual(option, string)
4545
4546 def test_argument(self):
4547 argument = argparse.Action(
4548 option_strings=[],
4549 dest='x',
4550 type=float,
4551 nargs='?',
4552 default=2.5,
4553 choices=[0.5, 1.5, 2.5],
4554 help='H HH H',
4555 metavar='MV MV MV')
4556 string = (
4557 "Action(option_strings=[], dest='x', nargs='?', "
4558 "const=None, default=2.5, type=%r, choices=[0.5, 1.5, 2.5], "
4559 "help='H HH H', metavar='MV MV MV')" % float)
4560 self.assertStringEqual(argument, string)
4561
4562 def test_namespace(self):
4563 ns = argparse.Namespace(foo=42, bar='spam')
4564 string = "Namespace(bar='spam', foo=42)"
4565 self.assertStringEqual(ns, string)
4566
Berker Peksag76b17142015-07-29 23:51:47 +03004567 def test_namespace_starkwargs_notidentifier(self):
4568 ns = argparse.Namespace(**{'"': 'quote'})
4569 string = """Namespace(**{'"': 'quote'})"""
4570 self.assertStringEqual(ns, string)
4571
4572 def test_namespace_kwargs_and_starkwargs_notidentifier(self):
4573 ns = argparse.Namespace(a=1, **{'"': 'quote'})
4574 string = """Namespace(a=1, **{'"': 'quote'})"""
4575 self.assertStringEqual(ns, string)
4576
4577 def test_namespace_starkwargs_identifier(self):
4578 ns = argparse.Namespace(**{'valid': True})
4579 string = "Namespace(valid=True)"
4580 self.assertStringEqual(ns, string)
4581
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004582 def test_parser(self):
4583 parser = argparse.ArgumentParser(prog='PROG')
4584 string = (
4585 "ArgumentParser(prog='PROG', usage=None, description=None, "
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004586 "formatter_class=%r, conflict_handler='error', "
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004587 "add_help=True)" % argparse.HelpFormatter)
4588 self.assertStringEqual(parser, string)
4589
4590# ===============
4591# Namespace tests
4592# ===============
4593
4594class TestNamespace(TestCase):
4595
4596 def test_constructor(self):
4597 ns = argparse.Namespace()
4598 self.assertRaises(AttributeError, getattr, ns, 'x')
4599
4600 ns = argparse.Namespace(a=42, b='spam')
4601 self.assertEqual(ns.a, 42)
4602 self.assertEqual(ns.b, 'spam')
4603
4604 def test_equality(self):
4605 ns1 = argparse.Namespace(a=1, b=2)
4606 ns2 = argparse.Namespace(b=2, a=1)
4607 ns3 = argparse.Namespace(a=1)
4608 ns4 = argparse.Namespace(b=2)
4609
4610 self.assertEqual(ns1, ns2)
4611 self.assertNotEqual(ns1, ns3)
4612 self.assertNotEqual(ns1, ns4)
4613 self.assertNotEqual(ns2, ns3)
4614 self.assertNotEqual(ns2, ns4)
4615 self.assertTrue(ns1 != ns3)
4616 self.assertTrue(ns1 != ns4)
4617 self.assertTrue(ns2 != ns3)
4618 self.assertTrue(ns2 != ns4)
4619
Berker Peksagc16387b2016-09-28 17:21:52 +03004620 def test_equality_returns_notimplemented(self):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07004621 # See issue 21481
4622 ns = argparse.Namespace(a=1, b=2)
4623 self.assertIs(ns.__eq__(None), NotImplemented)
4624 self.assertIs(ns.__ne__(None), NotImplemented)
4625
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004626
4627# ===================
4628# File encoding tests
4629# ===================
4630
4631class TestEncoding(TestCase):
4632
4633 def _test_module_encoding(self, path):
4634 path, _ = os.path.splitext(path)
4635 path += ".py"
Victor Stinner272d8882017-06-16 08:59:01 +02004636 with open(path, 'r', encoding='utf-8') as f:
Antoine Pitroub86680e2010-10-14 21:15:17 +00004637 f.read()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004638
4639 def test_argparse_module_encoding(self):
4640 self._test_module_encoding(argparse.__file__)
4641
4642 def test_test_argparse_module_encoding(self):
4643 self._test_module_encoding(__file__)
4644
4645# ===================
4646# ArgumentError tests
4647# ===================
4648
4649class TestArgumentError(TestCase):
4650
4651 def test_argument_error(self):
4652 msg = "my error here"
4653 error = argparse.ArgumentError(None, msg)
4654 self.assertEqual(str(error), msg)
4655
4656# =======================
4657# ArgumentTypeError tests
4658# =======================
4659
R. David Murray722b5fd2010-11-20 03:48:58 +00004660class TestArgumentTypeError(TestCase):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004661
4662 def test_argument_type_error(self):
4663
4664 def spam(string):
4665 raise argparse.ArgumentTypeError('spam!')
4666
4667 parser = ErrorRaisingArgumentParser(prog='PROG', add_help=False)
4668 parser.add_argument('x', type=spam)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004669 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004670 parser.parse_args(['XXX'])
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004671 self.assertEqual('usage: PROG x\nPROG: error: argument x: spam!\n',
4672 cm.exception.stderr)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004673
R David Murrayf97c59a2011-06-09 12:34:07 -04004674# =========================
4675# MessageContentError tests
4676# =========================
4677
4678class TestMessageContentError(TestCase):
4679
4680 def test_missing_argument_name_in_message(self):
4681 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4682 parser.add_argument('req_pos', type=str)
4683 parser.add_argument('-req_opt', type=int, required=True)
4684 parser.add_argument('need_one', type=str, nargs='+')
4685
4686 with self.assertRaises(ArgumentParserError) as cm:
4687 parser.parse_args([])
4688 msg = str(cm.exception)
4689 self.assertRegex(msg, 'req_pos')
4690 self.assertRegex(msg, 'req_opt')
4691 self.assertRegex(msg, 'need_one')
4692 with self.assertRaises(ArgumentParserError) as cm:
4693 parser.parse_args(['myXargument'])
4694 msg = str(cm.exception)
4695 self.assertNotIn(msg, 'req_pos')
4696 self.assertRegex(msg, 'req_opt')
4697 self.assertRegex(msg, 'need_one')
4698 with self.assertRaises(ArgumentParserError) as cm:
4699 parser.parse_args(['myXargument', '-req_opt=1'])
4700 msg = str(cm.exception)
4701 self.assertNotIn(msg, 'req_pos')
4702 self.assertNotIn(msg, 'req_opt')
4703 self.assertRegex(msg, 'need_one')
4704
4705 def test_optional_optional_not_in_message(self):
4706 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4707 parser.add_argument('req_pos', type=str)
4708 parser.add_argument('--req_opt', type=int, required=True)
4709 parser.add_argument('--opt_opt', type=bool, nargs='?',
4710 default=True)
4711 with self.assertRaises(ArgumentParserError) as cm:
4712 parser.parse_args([])
4713 msg = str(cm.exception)
4714 self.assertRegex(msg, 'req_pos')
4715 self.assertRegex(msg, 'req_opt')
4716 self.assertNotIn(msg, 'opt_opt')
4717 with self.assertRaises(ArgumentParserError) as cm:
4718 parser.parse_args(['--req_opt=1'])
4719 msg = str(cm.exception)
4720 self.assertRegex(msg, 'req_pos')
4721 self.assertNotIn(msg, 'req_opt')
4722 self.assertNotIn(msg, 'opt_opt')
4723
4724 def test_optional_positional_not_in_message(self):
4725 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4726 parser.add_argument('req_pos')
4727 parser.add_argument('optional_positional', nargs='?', default='eggs')
4728 with self.assertRaises(ArgumentParserError) as cm:
4729 parser.parse_args([])
4730 msg = str(cm.exception)
4731 self.assertRegex(msg, 'req_pos')
4732 self.assertNotIn(msg, 'optional_positional')
4733
4734
R David Murray6fb8fb12012-08-31 22:45:20 -04004735# ================================================
4736# Check that the type function is called only once
4737# ================================================
4738
4739class TestTypeFunctionCallOnlyOnce(TestCase):
4740
4741 def test_type_function_call_only_once(self):
4742 def spam(string_to_convert):
4743 self.assertEqual(string_to_convert, 'spam!')
4744 return 'foo_converted'
4745
4746 parser = argparse.ArgumentParser()
4747 parser.add_argument('--foo', type=spam, default='bar')
4748 args = parser.parse_args('--foo spam!'.split())
4749 self.assertEqual(NS(foo='foo_converted'), args)
4750
Barry Warsaweaae1b72012-09-12 14:34:50 -04004751# ==================================================================
4752# Check semantics regarding the default argument and type conversion
4753# ==================================================================
R David Murray6fb8fb12012-08-31 22:45:20 -04004754
Barry Warsaweaae1b72012-09-12 14:34:50 -04004755class TestTypeFunctionCalledOnDefault(TestCase):
R David Murray6fb8fb12012-08-31 22:45:20 -04004756
4757 def test_type_function_call_with_non_string_default(self):
4758 def spam(int_to_convert):
4759 self.assertEqual(int_to_convert, 0)
4760 return 'foo_converted'
4761
4762 parser = argparse.ArgumentParser()
4763 parser.add_argument('--foo', type=spam, default=0)
4764 args = parser.parse_args([])
Barry Warsaweaae1b72012-09-12 14:34:50 -04004765 # foo should *not* be converted because its default is not a string.
4766 self.assertEqual(NS(foo=0), args)
4767
4768 def test_type_function_call_with_string_default(self):
4769 def spam(int_to_convert):
4770 return 'foo_converted'
4771
4772 parser = argparse.ArgumentParser()
4773 parser.add_argument('--foo', type=spam, default='0')
4774 args = parser.parse_args([])
4775 # foo is converted because its default is a string.
R David Murray6fb8fb12012-08-31 22:45:20 -04004776 self.assertEqual(NS(foo='foo_converted'), args)
4777
Barry Warsaweaae1b72012-09-12 14:34:50 -04004778 def test_no_double_type_conversion_of_default(self):
4779 def extend(str_to_convert):
4780 return str_to_convert + '*'
4781
4782 parser = argparse.ArgumentParser()
4783 parser.add_argument('--test', type=extend, default='*')
4784 args = parser.parse_args([])
4785 # The test argument will be two stars, one coming from the default
4786 # value and one coming from the type conversion being called exactly
4787 # once.
4788 self.assertEqual(NS(test='**'), args)
4789
Barry Warsaw4b2f9e92012-09-11 22:38:47 -04004790 def test_issue_15906(self):
4791 # Issue #15906: When action='append', type=str, default=[] are
4792 # providing, the dest value was the string representation "[]" when it
4793 # should have been an empty list.
4794 parser = argparse.ArgumentParser()
4795 parser.add_argument('--test', dest='test', type=str,
4796 default=[], action='append')
4797 args = parser.parse_args([])
4798 self.assertEqual(args.test, [])
4799
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004800# ======================
4801# parse_known_args tests
4802# ======================
4803
4804class TestParseKnownArgs(TestCase):
4805
R David Murrayb5228282012-09-08 12:08:01 -04004806 def test_arguments_tuple(self):
4807 parser = argparse.ArgumentParser()
4808 parser.parse_args(())
4809
4810 def test_arguments_list(self):
4811 parser = argparse.ArgumentParser()
4812 parser.parse_args([])
4813
4814 def test_arguments_tuple_positional(self):
4815 parser = argparse.ArgumentParser()
4816 parser.add_argument('x')
4817 parser.parse_args(('x',))
4818
4819 def test_arguments_list_positional(self):
4820 parser = argparse.ArgumentParser()
4821 parser.add_argument('x')
4822 parser.parse_args(['x'])
4823
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004824 def test_optionals(self):
4825 parser = argparse.ArgumentParser()
4826 parser.add_argument('--foo')
4827 args, extras = parser.parse_known_args('--foo F --bar --baz'.split())
4828 self.assertEqual(NS(foo='F'), args)
4829 self.assertEqual(['--bar', '--baz'], extras)
4830
4831 def test_mixed(self):
4832 parser = argparse.ArgumentParser()
4833 parser.add_argument('-v', nargs='?', const=1, type=int)
4834 parser.add_argument('--spam', action='store_false')
4835 parser.add_argument('badger')
4836
4837 argv = ["B", "C", "--foo", "-v", "3", "4"]
4838 args, extras = parser.parse_known_args(argv)
4839 self.assertEqual(NS(v=3, spam=True, badger="B"), args)
4840 self.assertEqual(["C", "--foo", "4"], extras)
4841
R. David Murray0f6b9d22017-09-06 20:25:40 -04004842# ===========================
4843# parse_intermixed_args tests
4844# ===========================
4845
4846class TestIntermixedArgs(TestCase):
4847 def test_basic(self):
4848 # test parsing intermixed optionals and positionals
4849 parser = argparse.ArgumentParser(prog='PROG')
4850 parser.add_argument('--foo', dest='foo')
4851 bar = parser.add_argument('--bar', dest='bar', required=True)
4852 parser.add_argument('cmd')
4853 parser.add_argument('rest', nargs='*', type=int)
4854 argv = 'cmd --foo x 1 --bar y 2 3'.split()
4855 args = parser.parse_intermixed_args(argv)
4856 # rest gets [1,2,3] despite the foo and bar strings
4857 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args)
4858
4859 args, extras = parser.parse_known_args(argv)
4860 # cannot parse the '1,2,3'
4861 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[]), args)
4862 self.assertEqual(["1", "2", "3"], extras)
4863
4864 argv = 'cmd --foo x 1 --error 2 --bar y 3'.split()
4865 args, extras = parser.parse_known_intermixed_args(argv)
4866 # unknown optionals go into extras
4867 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1]), args)
4868 self.assertEqual(['--error', '2', '3'], extras)
4869
4870 # restores attributes that were temporarily changed
4871 self.assertIsNone(parser.usage)
4872 self.assertEqual(bar.required, True)
4873
4874 def test_remainder(self):
4875 # Intermixed and remainder are incompatible
4876 parser = ErrorRaisingArgumentParser(prog='PROG')
4877 parser.add_argument('-z')
4878 parser.add_argument('x')
4879 parser.add_argument('y', nargs='...')
4880 argv = 'X A B -z Z'.split()
4881 # intermixed fails with '...' (also 'A...')
4882 # self.assertRaises(TypeError, parser.parse_intermixed_args, argv)
4883 with self.assertRaises(TypeError) as cm:
4884 parser.parse_intermixed_args(argv)
4885 self.assertRegex(str(cm.exception), r'\.\.\.')
4886
4887 def test_exclusive(self):
4888 # mutually exclusive group; intermixed works fine
4889 parser = ErrorRaisingArgumentParser(prog='PROG')
4890 group = parser.add_mutually_exclusive_group(required=True)
4891 group.add_argument('--foo', action='store_true', help='FOO')
4892 group.add_argument('--spam', help='SPAM')
4893 parser.add_argument('badger', nargs='*', default='X', help='BADGER')
4894 args = parser.parse_intermixed_args('1 --foo 2'.split())
4895 self.assertEqual(NS(badger=['1', '2'], foo=True, spam=None), args)
4896 self.assertRaises(ArgumentParserError, parser.parse_intermixed_args, '1 2'.split())
4897 self.assertEqual(group.required, True)
4898
4899 def test_exclusive_incompatible(self):
4900 # mutually exclusive group including positional - fail
4901 parser = ErrorRaisingArgumentParser(prog='PROG')
4902 group = parser.add_mutually_exclusive_group(required=True)
4903 group.add_argument('--foo', action='store_true', help='FOO')
4904 group.add_argument('--spam', help='SPAM')
4905 group.add_argument('badger', nargs='*', default='X', help='BADGER')
4906 self.assertRaises(TypeError, parser.parse_intermixed_args, [])
4907 self.assertEqual(group.required, True)
4908
4909class TestIntermixedMessageContentError(TestCase):
4910 # case where Intermixed gives different error message
4911 # error is raised by 1st parsing step
4912 def test_missing_argument_name_in_message(self):
4913 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4914 parser.add_argument('req_pos', type=str)
4915 parser.add_argument('-req_opt', type=int, required=True)
4916
4917 with self.assertRaises(ArgumentParserError) as cm:
4918 parser.parse_args([])
4919 msg = str(cm.exception)
4920 self.assertRegex(msg, 'req_pos')
4921 self.assertRegex(msg, 'req_opt')
4922
4923 with self.assertRaises(ArgumentParserError) as cm:
4924 parser.parse_intermixed_args([])
4925 msg = str(cm.exception)
4926 self.assertNotRegex(msg, 'req_pos')
4927 self.assertRegex(msg, 'req_opt')
4928
Steven Bethard8d9a4622011-03-26 17:33:56 +01004929# ==========================
4930# add_argument metavar tests
4931# ==========================
4932
4933class TestAddArgumentMetavar(TestCase):
4934
4935 EXPECTED_MESSAGE = "length of metavar tuple does not match nargs"
4936
4937 def do_test_no_exception(self, nargs, metavar):
4938 parser = argparse.ArgumentParser()
4939 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
4940
4941 def do_test_exception(self, nargs, metavar):
4942 parser = argparse.ArgumentParser()
4943 with self.assertRaises(ValueError) as cm:
4944 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
4945 self.assertEqual(cm.exception.args[0], self.EXPECTED_MESSAGE)
4946
4947 # Unit tests for different values of metavar when nargs=None
4948
4949 def test_nargs_None_metavar_string(self):
4950 self.do_test_no_exception(nargs=None, metavar="1")
4951
4952 def test_nargs_None_metavar_length0(self):
4953 self.do_test_exception(nargs=None, metavar=tuple())
4954
4955 def test_nargs_None_metavar_length1(self):
4956 self.do_test_no_exception(nargs=None, metavar=("1"))
4957
4958 def test_nargs_None_metavar_length2(self):
4959 self.do_test_exception(nargs=None, metavar=("1", "2"))
4960
4961 def test_nargs_None_metavar_length3(self):
4962 self.do_test_exception(nargs=None, metavar=("1", "2", "3"))
4963
4964 # Unit tests for different values of metavar when nargs=?
4965
4966 def test_nargs_optional_metavar_string(self):
4967 self.do_test_no_exception(nargs="?", metavar="1")
4968
4969 def test_nargs_optional_metavar_length0(self):
4970 self.do_test_exception(nargs="?", metavar=tuple())
4971
4972 def test_nargs_optional_metavar_length1(self):
4973 self.do_test_no_exception(nargs="?", metavar=("1"))
4974
4975 def test_nargs_optional_metavar_length2(self):
4976 self.do_test_exception(nargs="?", metavar=("1", "2"))
4977
4978 def test_nargs_optional_metavar_length3(self):
4979 self.do_test_exception(nargs="?", metavar=("1", "2", "3"))
4980
4981 # Unit tests for different values of metavar when nargs=*
4982
4983 def test_nargs_zeroormore_metavar_string(self):
4984 self.do_test_no_exception(nargs="*", metavar="1")
4985
4986 def test_nargs_zeroormore_metavar_length0(self):
4987 self.do_test_exception(nargs="*", metavar=tuple())
4988
4989 def test_nargs_zeroormore_metavar_length1(self):
4990 self.do_test_no_exception(nargs="*", metavar=("1"))
4991
4992 def test_nargs_zeroormore_metavar_length2(self):
4993 self.do_test_no_exception(nargs="*", metavar=("1", "2"))
4994
4995 def test_nargs_zeroormore_metavar_length3(self):
4996 self.do_test_exception(nargs="*", metavar=("1", "2", "3"))
4997
4998 # Unit tests for different values of metavar when nargs=+
4999
5000 def test_nargs_oneormore_metavar_string(self):
5001 self.do_test_no_exception(nargs="+", metavar="1")
5002
5003 def test_nargs_oneormore_metavar_length0(self):
5004 self.do_test_exception(nargs="+", metavar=tuple())
5005
5006 def test_nargs_oneormore_metavar_length1(self):
5007 self.do_test_no_exception(nargs="+", metavar=("1"))
5008
5009 def test_nargs_oneormore_metavar_length2(self):
5010 self.do_test_no_exception(nargs="+", metavar=("1", "2"))
5011
5012 def test_nargs_oneormore_metavar_length3(self):
5013 self.do_test_exception(nargs="+", metavar=("1", "2", "3"))
5014
5015 # Unit tests for different values of metavar when nargs=...
5016
5017 def test_nargs_remainder_metavar_string(self):
5018 self.do_test_no_exception(nargs="...", metavar="1")
5019
5020 def test_nargs_remainder_metavar_length0(self):
5021 self.do_test_no_exception(nargs="...", metavar=tuple())
5022
5023 def test_nargs_remainder_metavar_length1(self):
5024 self.do_test_no_exception(nargs="...", metavar=("1"))
5025
5026 def test_nargs_remainder_metavar_length2(self):
5027 self.do_test_no_exception(nargs="...", metavar=("1", "2"))
5028
5029 def test_nargs_remainder_metavar_length3(self):
5030 self.do_test_no_exception(nargs="...", metavar=("1", "2", "3"))
5031
5032 # Unit tests for different values of metavar when nargs=A...
5033
5034 def test_nargs_parser_metavar_string(self):
5035 self.do_test_no_exception(nargs="A...", metavar="1")
5036
5037 def test_nargs_parser_metavar_length0(self):
5038 self.do_test_exception(nargs="A...", metavar=tuple())
5039
5040 def test_nargs_parser_metavar_length1(self):
5041 self.do_test_no_exception(nargs="A...", metavar=("1"))
5042
5043 def test_nargs_parser_metavar_length2(self):
5044 self.do_test_exception(nargs="A...", metavar=("1", "2"))
5045
5046 def test_nargs_parser_metavar_length3(self):
5047 self.do_test_exception(nargs="A...", metavar=("1", "2", "3"))
5048
5049 # Unit tests for different values of metavar when nargs=1
5050
5051 def test_nargs_1_metavar_string(self):
5052 self.do_test_no_exception(nargs=1, metavar="1")
5053
5054 def test_nargs_1_metavar_length0(self):
5055 self.do_test_exception(nargs=1, metavar=tuple())
5056
5057 def test_nargs_1_metavar_length1(self):
5058 self.do_test_no_exception(nargs=1, metavar=("1"))
5059
5060 def test_nargs_1_metavar_length2(self):
5061 self.do_test_exception(nargs=1, metavar=("1", "2"))
5062
5063 def test_nargs_1_metavar_length3(self):
5064 self.do_test_exception(nargs=1, metavar=("1", "2", "3"))
5065
5066 # Unit tests for different values of metavar when nargs=2
5067
5068 def test_nargs_2_metavar_string(self):
5069 self.do_test_no_exception(nargs=2, metavar="1")
5070
5071 def test_nargs_2_metavar_length0(self):
5072 self.do_test_exception(nargs=2, metavar=tuple())
5073
5074 def test_nargs_2_metavar_length1(self):
5075 self.do_test_no_exception(nargs=2, metavar=("1"))
5076
5077 def test_nargs_2_metavar_length2(self):
5078 self.do_test_no_exception(nargs=2, metavar=("1", "2"))
5079
5080 def test_nargs_2_metavar_length3(self):
5081 self.do_test_exception(nargs=2, metavar=("1", "2", "3"))
5082
5083 # Unit tests for different values of metavar when nargs=3
5084
5085 def test_nargs_3_metavar_string(self):
5086 self.do_test_no_exception(nargs=3, metavar="1")
5087
5088 def test_nargs_3_metavar_length0(self):
5089 self.do_test_exception(nargs=3, metavar=tuple())
5090
5091 def test_nargs_3_metavar_length1(self):
5092 self.do_test_no_exception(nargs=3, metavar=("1"))
5093
5094 def test_nargs_3_metavar_length2(self):
5095 self.do_test_exception(nargs=3, metavar=("1", "2"))
5096
5097 def test_nargs_3_metavar_length3(self):
5098 self.do_test_no_exception(nargs=3, metavar=("1", "2", "3"))
5099
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005100# ============================
5101# from argparse import * tests
5102# ============================
5103
5104class TestImportStar(TestCase):
5105
5106 def test(self):
5107 for name in argparse.__all__:
5108 self.assertTrue(hasattr(argparse, name))
5109
Steven Bethard72c55382010-11-01 15:23:12 +00005110 def test_all_exports_everything_but_modules(self):
5111 items = [
5112 name
5113 for name, value in vars(argparse).items()
Éric Araujo12159152010-12-04 17:31:49 +00005114 if not (name.startswith("_") or name == 'ngettext')
Steven Bethard72c55382010-11-01 15:23:12 +00005115 if not inspect.ismodule(value)
5116 ]
5117 self.assertEqual(sorted(items), sorted(argparse.__all__))
5118
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005119def test_main():
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02005120 support.run_unittest(__name__)
Benjamin Peterson4fd181c2010-03-02 23:46:42 +00005121 # Remove global references to avoid looking like we have refleaks.
5122 RFile.seen = {}
5123 WFile.seen = set()
5124
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005125
5126
5127if __name__ == '__main__':
5128 test_main()