blob: e849c7ba49bcd26fa70594b8fa085749e81db198 [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
Berker Peksag74102c92018-07-25 18:23:44 +030026 # variable. To ensure that this width is used, set COLUMNS to 80.
Steven Bethard1f1c2472010-11-01 13:56:09 +000027 env = support.EnvironmentVarGuard()
Berker Peksag74102c92018-07-25 18:23:44 +030028 env['COLUMNS'] = '80'
Steven Bethard1f1c2472010-11-01 13:56:09 +000029 self.addCleanup(env.__exit__)
Benjamin Peterson698a18a2010-03-02 22:34:37 +000030
Benjamin Petersonb48af542010-04-11 20:43:16 +000031
Benjamin Peterson698a18a2010-03-02 22:34:37 +000032class TempDirMixin(object):
33
34 def setUp(self):
35 self.temp_dir = tempfile.mkdtemp()
36 self.old_dir = os.getcwd()
37 os.chdir(self.temp_dir)
38
39 def tearDown(self):
40 os.chdir(self.old_dir)
Benjamin Peterson511e2222014-04-04 13:55:56 -040041 for root, dirs, files in os.walk(self.temp_dir, topdown=False):
42 for name in files:
43 os.chmod(os.path.join(self.temp_dir, name), stat.S_IWRITE)
Steven Bethardb0270112011-01-24 21:02:50 +000044 shutil.rmtree(self.temp_dir, True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +000045
Steven Bethardb0270112011-01-24 21:02:50 +000046 def create_readonly_file(self, filename):
47 file_path = os.path.join(self.temp_dir, filename)
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:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001382 with open(path, 'w') as file:
1383 file.write(text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001384
1385 parser_signature = Sig(fromfile_prefix_chars='@')
1386 argument_signatures = [
1387 Sig('-a'),
1388 Sig('x'),
1389 Sig('y', nargs='+'),
1390 ]
1391 failures = ['', '-b', 'X', '@invalid', '@missing']
1392 successes = [
1393 ('X Y', NS(a=None, x='X', y=['Y'])),
1394 ('X -a A Y Z', NS(a='A', x='X', y=['Y', 'Z'])),
1395 ('@hello X', NS(a=None, x='hello world!', y=['X'])),
1396 ('X @hello', NS(a=None, x='X', y=['hello world!'])),
1397 ('-a B @recursive Y Z', NS(a='A', x='hello world!', y=['Y', 'Z'])),
1398 ('X @recursive Z -a B', NS(a='B', x='X', y=['hello world!', 'Z'])),
R David Murrayb94082a2012-07-21 22:20:11 -04001399 (["-a", "", "X", "Y"], NS(a='', x='X', y=['Y'])),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001400 ]
1401
1402
1403class TestArgumentsFromFileConverter(TempDirMixin, ParserTestCase):
1404 """Test reading arguments from a file"""
1405
1406 def setUp(self):
1407 super(TestArgumentsFromFileConverter, self).setUp()
1408 file_texts = [
1409 ('hello', 'hello world!\n'),
1410 ]
1411 for path, text in file_texts:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001412 with open(path, 'w') as file:
1413 file.write(text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001414
1415 class FromFileConverterArgumentParser(ErrorRaisingArgumentParser):
1416
1417 def convert_arg_line_to_args(self, arg_line):
1418 for arg in arg_line.split():
1419 if not arg.strip():
1420 continue
1421 yield arg
1422 parser_class = FromFileConverterArgumentParser
1423 parser_signature = Sig(fromfile_prefix_chars='@')
1424 argument_signatures = [
1425 Sig('y', nargs='+'),
1426 ]
1427 failures = []
1428 successes = [
1429 ('@hello X', NS(y=['hello', 'world!', 'X'])),
1430 ]
1431
1432
1433# =====================
1434# Type conversion tests
1435# =====================
1436
1437class TestFileTypeRepr(TestCase):
1438
1439 def test_r(self):
1440 type = argparse.FileType('r')
1441 self.assertEqual("FileType('r')", repr(type))
1442
1443 def test_wb_1(self):
1444 type = argparse.FileType('wb', 1)
1445 self.assertEqual("FileType('wb', 1)", repr(type))
1446
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001447 def test_r_latin(self):
1448 type = argparse.FileType('r', encoding='latin_1')
1449 self.assertEqual("FileType('r', encoding='latin_1')", repr(type))
1450
1451 def test_w_big5_ignore(self):
1452 type = argparse.FileType('w', encoding='big5', errors='ignore')
1453 self.assertEqual("FileType('w', encoding='big5', errors='ignore')",
1454 repr(type))
1455
1456 def test_r_1_replace(self):
1457 type = argparse.FileType('r', 1, errors='replace')
1458 self.assertEqual("FileType('r', 1, errors='replace')", repr(type))
1459
Steve Dowerd0f49d22018-09-18 09:10:26 -07001460class StdStreamComparer:
1461 def __init__(self, attr):
1462 self.attr = attr
1463
1464 def __eq__(self, other):
1465 return other == getattr(sys, self.attr)
1466
1467eq_stdin = StdStreamComparer('stdin')
1468eq_stdout = StdStreamComparer('stdout')
1469eq_stderr = StdStreamComparer('stderr')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001470
1471class RFile(object):
1472 seen = {}
1473
1474 def __init__(self, name):
1475 self.name = name
1476
1477 def __eq__(self, other):
1478 if other in self.seen:
1479 text = self.seen[other]
1480 else:
1481 text = self.seen[other] = other.read()
1482 other.close()
1483 if not isinstance(text, str):
1484 text = text.decode('ascii')
1485 return self.name == other.name == text
1486
1487
1488class TestFileTypeR(TempDirMixin, ParserTestCase):
1489 """Test the FileType option/argument type for reading files"""
1490
1491 def setUp(self):
1492 super(TestFileTypeR, self).setUp()
1493 for file_name in ['foo', 'bar']:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001494 with open(os.path.join(self.temp_dir, file_name), 'w') as file:
1495 file.write(file_name)
Steven Bethardb0270112011-01-24 21:02:50 +00001496 self.create_readonly_file('readonly')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001497
1498 argument_signatures = [
1499 Sig('-x', type=argparse.FileType()),
1500 Sig('spam', type=argparse.FileType('r')),
1501 ]
Steven Bethardb0270112011-01-24 21:02:50 +00001502 failures = ['-x', '', 'non-existent-file.txt']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001503 successes = [
1504 ('foo', NS(x=None, spam=RFile('foo'))),
1505 ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
1506 ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001507 ('-x - -', NS(x=eq_stdin, spam=eq_stdin)),
Steven Bethardb0270112011-01-24 21:02:50 +00001508 ('readonly', NS(x=None, spam=RFile('readonly'))),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001509 ]
1510
R David Murray6fb8fb12012-08-31 22:45:20 -04001511class TestFileTypeDefaults(TempDirMixin, ParserTestCase):
1512 """Test that a file is not created unless the default is needed"""
1513 def setUp(self):
1514 super(TestFileTypeDefaults, self).setUp()
1515 file = open(os.path.join(self.temp_dir, 'good'), 'w')
1516 file.write('good')
1517 file.close()
1518
1519 argument_signatures = [
1520 Sig('-c', type=argparse.FileType('r'), default='no-file.txt'),
1521 ]
1522 # should provoke no such file error
1523 failures = ['']
1524 # should not provoke error because default file is created
1525 successes = [('-c good', NS(c=RFile('good')))]
1526
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001527
1528class TestFileTypeRB(TempDirMixin, ParserTestCase):
1529 """Test the FileType option/argument type for reading files"""
1530
1531 def setUp(self):
1532 super(TestFileTypeRB, self).setUp()
1533 for file_name in ['foo', 'bar']:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001534 with open(os.path.join(self.temp_dir, file_name), 'w') as file:
1535 file.write(file_name)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001536
1537 argument_signatures = [
1538 Sig('-x', type=argparse.FileType('rb')),
1539 Sig('spam', type=argparse.FileType('rb')),
1540 ]
1541 failures = ['-x', '']
1542 successes = [
1543 ('foo', NS(x=None, spam=RFile('foo'))),
1544 ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
1545 ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001546 ('-x - -', NS(x=eq_stdin, spam=eq_stdin)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001547 ]
1548
1549
1550class WFile(object):
1551 seen = set()
1552
1553 def __init__(self, name):
1554 self.name = name
1555
1556 def __eq__(self, other):
1557 if other not in self.seen:
1558 text = 'Check that file is writable.'
1559 if 'b' in other.mode:
1560 text = text.encode('ascii')
1561 other.write(text)
1562 other.close()
1563 self.seen.add(other)
1564 return self.name == other.name
1565
1566
Victor Stinnera04b39b2011-11-20 23:09:09 +01001567@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
1568 "non-root user required")
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001569class TestFileTypeW(TempDirMixin, ParserTestCase):
1570 """Test the FileType option/argument type for writing files"""
1571
Steven Bethardb0270112011-01-24 21:02:50 +00001572 def setUp(self):
1573 super(TestFileTypeW, self).setUp()
1574 self.create_readonly_file('readonly')
1575
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001576 argument_signatures = [
1577 Sig('-x', type=argparse.FileType('w')),
1578 Sig('spam', type=argparse.FileType('w')),
1579 ]
Steven Bethardb0270112011-01-24 21:02:50 +00001580 failures = ['-x', '', 'readonly']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001581 successes = [
1582 ('foo', NS(x=None, spam=WFile('foo'))),
1583 ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
1584 ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001585 ('-x - -', NS(x=eq_stdout, spam=eq_stdout)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001586 ]
1587
1588
1589class TestFileTypeWB(TempDirMixin, ParserTestCase):
1590
1591 argument_signatures = [
1592 Sig('-x', type=argparse.FileType('wb')),
1593 Sig('spam', type=argparse.FileType('wb')),
1594 ]
1595 failures = ['-x', '']
1596 successes = [
1597 ('foo', NS(x=None, spam=WFile('foo'))),
1598 ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
1599 ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001600 ('-x - -', NS(x=eq_stdout, spam=eq_stdout)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001601 ]
1602
1603
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001604class TestFileTypeOpenArgs(TestCase):
1605 """Test that open (the builtin) is correctly called"""
1606
1607 def test_open_args(self):
1608 FT = argparse.FileType
1609 cases = [
1610 (FT('rb'), ('rb', -1, None, None)),
1611 (FT('w', 1), ('w', 1, None, None)),
1612 (FT('w', errors='replace'), ('w', -1, None, 'replace')),
1613 (FT('wb', encoding='big5'), ('wb', -1, 'big5', None)),
1614 (FT('w', 0, 'l1', 'strict'), ('w', 0, 'l1', 'strict')),
1615 ]
1616 with mock.patch('builtins.open') as m:
1617 for type, args in cases:
1618 type('foo')
1619 m.assert_called_with('foo', *args)
1620
1621
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001622class TestTypeCallable(ParserTestCase):
1623 """Test some callables as option/argument types"""
1624
1625 argument_signatures = [
1626 Sig('--eggs', type=complex),
1627 Sig('spam', type=float),
1628 ]
1629 failures = ['a', '42j', '--eggs a', '--eggs 2i']
1630 successes = [
1631 ('--eggs=42 42', NS(eggs=42, spam=42.0)),
1632 ('--eggs 2j -- -1.5', NS(eggs=2j, spam=-1.5)),
1633 ('1024.675', NS(eggs=None, spam=1024.675)),
1634 ]
1635
1636
1637class TestTypeUserDefined(ParserTestCase):
1638 """Test a user-defined option/argument type"""
1639
1640 class MyType(TestCase):
1641
1642 def __init__(self, value):
1643 self.value = value
1644
1645 def __eq__(self, other):
1646 return (type(self), self.value) == (type(other), other.value)
1647
1648 argument_signatures = [
1649 Sig('-x', type=MyType),
1650 Sig('spam', type=MyType),
1651 ]
1652 failures = []
1653 successes = [
1654 ('a -x b', NS(x=MyType('b'), spam=MyType('a'))),
1655 ('-xf g', NS(x=MyType('f'), spam=MyType('g'))),
1656 ]
1657
1658
1659class TestTypeClassicClass(ParserTestCase):
1660 """Test a classic class type"""
1661
1662 class C:
1663
1664 def __init__(self, value):
1665 self.value = value
1666
1667 def __eq__(self, other):
1668 return (type(self), self.value) == (type(other), other.value)
1669
1670 argument_signatures = [
1671 Sig('-x', type=C),
1672 Sig('spam', type=C),
1673 ]
1674 failures = []
1675 successes = [
1676 ('a -x b', NS(x=C('b'), spam=C('a'))),
1677 ('-xf g', NS(x=C('f'), spam=C('g'))),
1678 ]
1679
1680
1681class TestTypeRegistration(TestCase):
1682 """Test a user-defined type by registering it"""
1683
1684 def test(self):
1685
1686 def get_my_type(string):
1687 return 'my_type{%s}' % string
1688
1689 parser = argparse.ArgumentParser()
1690 parser.register('type', 'my_type', get_my_type)
1691 parser.add_argument('-x', type='my_type')
1692 parser.add_argument('y', type='my_type')
1693
1694 self.assertEqual(parser.parse_args('1'.split()),
1695 NS(x=None, y='my_type{1}'))
1696 self.assertEqual(parser.parse_args('-x 1 42'.split()),
1697 NS(x='my_type{1}', y='my_type{42}'))
1698
1699
1700# ============
1701# Action tests
1702# ============
1703
1704class TestActionUserDefined(ParserTestCase):
1705 """Test a user-defined option/argument action"""
1706
1707 class OptionalAction(argparse.Action):
1708
1709 def __call__(self, parser, namespace, value, option_string=None):
1710 try:
1711 # check destination and option string
1712 assert self.dest == 'spam', 'dest: %s' % self.dest
1713 assert option_string == '-s', 'flag: %s' % option_string
1714 # when option is before argument, badger=2, and when
1715 # option is after argument, badger=<whatever was set>
1716 expected_ns = NS(spam=0.25)
1717 if value in [0.125, 0.625]:
1718 expected_ns.badger = 2
1719 elif value in [2.0]:
1720 expected_ns.badger = 84
1721 else:
1722 raise AssertionError('value: %s' % value)
1723 assert expected_ns == namespace, ('expected %s, got %s' %
1724 (expected_ns, namespace))
1725 except AssertionError:
1726 e = sys.exc_info()[1]
1727 raise ArgumentParserError('opt_action failed: %s' % e)
1728 setattr(namespace, 'spam', value)
1729
1730 class PositionalAction(argparse.Action):
1731
1732 def __call__(self, parser, namespace, value, option_string=None):
1733 try:
1734 assert option_string is None, ('option_string: %s' %
1735 option_string)
1736 # check destination
1737 assert self.dest == 'badger', 'dest: %s' % self.dest
1738 # when argument is before option, spam=0.25, and when
1739 # option is after argument, spam=<whatever was set>
1740 expected_ns = NS(badger=2)
1741 if value in [42, 84]:
1742 expected_ns.spam = 0.25
1743 elif value in [1]:
1744 expected_ns.spam = 0.625
1745 elif value in [2]:
1746 expected_ns.spam = 0.125
1747 else:
1748 raise AssertionError('value: %s' % value)
1749 assert expected_ns == namespace, ('expected %s, got %s' %
1750 (expected_ns, namespace))
1751 except AssertionError:
1752 e = sys.exc_info()[1]
1753 raise ArgumentParserError('arg_action failed: %s' % e)
1754 setattr(namespace, 'badger', value)
1755
1756 argument_signatures = [
1757 Sig('-s', dest='spam', action=OptionalAction,
1758 type=float, default=0.25),
1759 Sig('badger', action=PositionalAction,
1760 type=int, nargs='?', default=2),
1761 ]
1762 failures = []
1763 successes = [
1764 ('-s0.125', NS(spam=0.125, badger=2)),
1765 ('42', NS(spam=0.25, badger=42)),
1766 ('-s 0.625 1', NS(spam=0.625, badger=1)),
1767 ('84 -s2', NS(spam=2.0, badger=84)),
1768 ]
1769
1770
1771class TestActionRegistration(TestCase):
1772 """Test a user-defined action supplied by registering it"""
1773
1774 class MyAction(argparse.Action):
1775
1776 def __call__(self, parser, namespace, values, option_string=None):
1777 setattr(namespace, self.dest, 'foo[%s]' % values)
1778
1779 def test(self):
1780
1781 parser = argparse.ArgumentParser()
1782 parser.register('action', 'my_action', self.MyAction)
1783 parser.add_argument('badger', action='my_action')
1784
1785 self.assertEqual(parser.parse_args(['1']), NS(badger='foo[1]'))
1786 self.assertEqual(parser.parse_args(['42']), NS(badger='foo[42]'))
1787
1788
1789# ================
1790# Subparsers tests
1791# ================
1792
1793class TestAddSubparsers(TestCase):
1794 """Test the add_subparsers method"""
1795
1796 def assertArgumentParserError(self, *args, **kwargs):
1797 self.assertRaises(ArgumentParserError, *args, **kwargs)
1798
Steven Bethardfd311a72010-12-18 11:19:23 +00001799 def _get_parser(self, subparser_help=False, prefix_chars=None,
1800 aliases=False):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001801 # create a parser with a subparsers argument
R. David Murray88c49fe2010-08-03 17:56:09 +00001802 if prefix_chars:
1803 parser = ErrorRaisingArgumentParser(
1804 prog='PROG', description='main description', prefix_chars=prefix_chars)
1805 parser.add_argument(
1806 prefix_chars[0] * 2 + 'foo', action='store_true', help='foo help')
1807 else:
1808 parser = ErrorRaisingArgumentParser(
1809 prog='PROG', description='main description')
1810 parser.add_argument(
1811 '--foo', action='store_true', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001812 parser.add_argument(
1813 'bar', type=float, help='bar help')
1814
1815 # check that only one subparsers argument can be added
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001816 subparsers_kwargs = {'required': False}
Steven Bethardfd311a72010-12-18 11:19:23 +00001817 if aliases:
1818 subparsers_kwargs['metavar'] = 'COMMAND'
1819 subparsers_kwargs['title'] = 'commands'
1820 else:
1821 subparsers_kwargs['help'] = 'command help'
1822 subparsers = parser.add_subparsers(**subparsers_kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001823 self.assertArgumentParserError(parser.add_subparsers)
1824
1825 # add first sub-parser
1826 parser1_kwargs = dict(description='1 description')
1827 if subparser_help:
1828 parser1_kwargs['help'] = '1 help'
Steven Bethardfd311a72010-12-18 11:19:23 +00001829 if aliases:
1830 parser1_kwargs['aliases'] = ['1alias1', '1alias2']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001831 parser1 = subparsers.add_parser('1', **parser1_kwargs)
1832 parser1.add_argument('-w', type=int, help='w help')
1833 parser1.add_argument('x', choices='abc', help='x help')
1834
1835 # add second sub-parser
1836 parser2_kwargs = dict(description='2 description')
1837 if subparser_help:
1838 parser2_kwargs['help'] = '2 help'
1839 parser2 = subparsers.add_parser('2', **parser2_kwargs)
1840 parser2.add_argument('-y', choices='123', help='y help')
1841 parser2.add_argument('z', type=complex, nargs='*', help='z help')
1842
R David Murray00528e82012-07-21 22:48:35 -04001843 # add third sub-parser
1844 parser3_kwargs = dict(description='3 description')
1845 if subparser_help:
1846 parser3_kwargs['help'] = '3 help'
1847 parser3 = subparsers.add_parser('3', **parser3_kwargs)
1848 parser3.add_argument('t', type=int, help='t help')
1849 parser3.add_argument('u', nargs='...', help='u help')
1850
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001851 # return the main parser
1852 return parser
1853
1854 def setUp(self):
Steven Bethard1f1c2472010-11-01 13:56:09 +00001855 super().setUp()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001856 self.parser = self._get_parser()
1857 self.command_help_parser = self._get_parser(subparser_help=True)
1858
1859 def test_parse_args_failures(self):
1860 # check some failure cases:
1861 for args_str in ['', 'a', 'a a', '0.5 a', '0.5 1',
1862 '0.5 1 -y', '0.5 2 -w']:
1863 args = args_str.split()
1864 self.assertArgumentParserError(self.parser.parse_args, args)
1865
1866 def test_parse_args(self):
1867 # check some non-failure cases:
1868 self.assertEqual(
1869 self.parser.parse_args('0.5 1 b -w 7'.split()),
1870 NS(foo=False, bar=0.5, w=7, x='b'),
1871 )
1872 self.assertEqual(
1873 self.parser.parse_args('0.25 --foo 2 -y 2 3j -- -1j'.split()),
1874 NS(foo=True, bar=0.25, y='2', z=[3j, -1j]),
1875 )
1876 self.assertEqual(
1877 self.parser.parse_args('--foo 0.125 1 c'.split()),
1878 NS(foo=True, bar=0.125, w=None, x='c'),
1879 )
R David Murray00528e82012-07-21 22:48:35 -04001880 self.assertEqual(
1881 self.parser.parse_args('-1.5 3 11 -- a --foo 7 -- b'.split()),
1882 NS(foo=False, bar=-1.5, t=11, u=['a', '--foo', '7', '--', 'b']),
1883 )
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001884
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001885 def test_parse_known_args(self):
1886 self.assertEqual(
1887 self.parser.parse_known_args('0.5 1 b -w 7'.split()),
1888 (NS(foo=False, bar=0.5, w=7, x='b'), []),
1889 )
1890 self.assertEqual(
1891 self.parser.parse_known_args('0.5 -p 1 b -w 7'.split()),
1892 (NS(foo=False, bar=0.5, w=7, x='b'), ['-p']),
1893 )
1894 self.assertEqual(
1895 self.parser.parse_known_args('0.5 1 b -w 7 -p'.split()),
1896 (NS(foo=False, bar=0.5, w=7, x='b'), ['-p']),
1897 )
1898 self.assertEqual(
1899 self.parser.parse_known_args('0.5 1 b -q -rs -w 7'.split()),
1900 (NS(foo=False, bar=0.5, w=7, x='b'), ['-q', '-rs']),
1901 )
1902 self.assertEqual(
1903 self.parser.parse_known_args('0.5 -W 1 b -X Y -w 7 Z'.split()),
1904 (NS(foo=False, bar=0.5, w=7, x='b'), ['-W', '-X', 'Y', 'Z']),
1905 )
1906
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001907 def test_dest(self):
1908 parser = ErrorRaisingArgumentParser()
1909 parser.add_argument('--foo', action='store_true')
1910 subparsers = parser.add_subparsers(dest='bar')
1911 parser1 = subparsers.add_parser('1')
1912 parser1.add_argument('baz')
1913 self.assertEqual(NS(foo=False, bar='1', baz='2'),
1914 parser.parse_args('1 2'.split()))
1915
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001916 def _test_required_subparsers(self, parser):
1917 # Should parse the sub command
1918 ret = parser.parse_args(['run'])
1919 self.assertEqual(ret.command, 'run')
1920
1921 # Error when the command is missing
1922 self.assertArgumentParserError(parser.parse_args, ())
1923
1924 def test_required_subparsers_via_attribute(self):
1925 parser = ErrorRaisingArgumentParser()
1926 subparsers = parser.add_subparsers(dest='command')
1927 subparsers.required = True
1928 subparsers.add_parser('run')
1929 self._test_required_subparsers(parser)
1930
1931 def test_required_subparsers_via_kwarg(self):
1932 parser = ErrorRaisingArgumentParser()
1933 subparsers = parser.add_subparsers(dest='command', required=True)
1934 subparsers.add_parser('run')
1935 self._test_required_subparsers(parser)
1936
1937 def test_required_subparsers_default(self):
1938 parser = ErrorRaisingArgumentParser()
1939 subparsers = parser.add_subparsers(dest='command')
1940 subparsers.add_parser('run')
Ned Deily8ebf5ce2018-05-23 21:55:15 -04001941 # No error here
1942 ret = parser.parse_args(())
1943 self.assertIsNone(ret.command)
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001944
1945 def test_optional_subparsers(self):
1946 parser = ErrorRaisingArgumentParser()
1947 subparsers = parser.add_subparsers(dest='command', required=False)
1948 subparsers.add_parser('run')
1949 # No error here
1950 ret = parser.parse_args(())
1951 self.assertIsNone(ret.command)
1952
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001953 def test_help(self):
1954 self.assertEqual(self.parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01001955 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001956 self.assertEqual(self.parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01001957 usage: PROG [-h] [--foo] bar {1,2,3} ...
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001958
1959 main description
1960
1961 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01001962 bar bar help
1963 {1,2,3} command help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001964
1965 optional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01001966 -h, --help show this help message and exit
1967 --foo foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001968 '''))
1969
R. David Murray88c49fe2010-08-03 17:56:09 +00001970 def test_help_extra_prefix_chars(self):
1971 # Make sure - is still used for help if it is a non-first prefix char
1972 parser = self._get_parser(prefix_chars='+:-')
1973 self.assertEqual(parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01001974 'usage: PROG [-h] [++foo] bar {1,2,3} ...\n')
R. David Murray88c49fe2010-08-03 17:56:09 +00001975 self.assertEqual(parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01001976 usage: PROG [-h] [++foo] bar {1,2,3} ...
R. David Murray88c49fe2010-08-03 17:56:09 +00001977
1978 main description
1979
1980 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01001981 bar bar help
1982 {1,2,3} command help
R. David Murray88c49fe2010-08-03 17:56:09 +00001983
1984 optional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01001985 -h, --help show this help message and exit
1986 ++foo foo help
R. David Murray88c49fe2010-08-03 17:56:09 +00001987 '''))
1988
Xiang Zhang7fe28ad2017-01-22 14:37:22 +08001989 def test_help_non_breaking_spaces(self):
1990 parser = ErrorRaisingArgumentParser(
1991 prog='PROG', description='main description')
1992 parser.add_argument(
1993 "--non-breaking", action='store_false',
1994 help='help message containing non-breaking spaces shall not '
1995 'wrap\N{NO-BREAK SPACE}at non-breaking spaces')
1996 self.assertEqual(parser.format_help(), textwrap.dedent('''\
1997 usage: PROG [-h] [--non-breaking]
1998
1999 main description
2000
2001 optional arguments:
2002 -h, --help show this help message and exit
2003 --non-breaking help message containing non-breaking spaces shall not
2004 wrap\N{NO-BREAK SPACE}at non-breaking spaces
2005 '''))
R. David Murray88c49fe2010-08-03 17:56:09 +00002006
2007 def test_help_alternate_prefix_chars(self):
2008 parser = self._get_parser(prefix_chars='+:/')
2009 self.assertEqual(parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002010 'usage: PROG [+h] [++foo] bar {1,2,3} ...\n')
R. David Murray88c49fe2010-08-03 17:56:09 +00002011 self.assertEqual(parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002012 usage: PROG [+h] [++foo] bar {1,2,3} ...
R. David Murray88c49fe2010-08-03 17:56:09 +00002013
2014 main description
2015
2016 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002017 bar bar help
2018 {1,2,3} command help
R. David Murray88c49fe2010-08-03 17:56:09 +00002019
2020 optional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002021 +h, ++help show this help message and exit
2022 ++foo foo help
R. David Murray88c49fe2010-08-03 17:56:09 +00002023 '''))
2024
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002025 def test_parser_command_help(self):
2026 self.assertEqual(self.command_help_parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002027 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002028 self.assertEqual(self.command_help_parser.format_help(),
2029 textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002030 usage: PROG [-h] [--foo] bar {1,2,3} ...
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002031
2032 main description
2033
2034 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002035 bar bar help
2036 {1,2,3} command help
2037 1 1 help
2038 2 2 help
2039 3 3 help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002040
2041 optional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002042 -h, --help show this help message and exit
2043 --foo foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002044 '''))
2045
2046 def test_subparser_title_help(self):
2047 parser = ErrorRaisingArgumentParser(prog='PROG',
2048 description='main description')
2049 parser.add_argument('--foo', action='store_true', help='foo help')
2050 parser.add_argument('bar', help='bar help')
2051 subparsers = parser.add_subparsers(title='subcommands',
2052 description='command help',
2053 help='additional text')
2054 parser1 = subparsers.add_parser('1')
2055 parser2 = subparsers.add_parser('2')
2056 self.assertEqual(parser.format_usage(),
2057 'usage: PROG [-h] [--foo] bar {1,2} ...\n')
2058 self.assertEqual(parser.format_help(), textwrap.dedent('''\
2059 usage: PROG [-h] [--foo] bar {1,2} ...
2060
2061 main description
2062
2063 positional arguments:
2064 bar bar help
2065
2066 optional arguments:
2067 -h, --help show this help message and exit
2068 --foo foo help
2069
2070 subcommands:
2071 command help
2072
2073 {1,2} additional text
2074 '''))
2075
2076 def _test_subparser_help(self, args_str, expected_help):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002077 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002078 self.parser.parse_args(args_str.split())
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002079 self.assertEqual(expected_help, cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002080
2081 def test_subparser1_help(self):
2082 self._test_subparser_help('5.0 1 -h', textwrap.dedent('''\
2083 usage: PROG bar 1 [-h] [-w W] {a,b,c}
2084
2085 1 description
2086
2087 positional arguments:
2088 {a,b,c} x help
2089
2090 optional arguments:
2091 -h, --help show this help message and exit
2092 -w W w help
2093 '''))
2094
2095 def test_subparser2_help(self):
2096 self._test_subparser_help('5.0 2 -h', textwrap.dedent('''\
2097 usage: PROG bar 2 [-h] [-y {1,2,3}] [z [z ...]]
2098
2099 2 description
2100
2101 positional arguments:
2102 z z help
2103
2104 optional arguments:
2105 -h, --help show this help message and exit
2106 -y {1,2,3} y help
2107 '''))
2108
Steven Bethardfd311a72010-12-18 11:19:23 +00002109 def test_alias_invocation(self):
2110 parser = self._get_parser(aliases=True)
2111 self.assertEqual(
2112 parser.parse_known_args('0.5 1alias1 b'.split()),
2113 (NS(foo=False, bar=0.5, w=None, x='b'), []),
2114 )
2115 self.assertEqual(
2116 parser.parse_known_args('0.5 1alias2 b'.split()),
2117 (NS(foo=False, bar=0.5, w=None, x='b'), []),
2118 )
2119
2120 def test_error_alias_invocation(self):
2121 parser = self._get_parser(aliases=True)
2122 self.assertArgumentParserError(parser.parse_args,
2123 '0.5 1alias3 b'.split())
2124
2125 def test_alias_help(self):
2126 parser = self._get_parser(aliases=True, subparser_help=True)
2127 self.maxDiff = None
2128 self.assertEqual(parser.format_help(), textwrap.dedent("""\
2129 usage: PROG [-h] [--foo] bar COMMAND ...
2130
2131 main description
2132
2133 positional arguments:
2134 bar bar help
2135
2136 optional arguments:
2137 -h, --help show this help message and exit
2138 --foo foo help
2139
2140 commands:
2141 COMMAND
2142 1 (1alias1, 1alias2)
2143 1 help
2144 2 2 help
R David Murray00528e82012-07-21 22:48:35 -04002145 3 3 help
Steven Bethardfd311a72010-12-18 11:19:23 +00002146 """))
2147
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002148# ============
2149# Groups tests
2150# ============
2151
2152class TestPositionalsGroups(TestCase):
2153 """Tests that order of group positionals matches construction order"""
2154
2155 def test_nongroup_first(self):
2156 parser = ErrorRaisingArgumentParser()
2157 parser.add_argument('foo')
2158 group = parser.add_argument_group('g')
2159 group.add_argument('bar')
2160 parser.add_argument('baz')
2161 expected = NS(foo='1', bar='2', baz='3')
2162 result = parser.parse_args('1 2 3'.split())
2163 self.assertEqual(expected, result)
2164
2165 def test_group_first(self):
2166 parser = ErrorRaisingArgumentParser()
2167 group = parser.add_argument_group('xxx')
2168 group.add_argument('foo')
2169 parser.add_argument('bar')
2170 parser.add_argument('baz')
2171 expected = NS(foo='1', bar='2', baz='3')
2172 result = parser.parse_args('1 2 3'.split())
2173 self.assertEqual(expected, result)
2174
2175 def test_interleaved_groups(self):
2176 parser = ErrorRaisingArgumentParser()
2177 group = parser.add_argument_group('xxx')
2178 parser.add_argument('foo')
2179 group.add_argument('bar')
2180 parser.add_argument('baz')
2181 group = parser.add_argument_group('yyy')
2182 group.add_argument('frell')
2183 expected = NS(foo='1', bar='2', baz='3', frell='4')
2184 result = parser.parse_args('1 2 3 4'.split())
2185 self.assertEqual(expected, result)
2186
2187# ===================
2188# Parent parser tests
2189# ===================
2190
2191class TestParentParsers(TestCase):
2192 """Tests that parsers can be created with parent parsers"""
2193
2194 def assertArgumentParserError(self, *args, **kwargs):
2195 self.assertRaises(ArgumentParserError, *args, **kwargs)
2196
2197 def setUp(self):
Steven Bethard1f1c2472010-11-01 13:56:09 +00002198 super().setUp()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002199 self.wxyz_parent = ErrorRaisingArgumentParser(add_help=False)
2200 self.wxyz_parent.add_argument('--w')
2201 x_group = self.wxyz_parent.add_argument_group('x')
2202 x_group.add_argument('-y')
2203 self.wxyz_parent.add_argument('z')
2204
2205 self.abcd_parent = ErrorRaisingArgumentParser(add_help=False)
2206 self.abcd_parent.add_argument('a')
2207 self.abcd_parent.add_argument('-b')
2208 c_group = self.abcd_parent.add_argument_group('c')
2209 c_group.add_argument('--d')
2210
2211 self.w_parent = ErrorRaisingArgumentParser(add_help=False)
2212 self.w_parent.add_argument('--w')
2213
2214 self.z_parent = ErrorRaisingArgumentParser(add_help=False)
2215 self.z_parent.add_argument('z')
2216
2217 # parents with mutually exclusive groups
2218 self.ab_mutex_parent = ErrorRaisingArgumentParser(add_help=False)
2219 group = self.ab_mutex_parent.add_mutually_exclusive_group()
2220 group.add_argument('-a', action='store_true')
2221 group.add_argument('-b', action='store_true')
2222
2223 self.main_program = os.path.basename(sys.argv[0])
2224
2225 def test_single_parent(self):
2226 parser = ErrorRaisingArgumentParser(parents=[self.wxyz_parent])
2227 self.assertEqual(parser.parse_args('-y 1 2 --w 3'.split()),
2228 NS(w='3', y='1', z='2'))
2229
2230 def test_single_parent_mutex(self):
2231 self._test_mutex_ab(self.ab_mutex_parent.parse_args)
2232 parser = ErrorRaisingArgumentParser(parents=[self.ab_mutex_parent])
2233 self._test_mutex_ab(parser.parse_args)
2234
2235 def test_single_granparent_mutex(self):
2236 parents = [self.ab_mutex_parent]
2237 parser = ErrorRaisingArgumentParser(add_help=False, parents=parents)
2238 parser = ErrorRaisingArgumentParser(parents=[parser])
2239 self._test_mutex_ab(parser.parse_args)
2240
2241 def _test_mutex_ab(self, parse_args):
2242 self.assertEqual(parse_args([]), NS(a=False, b=False))
2243 self.assertEqual(parse_args(['-a']), NS(a=True, b=False))
2244 self.assertEqual(parse_args(['-b']), NS(a=False, b=True))
2245 self.assertArgumentParserError(parse_args, ['-a', '-b'])
2246 self.assertArgumentParserError(parse_args, ['-b', '-a'])
2247 self.assertArgumentParserError(parse_args, ['-c'])
2248 self.assertArgumentParserError(parse_args, ['-a', '-c'])
2249 self.assertArgumentParserError(parse_args, ['-b', '-c'])
2250
2251 def test_multiple_parents(self):
2252 parents = [self.abcd_parent, self.wxyz_parent]
2253 parser = ErrorRaisingArgumentParser(parents=parents)
2254 self.assertEqual(parser.parse_args('--d 1 --w 2 3 4'.split()),
2255 NS(a='3', b=None, d='1', w='2', y=None, z='4'))
2256
2257 def test_multiple_parents_mutex(self):
2258 parents = [self.ab_mutex_parent, self.wxyz_parent]
2259 parser = ErrorRaisingArgumentParser(parents=parents)
2260 self.assertEqual(parser.parse_args('-a --w 2 3'.split()),
2261 NS(a=True, b=False, w='2', y=None, z='3'))
2262 self.assertArgumentParserError(
2263 parser.parse_args, '-a --w 2 3 -b'.split())
2264 self.assertArgumentParserError(
2265 parser.parse_args, '-a -b --w 2 3'.split())
2266
2267 def test_conflicting_parents(self):
2268 self.assertRaises(
2269 argparse.ArgumentError,
2270 argparse.ArgumentParser,
2271 parents=[self.w_parent, self.wxyz_parent])
2272
2273 def test_conflicting_parents_mutex(self):
2274 self.assertRaises(
2275 argparse.ArgumentError,
2276 argparse.ArgumentParser,
2277 parents=[self.abcd_parent, self.ab_mutex_parent])
2278
2279 def test_same_argument_name_parents(self):
2280 parents = [self.wxyz_parent, self.z_parent]
2281 parser = ErrorRaisingArgumentParser(parents=parents)
2282 self.assertEqual(parser.parse_args('1 2'.split()),
2283 NS(w=None, y=None, z='2'))
2284
2285 def test_subparser_parents(self):
2286 parser = ErrorRaisingArgumentParser()
2287 subparsers = parser.add_subparsers()
2288 abcde_parser = subparsers.add_parser('bar', parents=[self.abcd_parent])
2289 abcde_parser.add_argument('e')
2290 self.assertEqual(parser.parse_args('bar -b 1 --d 2 3 4'.split()),
2291 NS(a='3', b='1', d='2', e='4'))
2292
2293 def test_subparser_parents_mutex(self):
2294 parser = ErrorRaisingArgumentParser()
2295 subparsers = parser.add_subparsers()
2296 parents = [self.ab_mutex_parent]
2297 abc_parser = subparsers.add_parser('foo', parents=parents)
2298 c_group = abc_parser.add_argument_group('c_group')
2299 c_group.add_argument('c')
2300 parents = [self.wxyz_parent, self.ab_mutex_parent]
2301 wxyzabe_parser = subparsers.add_parser('bar', parents=parents)
2302 wxyzabe_parser.add_argument('e')
2303 self.assertEqual(parser.parse_args('foo -a 4'.split()),
2304 NS(a=True, b=False, c='4'))
2305 self.assertEqual(parser.parse_args('bar -b --w 2 3 4'.split()),
2306 NS(a=False, b=True, w='2', y=None, z='3', e='4'))
2307 self.assertArgumentParserError(
2308 parser.parse_args, 'foo -a -b 4'.split())
2309 self.assertArgumentParserError(
2310 parser.parse_args, 'bar -b -a 4'.split())
2311
2312 def test_parent_help(self):
2313 parents = [self.abcd_parent, self.wxyz_parent]
2314 parser = ErrorRaisingArgumentParser(parents=parents)
2315 parser_help = parser.format_help()
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002316 progname = self.main_program
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002317 self.assertEqual(parser_help, textwrap.dedent('''\
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002318 usage: {}{}[-h] [-b B] [--d D] [--w W] [-y Y] a z
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002319
2320 positional arguments:
2321 a
2322 z
2323
2324 optional arguments:
2325 -h, --help show this help message and exit
2326 -b B
2327 --w W
2328
2329 c:
2330 --d D
2331
2332 x:
2333 -y Y
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002334 '''.format(progname, ' ' if progname else '' )))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002335
2336 def test_groups_parents(self):
2337 parent = ErrorRaisingArgumentParser(add_help=False)
2338 g = parent.add_argument_group(title='g', description='gd')
2339 g.add_argument('-w')
2340 g.add_argument('-x')
2341 m = parent.add_mutually_exclusive_group()
2342 m.add_argument('-y')
2343 m.add_argument('-z')
2344 parser = ErrorRaisingArgumentParser(parents=[parent])
2345
2346 self.assertRaises(ArgumentParserError, parser.parse_args,
2347 ['-y', 'Y', '-z', 'Z'])
2348
2349 parser_help = parser.format_help()
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002350 progname = self.main_program
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002351 self.assertEqual(parser_help, textwrap.dedent('''\
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002352 usage: {}{}[-h] [-w W] [-x X] [-y Y | -z Z]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002353
2354 optional arguments:
2355 -h, --help show this help message and exit
2356 -y Y
2357 -z Z
2358
2359 g:
2360 gd
2361
2362 -w W
2363 -x X
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002364 '''.format(progname, ' ' if progname else '' )))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002365
2366# ==============================
2367# Mutually exclusive group tests
2368# ==============================
2369
2370class TestMutuallyExclusiveGroupErrors(TestCase):
2371
2372 def test_invalid_add_argument_group(self):
2373 parser = ErrorRaisingArgumentParser()
2374 raises = self.assertRaises
2375 raises(TypeError, parser.add_mutually_exclusive_group, title='foo')
2376
2377 def test_invalid_add_argument(self):
2378 parser = ErrorRaisingArgumentParser()
2379 group = parser.add_mutually_exclusive_group()
2380 add_argument = group.add_argument
2381 raises = self.assertRaises
2382 raises(ValueError, add_argument, '--foo', required=True)
2383 raises(ValueError, add_argument, 'bar')
2384 raises(ValueError, add_argument, 'bar', nargs='+')
2385 raises(ValueError, add_argument, 'bar', nargs=1)
2386 raises(ValueError, add_argument, 'bar', nargs=argparse.PARSER)
2387
Steven Bethard49998ee2010-11-01 16:29:26 +00002388 def test_help(self):
2389 parser = ErrorRaisingArgumentParser(prog='PROG')
2390 group1 = parser.add_mutually_exclusive_group()
2391 group1.add_argument('--foo', action='store_true')
2392 group1.add_argument('--bar', action='store_false')
2393 group2 = parser.add_mutually_exclusive_group()
2394 group2.add_argument('--soup', action='store_true')
2395 group2.add_argument('--nuts', action='store_false')
2396 expected = '''\
2397 usage: PROG [-h] [--foo | --bar] [--soup | --nuts]
2398
2399 optional arguments:
2400 -h, --help show this help message and exit
2401 --foo
2402 --bar
2403 --soup
2404 --nuts
2405 '''
2406 self.assertEqual(parser.format_help(), textwrap.dedent(expected))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002407
2408class MEMixin(object):
2409
2410 def test_failures_when_not_required(self):
2411 parse_args = self.get_parser(required=False).parse_args
2412 error = ArgumentParserError
2413 for args_string in self.failures:
2414 self.assertRaises(error, parse_args, args_string.split())
2415
2416 def test_failures_when_required(self):
2417 parse_args = self.get_parser(required=True).parse_args
2418 error = ArgumentParserError
2419 for args_string in self.failures + ['']:
2420 self.assertRaises(error, parse_args, args_string.split())
2421
2422 def test_successes_when_not_required(self):
2423 parse_args = self.get_parser(required=False).parse_args
2424 successes = self.successes + self.successes_when_not_required
2425 for args_string, expected_ns in successes:
2426 actual_ns = parse_args(args_string.split())
2427 self.assertEqual(actual_ns, expected_ns)
2428
2429 def test_successes_when_required(self):
2430 parse_args = self.get_parser(required=True).parse_args
2431 for args_string, expected_ns in self.successes:
2432 actual_ns = parse_args(args_string.split())
2433 self.assertEqual(actual_ns, expected_ns)
2434
2435 def test_usage_when_not_required(self):
2436 format_usage = self.get_parser(required=False).format_usage
2437 expected_usage = self.usage_when_not_required
2438 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))
2439
2440 def test_usage_when_required(self):
2441 format_usage = self.get_parser(required=True).format_usage
2442 expected_usage = self.usage_when_required
2443 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))
2444
2445 def test_help_when_not_required(self):
2446 format_help = self.get_parser(required=False).format_help
2447 help = self.usage_when_not_required + self.help
2448 self.assertEqual(format_help(), textwrap.dedent(help))
2449
2450 def test_help_when_required(self):
2451 format_help = self.get_parser(required=True).format_help
2452 help = self.usage_when_required + self.help
2453 self.assertEqual(format_help(), textwrap.dedent(help))
2454
2455
2456class TestMutuallyExclusiveSimple(MEMixin, TestCase):
2457
2458 def get_parser(self, required=None):
2459 parser = ErrorRaisingArgumentParser(prog='PROG')
2460 group = parser.add_mutually_exclusive_group(required=required)
2461 group.add_argument('--bar', help='bar help')
2462 group.add_argument('--baz', nargs='?', const='Z', help='baz help')
2463 return parser
2464
2465 failures = ['--bar X --baz Y', '--bar X --baz']
2466 successes = [
2467 ('--bar X', NS(bar='X', baz=None)),
2468 ('--bar X --bar Z', NS(bar='Z', baz=None)),
2469 ('--baz Y', NS(bar=None, baz='Y')),
2470 ('--baz', NS(bar=None, baz='Z')),
2471 ]
2472 successes_when_not_required = [
2473 ('', NS(bar=None, baz=None)),
2474 ]
2475
2476 usage_when_not_required = '''\
2477 usage: PROG [-h] [--bar BAR | --baz [BAZ]]
2478 '''
2479 usage_when_required = '''\
2480 usage: PROG [-h] (--bar BAR | --baz [BAZ])
2481 '''
2482 help = '''\
2483
2484 optional arguments:
2485 -h, --help show this help message and exit
2486 --bar BAR bar help
2487 --baz [BAZ] baz help
2488 '''
2489
2490
2491class TestMutuallyExclusiveLong(MEMixin, TestCase):
2492
2493 def get_parser(self, required=None):
2494 parser = ErrorRaisingArgumentParser(prog='PROG')
2495 parser.add_argument('--abcde', help='abcde help')
2496 parser.add_argument('--fghij', help='fghij help')
2497 group = parser.add_mutually_exclusive_group(required=required)
2498 group.add_argument('--klmno', help='klmno help')
2499 group.add_argument('--pqrst', help='pqrst help')
2500 return parser
2501
2502 failures = ['--klmno X --pqrst Y']
2503 successes = [
2504 ('--klmno X', NS(abcde=None, fghij=None, klmno='X', pqrst=None)),
2505 ('--abcde Y --klmno X',
2506 NS(abcde='Y', fghij=None, klmno='X', pqrst=None)),
2507 ('--pqrst X', NS(abcde=None, fghij=None, klmno=None, pqrst='X')),
2508 ('--pqrst X --fghij Y',
2509 NS(abcde=None, fghij='Y', klmno=None, pqrst='X')),
2510 ]
2511 successes_when_not_required = [
2512 ('', NS(abcde=None, fghij=None, klmno=None, pqrst=None)),
2513 ]
2514
2515 usage_when_not_required = '''\
2516 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]
2517 [--klmno KLMNO | --pqrst PQRST]
2518 '''
2519 usage_when_required = '''\
2520 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]
2521 (--klmno KLMNO | --pqrst PQRST)
2522 '''
2523 help = '''\
2524
2525 optional arguments:
2526 -h, --help show this help message and exit
2527 --abcde ABCDE abcde help
2528 --fghij FGHIJ fghij help
2529 --klmno KLMNO klmno help
2530 --pqrst PQRST pqrst help
2531 '''
2532
2533
2534class TestMutuallyExclusiveFirstSuppressed(MEMixin, TestCase):
2535
2536 def get_parser(self, required):
2537 parser = ErrorRaisingArgumentParser(prog='PROG')
2538 group = parser.add_mutually_exclusive_group(required=required)
2539 group.add_argument('-x', help=argparse.SUPPRESS)
2540 group.add_argument('-y', action='store_false', help='y help')
2541 return parser
2542
2543 failures = ['-x X -y']
2544 successes = [
2545 ('-x X', NS(x='X', y=True)),
2546 ('-x X -x Y', NS(x='Y', y=True)),
2547 ('-y', NS(x=None, y=False)),
2548 ]
2549 successes_when_not_required = [
2550 ('', NS(x=None, y=True)),
2551 ]
2552
2553 usage_when_not_required = '''\
2554 usage: PROG [-h] [-y]
2555 '''
2556 usage_when_required = '''\
2557 usage: PROG [-h] -y
2558 '''
2559 help = '''\
2560
2561 optional arguments:
2562 -h, --help show this help message and exit
2563 -y y help
2564 '''
2565
2566
2567class TestMutuallyExclusiveManySuppressed(MEMixin, TestCase):
2568
2569 def get_parser(self, required):
2570 parser = ErrorRaisingArgumentParser(prog='PROG')
2571 group = parser.add_mutually_exclusive_group(required=required)
2572 add = group.add_argument
2573 add('--spam', action='store_true', help=argparse.SUPPRESS)
2574 add('--badger', action='store_false', help=argparse.SUPPRESS)
2575 add('--bladder', help=argparse.SUPPRESS)
2576 return parser
2577
2578 failures = [
2579 '--spam --badger',
2580 '--badger --bladder B',
2581 '--bladder B --spam',
2582 ]
2583 successes = [
2584 ('--spam', NS(spam=True, badger=True, bladder=None)),
2585 ('--badger', NS(spam=False, badger=False, bladder=None)),
2586 ('--bladder B', NS(spam=False, badger=True, bladder='B')),
2587 ('--spam --spam', NS(spam=True, badger=True, bladder=None)),
2588 ]
2589 successes_when_not_required = [
2590 ('', NS(spam=False, badger=True, bladder=None)),
2591 ]
2592
2593 usage_when_required = usage_when_not_required = '''\
2594 usage: PROG [-h]
2595 '''
2596 help = '''\
2597
2598 optional arguments:
2599 -h, --help show this help message and exit
2600 '''
2601
2602
2603class TestMutuallyExclusiveOptionalAndPositional(MEMixin, TestCase):
2604
2605 def get_parser(self, required):
2606 parser = ErrorRaisingArgumentParser(prog='PROG')
2607 group = parser.add_mutually_exclusive_group(required=required)
2608 group.add_argument('--foo', action='store_true', help='FOO')
2609 group.add_argument('--spam', help='SPAM')
2610 group.add_argument('badger', nargs='*', default='X', help='BADGER')
2611 return parser
2612
2613 failures = [
2614 '--foo --spam S',
2615 '--spam S X',
2616 'X --foo',
2617 'X Y Z --spam S',
2618 '--foo X Y',
2619 ]
2620 successes = [
2621 ('--foo', NS(foo=True, spam=None, badger='X')),
2622 ('--spam S', NS(foo=False, spam='S', badger='X')),
2623 ('X', NS(foo=False, spam=None, badger=['X'])),
2624 ('X Y Z', NS(foo=False, spam=None, badger=['X', 'Y', 'Z'])),
2625 ]
2626 successes_when_not_required = [
2627 ('', NS(foo=False, spam=None, badger='X')),
2628 ]
2629
2630 usage_when_not_required = '''\
2631 usage: PROG [-h] [--foo | --spam SPAM | badger [badger ...]]
2632 '''
2633 usage_when_required = '''\
2634 usage: PROG [-h] (--foo | --spam SPAM | badger [badger ...])
2635 '''
2636 help = '''\
2637
2638 positional arguments:
2639 badger BADGER
2640
2641 optional arguments:
2642 -h, --help show this help message and exit
2643 --foo FOO
2644 --spam SPAM SPAM
2645 '''
2646
2647
2648class TestMutuallyExclusiveOptionalsMixed(MEMixin, TestCase):
2649
2650 def get_parser(self, required):
2651 parser = ErrorRaisingArgumentParser(prog='PROG')
2652 parser.add_argument('-x', action='store_true', help='x help')
2653 group = parser.add_mutually_exclusive_group(required=required)
2654 group.add_argument('-a', action='store_true', help='a help')
2655 group.add_argument('-b', action='store_true', help='b help')
2656 parser.add_argument('-y', action='store_true', help='y help')
2657 group.add_argument('-c', action='store_true', help='c help')
2658 return parser
2659
2660 failures = ['-a -b', '-b -c', '-a -c', '-a -b -c']
2661 successes = [
2662 ('-a', NS(a=True, b=False, c=False, x=False, y=False)),
2663 ('-b', NS(a=False, b=True, c=False, x=False, y=False)),
2664 ('-c', NS(a=False, b=False, c=True, x=False, y=False)),
2665 ('-a -x', NS(a=True, b=False, c=False, x=True, y=False)),
2666 ('-y -b', NS(a=False, b=True, c=False, x=False, y=True)),
2667 ('-x -y -c', NS(a=False, b=False, c=True, x=True, y=True)),
2668 ]
2669 successes_when_not_required = [
2670 ('', NS(a=False, b=False, c=False, x=False, y=False)),
2671 ('-x', NS(a=False, b=False, c=False, x=True, y=False)),
2672 ('-y', NS(a=False, b=False, c=False, x=False, y=True)),
2673 ]
2674
2675 usage_when_required = usage_when_not_required = '''\
2676 usage: PROG [-h] [-x] [-a] [-b] [-y] [-c]
2677 '''
2678 help = '''\
2679
2680 optional arguments:
2681 -h, --help show this help message and exit
2682 -x x help
2683 -a a help
2684 -b b help
2685 -y y help
2686 -c c help
2687 '''
2688
2689
Georg Brandl0f6b47a2011-01-30 12:19:35 +00002690class TestMutuallyExclusiveInGroup(MEMixin, TestCase):
2691
2692 def get_parser(self, required=None):
2693 parser = ErrorRaisingArgumentParser(prog='PROG')
2694 titled_group = parser.add_argument_group(
2695 title='Titled group', description='Group description')
2696 mutex_group = \
2697 titled_group.add_mutually_exclusive_group(required=required)
2698 mutex_group.add_argument('--bar', help='bar help')
2699 mutex_group.add_argument('--baz', help='baz help')
2700 return parser
2701
2702 failures = ['--bar X --baz Y', '--baz X --bar Y']
2703 successes = [
2704 ('--bar X', NS(bar='X', baz=None)),
2705 ('--baz Y', NS(bar=None, baz='Y')),
2706 ]
2707 successes_when_not_required = [
2708 ('', NS(bar=None, baz=None)),
2709 ]
2710
2711 usage_when_not_required = '''\
2712 usage: PROG [-h] [--bar BAR | --baz BAZ]
2713 '''
2714 usage_when_required = '''\
2715 usage: PROG [-h] (--bar BAR | --baz BAZ)
2716 '''
2717 help = '''\
2718
2719 optional arguments:
2720 -h, --help show this help message and exit
2721
2722 Titled group:
2723 Group description
2724
2725 --bar BAR bar help
2726 --baz BAZ baz help
2727 '''
2728
2729
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002730class TestMutuallyExclusiveOptionalsAndPositionalsMixed(MEMixin, TestCase):
2731
2732 def get_parser(self, required):
2733 parser = ErrorRaisingArgumentParser(prog='PROG')
2734 parser.add_argument('x', help='x help')
2735 parser.add_argument('-y', action='store_true', help='y help')
2736 group = parser.add_mutually_exclusive_group(required=required)
2737 group.add_argument('a', nargs='?', help='a help')
2738 group.add_argument('-b', action='store_true', help='b help')
2739 group.add_argument('-c', action='store_true', help='c help')
2740 return parser
2741
2742 failures = ['X A -b', '-b -c', '-c X A']
2743 successes = [
2744 ('X A', NS(a='A', b=False, c=False, x='X', y=False)),
2745 ('X -b', NS(a=None, b=True, c=False, x='X', y=False)),
2746 ('X -c', NS(a=None, b=False, c=True, x='X', y=False)),
2747 ('X A -y', NS(a='A', b=False, c=False, x='X', y=True)),
2748 ('X -y -b', NS(a=None, b=True, c=False, x='X', y=True)),
2749 ]
2750 successes_when_not_required = [
2751 ('X', NS(a=None, b=False, c=False, x='X', y=False)),
2752 ('X -y', NS(a=None, b=False, c=False, x='X', y=True)),
2753 ]
2754
2755 usage_when_required = usage_when_not_required = '''\
2756 usage: PROG [-h] [-y] [-b] [-c] x [a]
2757 '''
2758 help = '''\
2759
2760 positional arguments:
2761 x x help
2762 a a help
2763
2764 optional arguments:
2765 -h, --help show this help message and exit
2766 -y y help
2767 -b b help
2768 -c c help
2769 '''
2770
2771# =================================================
2772# Mutually exclusive group in parent parser tests
2773# =================================================
2774
2775class MEPBase(object):
2776
2777 def get_parser(self, required=None):
2778 parent = super(MEPBase, self).get_parser(required=required)
2779 parser = ErrorRaisingArgumentParser(
2780 prog=parent.prog, add_help=False, parents=[parent])
2781 return parser
2782
2783
2784class TestMutuallyExclusiveGroupErrorsParent(
2785 MEPBase, TestMutuallyExclusiveGroupErrors):
2786 pass
2787
2788
2789class TestMutuallyExclusiveSimpleParent(
2790 MEPBase, TestMutuallyExclusiveSimple):
2791 pass
2792
2793
2794class TestMutuallyExclusiveLongParent(
2795 MEPBase, TestMutuallyExclusiveLong):
2796 pass
2797
2798
2799class TestMutuallyExclusiveFirstSuppressedParent(
2800 MEPBase, TestMutuallyExclusiveFirstSuppressed):
2801 pass
2802
2803
2804class TestMutuallyExclusiveManySuppressedParent(
2805 MEPBase, TestMutuallyExclusiveManySuppressed):
2806 pass
2807
2808
2809class TestMutuallyExclusiveOptionalAndPositionalParent(
2810 MEPBase, TestMutuallyExclusiveOptionalAndPositional):
2811 pass
2812
2813
2814class TestMutuallyExclusiveOptionalsMixedParent(
2815 MEPBase, TestMutuallyExclusiveOptionalsMixed):
2816 pass
2817
2818
2819class TestMutuallyExclusiveOptionalsAndPositionalsMixedParent(
2820 MEPBase, TestMutuallyExclusiveOptionalsAndPositionalsMixed):
2821 pass
2822
2823# =================
2824# Set default tests
2825# =================
2826
2827class TestSetDefaults(TestCase):
2828
2829 def test_set_defaults_no_args(self):
2830 parser = ErrorRaisingArgumentParser()
2831 parser.set_defaults(x='foo')
2832 parser.set_defaults(y='bar', z=1)
2833 self.assertEqual(NS(x='foo', y='bar', z=1),
2834 parser.parse_args([]))
2835 self.assertEqual(NS(x='foo', y='bar', z=1),
2836 parser.parse_args([], NS()))
2837 self.assertEqual(NS(x='baz', y='bar', z=1),
2838 parser.parse_args([], NS(x='baz')))
2839 self.assertEqual(NS(x='baz', y='bar', z=2),
2840 parser.parse_args([], NS(x='baz', z=2)))
2841
2842 def test_set_defaults_with_args(self):
2843 parser = ErrorRaisingArgumentParser()
2844 parser.set_defaults(x='foo', y='bar')
2845 parser.add_argument('-x', default='xfoox')
2846 self.assertEqual(NS(x='xfoox', y='bar'),
2847 parser.parse_args([]))
2848 self.assertEqual(NS(x='xfoox', y='bar'),
2849 parser.parse_args([], NS()))
2850 self.assertEqual(NS(x='baz', y='bar'),
2851 parser.parse_args([], NS(x='baz')))
2852 self.assertEqual(NS(x='1', y='bar'),
2853 parser.parse_args('-x 1'.split()))
2854 self.assertEqual(NS(x='1', y='bar'),
2855 parser.parse_args('-x 1'.split(), NS()))
2856 self.assertEqual(NS(x='1', y='bar'),
2857 parser.parse_args('-x 1'.split(), NS(x='baz')))
2858
2859 def test_set_defaults_subparsers(self):
2860 parser = ErrorRaisingArgumentParser()
2861 parser.set_defaults(x='foo')
2862 subparsers = parser.add_subparsers()
2863 parser_a = subparsers.add_parser('a')
2864 parser_a.set_defaults(y='bar')
2865 self.assertEqual(NS(x='foo', y='bar'),
2866 parser.parse_args('a'.split()))
2867
2868 def test_set_defaults_parents(self):
2869 parent = ErrorRaisingArgumentParser(add_help=False)
2870 parent.set_defaults(x='foo')
2871 parser = ErrorRaisingArgumentParser(parents=[parent])
2872 self.assertEqual(NS(x='foo'), parser.parse_args([]))
2873
R David Murray7570cbd2014-10-17 19:55:11 -04002874 def test_set_defaults_on_parent_and_subparser(self):
2875 parser = argparse.ArgumentParser()
2876 xparser = parser.add_subparsers().add_parser('X')
2877 parser.set_defaults(foo=1)
2878 xparser.set_defaults(foo=2)
2879 self.assertEqual(NS(foo=2), parser.parse_args(['X']))
2880
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002881 def test_set_defaults_same_as_add_argument(self):
2882 parser = ErrorRaisingArgumentParser()
2883 parser.set_defaults(w='W', x='X', y='Y', z='Z')
2884 parser.add_argument('-w')
2885 parser.add_argument('-x', default='XX')
2886 parser.add_argument('y', nargs='?')
2887 parser.add_argument('z', nargs='?', default='ZZ')
2888
2889 # defaults set previously
2890 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
2891 parser.parse_args([]))
2892
2893 # reset defaults
2894 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
2895 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
2896 parser.parse_args([]))
2897
2898 def test_set_defaults_same_as_add_argument_group(self):
2899 parser = ErrorRaisingArgumentParser()
2900 parser.set_defaults(w='W', x='X', y='Y', z='Z')
2901 group = parser.add_argument_group('foo')
2902 group.add_argument('-w')
2903 group.add_argument('-x', default='XX')
2904 group.add_argument('y', nargs='?')
2905 group.add_argument('z', nargs='?', default='ZZ')
2906
2907
2908 # defaults set previously
2909 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
2910 parser.parse_args([]))
2911
2912 # reset defaults
2913 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
2914 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
2915 parser.parse_args([]))
2916
2917# =================
2918# Get default tests
2919# =================
2920
2921class TestGetDefault(TestCase):
2922
2923 def test_get_default(self):
2924 parser = ErrorRaisingArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002925 self.assertIsNone(parser.get_default("foo"))
2926 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002927
2928 parser.add_argument("--foo")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002929 self.assertIsNone(parser.get_default("foo"))
2930 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002931
2932 parser.add_argument("--bar", type=int, default=42)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002933 self.assertIsNone(parser.get_default("foo"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002934 self.assertEqual(42, parser.get_default("bar"))
2935
2936 parser.set_defaults(foo="badger")
2937 self.assertEqual("badger", parser.get_default("foo"))
2938 self.assertEqual(42, parser.get_default("bar"))
2939
2940# ==========================
2941# Namespace 'contains' tests
2942# ==========================
2943
2944class TestNamespaceContainsSimple(TestCase):
2945
2946 def test_empty(self):
2947 ns = argparse.Namespace()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002948 self.assertNotIn('', ns)
2949 self.assertNotIn('x', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002950
2951 def test_non_empty(self):
2952 ns = argparse.Namespace(x=1, y=2)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002953 self.assertNotIn('', ns)
2954 self.assertIn('x', ns)
2955 self.assertIn('y', ns)
2956 self.assertNotIn('xx', ns)
2957 self.assertNotIn('z', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002958
2959# =====================
2960# Help formatting tests
2961# =====================
2962
2963class TestHelpFormattingMetaclass(type):
2964
2965 def __init__(cls, name, bases, bodydict):
2966 if name == 'HelpTestCase':
2967 return
2968
2969 class AddTests(object):
2970
2971 def __init__(self, test_class, func_suffix, std_name):
2972 self.func_suffix = func_suffix
2973 self.std_name = std_name
2974
2975 for test_func in [self.test_format,
2976 self.test_print,
2977 self.test_print_file]:
2978 test_name = '%s_%s' % (test_func.__name__, func_suffix)
2979
2980 def test_wrapper(self, test_func=test_func):
2981 test_func(self)
2982 try:
2983 test_wrapper.__name__ = test_name
2984 except TypeError:
2985 pass
2986 setattr(test_class, test_name, test_wrapper)
2987
2988 def _get_parser(self, tester):
2989 parser = argparse.ArgumentParser(
2990 *tester.parser_signature.args,
2991 **tester.parser_signature.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02002992 for argument_sig in getattr(tester, 'argument_signatures', []):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002993 parser.add_argument(*argument_sig.args,
2994 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02002995 group_sigs = getattr(tester, 'argument_group_signatures', [])
2996 for group_sig, argument_sigs in group_sigs:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002997 group = parser.add_argument_group(*group_sig.args,
2998 **group_sig.kwargs)
2999 for argument_sig in argument_sigs:
3000 group.add_argument(*argument_sig.args,
3001 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003002 subparsers_sigs = getattr(tester, 'subparsers_signatures', [])
3003 if subparsers_sigs:
3004 subparsers = parser.add_subparsers()
3005 for subparser_sig in subparsers_sigs:
3006 subparsers.add_parser(*subparser_sig.args,
3007 **subparser_sig.kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003008 return parser
3009
3010 def _test(self, tester, parser_text):
3011 expected_text = getattr(tester, self.func_suffix)
3012 expected_text = textwrap.dedent(expected_text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003013 tester.assertEqual(expected_text, parser_text)
3014
3015 def test_format(self, tester):
3016 parser = self._get_parser(tester)
3017 format = getattr(parser, 'format_%s' % self.func_suffix)
3018 self._test(tester, format())
3019
3020 def test_print(self, tester):
3021 parser = self._get_parser(tester)
3022 print_ = getattr(parser, 'print_%s' % self.func_suffix)
3023 old_stream = getattr(sys, self.std_name)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003024 setattr(sys, self.std_name, StdIOBuffer())
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003025 try:
3026 print_()
3027 parser_text = getattr(sys, self.std_name).getvalue()
3028 finally:
3029 setattr(sys, self.std_name, old_stream)
3030 self._test(tester, parser_text)
3031
3032 def test_print_file(self, tester):
3033 parser = self._get_parser(tester)
3034 print_ = getattr(parser, 'print_%s' % self.func_suffix)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003035 sfile = StdIOBuffer()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003036 print_(sfile)
3037 parser_text = sfile.getvalue()
3038 self._test(tester, parser_text)
3039
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003040 # add tests for {format,print}_{usage,help}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003041 for func_suffix, std_name in [('usage', 'stdout'),
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003042 ('help', 'stdout')]:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003043 AddTests(cls, func_suffix, std_name)
3044
3045bases = TestCase,
3046HelpTestCase = TestHelpFormattingMetaclass('HelpTestCase', bases, {})
3047
3048
3049class TestHelpBiggerOptionals(HelpTestCase):
3050 """Make sure that argument help aligns when options are longer"""
3051
3052 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003053 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003054 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003055 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003056 Sig('-x', action='store_true', help='X HELP'),
3057 Sig('--y', help='Y HELP'),
3058 Sig('foo', help='FOO HELP'),
3059 Sig('bar', help='BAR HELP'),
3060 ]
3061 argument_group_signatures = []
3062 usage = '''\
3063 usage: PROG [-h] [-v] [-x] [--y Y] foo bar
3064 '''
3065 help = usage + '''\
3066
3067 DESCRIPTION
3068
3069 positional arguments:
3070 foo FOO HELP
3071 bar BAR HELP
3072
3073 optional arguments:
3074 -h, --help show this help message and exit
3075 -v, --version show program's version number and exit
3076 -x X HELP
3077 --y Y Y HELP
3078
3079 EPILOG
3080 '''
3081 version = '''\
3082 0.1
3083 '''
3084
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003085class TestShortColumns(HelpTestCase):
3086 '''Test extremely small number of columns.
3087
3088 TestCase prevents "COLUMNS" from being too small in the tests themselves,
Martin Panter2e4571a2015-11-14 01:07:43 +00003089 but we don't want any exceptions thrown in such cases. Only ugly representation.
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003090 '''
3091 def setUp(self):
3092 env = support.EnvironmentVarGuard()
3093 env.set("COLUMNS", '15')
3094 self.addCleanup(env.__exit__)
3095
3096 parser_signature = TestHelpBiggerOptionals.parser_signature
3097 argument_signatures = TestHelpBiggerOptionals.argument_signatures
3098 argument_group_signatures = TestHelpBiggerOptionals.argument_group_signatures
3099 usage = '''\
3100 usage: PROG
3101 [-h]
3102 [-v]
3103 [-x]
3104 [--y Y]
3105 foo
3106 bar
3107 '''
3108 help = usage + '''\
3109
3110 DESCRIPTION
3111
3112 positional arguments:
3113 foo
3114 FOO HELP
3115 bar
3116 BAR HELP
3117
3118 optional arguments:
3119 -h, --help
3120 show this
3121 help
3122 message and
3123 exit
3124 -v, --version
3125 show
3126 program's
3127 version
3128 number and
3129 exit
3130 -x
3131 X HELP
3132 --y Y
3133 Y HELP
3134
3135 EPILOG
3136 '''
3137 version = TestHelpBiggerOptionals.version
3138
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003139
3140class TestHelpBiggerOptionalGroups(HelpTestCase):
3141 """Make sure that argument help aligns when options are longer"""
3142
3143 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003144 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003145 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003146 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003147 Sig('-x', action='store_true', help='X HELP'),
3148 Sig('--y', help='Y HELP'),
3149 Sig('foo', help='FOO HELP'),
3150 Sig('bar', help='BAR HELP'),
3151 ]
3152 argument_group_signatures = [
3153 (Sig('GROUP TITLE', description='GROUP DESCRIPTION'), [
3154 Sig('baz', help='BAZ HELP'),
3155 Sig('-z', nargs='+', help='Z HELP')]),
3156 ]
3157 usage = '''\
3158 usage: PROG [-h] [-v] [-x] [--y Y] [-z Z [Z ...]] foo bar baz
3159 '''
3160 help = usage + '''\
3161
3162 DESCRIPTION
3163
3164 positional arguments:
3165 foo FOO HELP
3166 bar BAR HELP
3167
3168 optional arguments:
3169 -h, --help show this help message and exit
3170 -v, --version show program's version number and exit
3171 -x X HELP
3172 --y Y Y HELP
3173
3174 GROUP TITLE:
3175 GROUP DESCRIPTION
3176
3177 baz BAZ HELP
3178 -z Z [Z ...] Z HELP
3179
3180 EPILOG
3181 '''
3182 version = '''\
3183 0.1
3184 '''
3185
3186
3187class TestHelpBiggerPositionals(HelpTestCase):
3188 """Make sure that help aligns when arguments are longer"""
3189
3190 parser_signature = Sig(usage='USAGE', description='DESCRIPTION')
3191 argument_signatures = [
3192 Sig('-x', action='store_true', help='X HELP'),
3193 Sig('--y', help='Y HELP'),
3194 Sig('ekiekiekifekang', help='EKI HELP'),
3195 Sig('bar', help='BAR HELP'),
3196 ]
3197 argument_group_signatures = []
3198 usage = '''\
3199 usage: USAGE
3200 '''
3201 help = usage + '''\
3202
3203 DESCRIPTION
3204
3205 positional arguments:
3206 ekiekiekifekang EKI HELP
3207 bar BAR HELP
3208
3209 optional arguments:
3210 -h, --help show this help message and exit
3211 -x X HELP
3212 --y Y Y HELP
3213 '''
3214
3215 version = ''
3216
3217
3218class TestHelpReformatting(HelpTestCase):
3219 """Make sure that text after short names starts on the first line"""
3220
3221 parser_signature = Sig(
3222 prog='PROG',
3223 description=' oddly formatted\n'
3224 'description\n'
3225 '\n'
3226 'that is so long that it should go onto multiple '
3227 'lines when wrapped')
3228 argument_signatures = [
3229 Sig('-x', metavar='XX', help='oddly\n'
3230 ' formatted -x help'),
3231 Sig('y', metavar='yyy', help='normal y help'),
3232 ]
3233 argument_group_signatures = [
3234 (Sig('title', description='\n'
3235 ' oddly formatted group\n'
3236 '\n'
3237 'description'),
3238 [Sig('-a', action='store_true',
3239 help=' oddly \n'
3240 'formatted -a help \n'
3241 ' again, so long that it should be wrapped over '
3242 'multiple lines')]),
3243 ]
3244 usage = '''\
3245 usage: PROG [-h] [-x XX] [-a] yyy
3246 '''
3247 help = usage + '''\
3248
3249 oddly formatted description that is so long that it should go onto \
3250multiple
3251 lines when wrapped
3252
3253 positional arguments:
3254 yyy normal y help
3255
3256 optional arguments:
3257 -h, --help show this help message and exit
3258 -x XX oddly formatted -x help
3259
3260 title:
3261 oddly formatted group description
3262
3263 -a oddly formatted -a help again, so long that it should \
3264be wrapped
3265 over multiple lines
3266 '''
3267 version = ''
3268
3269
3270class TestHelpWrappingShortNames(HelpTestCase):
3271 """Make sure that text after short names starts on the first line"""
3272
3273 parser_signature = Sig(prog='PROG', description= 'D\nD' * 30)
3274 argument_signatures = [
3275 Sig('-x', metavar='XX', help='XHH HX' * 20),
3276 Sig('y', metavar='yyy', help='YH YH' * 20),
3277 ]
3278 argument_group_signatures = [
3279 (Sig('ALPHAS'), [
3280 Sig('-a', action='store_true', help='AHHH HHA' * 10)]),
3281 ]
3282 usage = '''\
3283 usage: PROG [-h] [-x XX] [-a] yyy
3284 '''
3285 help = usage + '''\
3286
3287 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3288DD DD DD
3289 DD DD DD DD D
3290
3291 positional arguments:
3292 yyy YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3293YHYH YHYH
3294 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3295
3296 optional arguments:
3297 -h, --help show this help message and exit
3298 -x XX XHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH \
3299HXXHH HXXHH
3300 HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HX
3301
3302 ALPHAS:
3303 -a AHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH \
3304HHAAHHH
3305 HHAAHHH HHAAHHH HHA
3306 '''
3307 version = ''
3308
3309
3310class TestHelpWrappingLongNames(HelpTestCase):
3311 """Make sure that text after long names starts on the next line"""
3312
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003313 parser_signature = Sig(usage='USAGE', description= 'D D' * 30)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003314 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003315 Sig('-v', '--version', action='version', version='V V' * 30),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003316 Sig('-x', metavar='X' * 25, help='XH XH' * 20),
3317 Sig('y', metavar='y' * 25, help='YH YH' * 20),
3318 ]
3319 argument_group_signatures = [
3320 (Sig('ALPHAS'), [
3321 Sig('-a', metavar='A' * 25, help='AH AH' * 20),
3322 Sig('z', metavar='z' * 25, help='ZH ZH' * 20)]),
3323 ]
3324 usage = '''\
3325 usage: USAGE
3326 '''
3327 help = usage + '''\
3328
3329 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3330DD DD DD
3331 DD DD DD DD D
3332
3333 positional arguments:
3334 yyyyyyyyyyyyyyyyyyyyyyyyy
3335 YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3336YHYH YHYH
3337 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3338
3339 optional arguments:
3340 -h, --help show this help message and exit
3341 -v, --version show program's version number and exit
3342 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3343 XH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH \
3344XHXH XHXH
3345 XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XH
3346
3347 ALPHAS:
3348 -a AAAAAAAAAAAAAAAAAAAAAAAAA
3349 AH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH \
3350AHAH AHAH
3351 AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AH
3352 zzzzzzzzzzzzzzzzzzzzzzzzz
3353 ZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH \
3354ZHZH ZHZH
3355 ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZH
3356 '''
3357 version = '''\
3358 V VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV \
3359VV VV VV
3360 VV VV VV VV V
3361 '''
3362
3363
3364class TestHelpUsage(HelpTestCase):
3365 """Test basic usage messages"""
3366
3367 parser_signature = Sig(prog='PROG')
3368 argument_signatures = [
3369 Sig('-w', nargs='+', help='w'),
3370 Sig('-x', nargs='*', help='x'),
3371 Sig('a', help='a'),
3372 Sig('b', help='b', nargs=2),
3373 Sig('c', help='c', nargs='?'),
3374 ]
3375 argument_group_signatures = [
3376 (Sig('group'), [
3377 Sig('-y', nargs='?', help='y'),
3378 Sig('-z', nargs=3, help='z'),
3379 Sig('d', help='d', nargs='*'),
3380 Sig('e', help='e', nargs='+'),
3381 ])
3382 ]
3383 usage = '''\
3384 usage: PROG [-h] [-w W [W ...]] [-x [X [X ...]]] [-y [Y]] [-z Z Z Z]
3385 a b b [c] [d [d ...]] e [e ...]
3386 '''
3387 help = usage + '''\
3388
3389 positional arguments:
3390 a a
3391 b b
3392 c c
3393
3394 optional arguments:
3395 -h, --help show this help message and exit
3396 -w W [W ...] w
3397 -x [X [X ...]] x
3398
3399 group:
3400 -y [Y] y
3401 -z Z Z Z z
3402 d d
3403 e e
3404 '''
3405 version = ''
3406
3407
3408class TestHelpOnlyUserGroups(HelpTestCase):
3409 """Test basic usage messages"""
3410
3411 parser_signature = Sig(prog='PROG', add_help=False)
3412 argument_signatures = []
3413 argument_group_signatures = [
3414 (Sig('xxxx'), [
3415 Sig('-x', help='x'),
3416 Sig('a', help='a'),
3417 ]),
3418 (Sig('yyyy'), [
3419 Sig('b', help='b'),
3420 Sig('-y', help='y'),
3421 ]),
3422 ]
3423 usage = '''\
3424 usage: PROG [-x X] [-y Y] a b
3425 '''
3426 help = usage + '''\
3427
3428 xxxx:
3429 -x X x
3430 a a
3431
3432 yyyy:
3433 b b
3434 -y Y y
3435 '''
3436 version = ''
3437
3438
3439class TestHelpUsageLongProg(HelpTestCase):
3440 """Test usage messages where the prog is long"""
3441
3442 parser_signature = Sig(prog='P' * 60)
3443 argument_signatures = [
3444 Sig('-w', metavar='W'),
3445 Sig('-x', metavar='X'),
3446 Sig('a'),
3447 Sig('b'),
3448 ]
3449 argument_group_signatures = []
3450 usage = '''\
3451 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3452 [-h] [-w W] [-x X] a b
3453 '''
3454 help = usage + '''\
3455
3456 positional arguments:
3457 a
3458 b
3459
3460 optional arguments:
3461 -h, --help show this help message and exit
3462 -w W
3463 -x X
3464 '''
3465 version = ''
3466
3467
3468class TestHelpUsageLongProgOptionsWrap(HelpTestCase):
3469 """Test usage messages where the prog is long and the optionals wrap"""
3470
3471 parser_signature = Sig(prog='P' * 60)
3472 argument_signatures = [
3473 Sig('-w', metavar='W' * 25),
3474 Sig('-x', metavar='X' * 25),
3475 Sig('-y', metavar='Y' * 25),
3476 Sig('-z', metavar='Z' * 25),
3477 Sig('a'),
3478 Sig('b'),
3479 ]
3480 argument_group_signatures = []
3481 usage = '''\
3482 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3483 [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3484[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3485 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3486 a b
3487 '''
3488 help = usage + '''\
3489
3490 positional arguments:
3491 a
3492 b
3493
3494 optional arguments:
3495 -h, --help show this help message and exit
3496 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3497 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3498 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3499 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3500 '''
3501 version = ''
3502
3503
3504class TestHelpUsageLongProgPositionalsWrap(HelpTestCase):
3505 """Test usage messages where the prog is long and the positionals wrap"""
3506
3507 parser_signature = Sig(prog='P' * 60, add_help=False)
3508 argument_signatures = [
3509 Sig('a' * 25),
3510 Sig('b' * 25),
3511 Sig('c' * 25),
3512 ]
3513 argument_group_signatures = []
3514 usage = '''\
3515 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3516 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3517 ccccccccccccccccccccccccc
3518 '''
3519 help = usage + '''\
3520
3521 positional arguments:
3522 aaaaaaaaaaaaaaaaaaaaaaaaa
3523 bbbbbbbbbbbbbbbbbbbbbbbbb
3524 ccccccccccccccccccccccccc
3525 '''
3526 version = ''
3527
3528
3529class TestHelpUsageOptionalsWrap(HelpTestCase):
3530 """Test usage messages where the optionals wrap"""
3531
3532 parser_signature = Sig(prog='PROG')
3533 argument_signatures = [
3534 Sig('-w', metavar='W' * 25),
3535 Sig('-x', metavar='X' * 25),
3536 Sig('-y', metavar='Y' * 25),
3537 Sig('-z', metavar='Z' * 25),
3538 Sig('a'),
3539 Sig('b'),
3540 Sig('c'),
3541 ]
3542 argument_group_signatures = []
3543 usage = '''\
3544 usage: PROG [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3545[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3546 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] \
3547[-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3548 a b c
3549 '''
3550 help = usage + '''\
3551
3552 positional arguments:
3553 a
3554 b
3555 c
3556
3557 optional arguments:
3558 -h, --help show this help message and exit
3559 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3560 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3561 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3562 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3563 '''
3564 version = ''
3565
3566
3567class TestHelpUsagePositionalsWrap(HelpTestCase):
3568 """Test usage messages where the positionals wrap"""
3569
3570 parser_signature = Sig(prog='PROG')
3571 argument_signatures = [
3572 Sig('-x'),
3573 Sig('-y'),
3574 Sig('-z'),
3575 Sig('a' * 25),
3576 Sig('b' * 25),
3577 Sig('c' * 25),
3578 ]
3579 argument_group_signatures = []
3580 usage = '''\
3581 usage: PROG [-h] [-x X] [-y Y] [-z Z]
3582 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3583 ccccccccccccccccccccccccc
3584 '''
3585 help = usage + '''\
3586
3587 positional arguments:
3588 aaaaaaaaaaaaaaaaaaaaaaaaa
3589 bbbbbbbbbbbbbbbbbbbbbbbbb
3590 ccccccccccccccccccccccccc
3591
3592 optional arguments:
3593 -h, --help show this help message and exit
3594 -x X
3595 -y Y
3596 -z Z
3597 '''
3598 version = ''
3599
3600
3601class TestHelpUsageOptionalsPositionalsWrap(HelpTestCase):
3602 """Test usage messages where the optionals and positionals wrap"""
3603
3604 parser_signature = Sig(prog='PROG')
3605 argument_signatures = [
3606 Sig('-x', metavar='X' * 25),
3607 Sig('-y', metavar='Y' * 25),
3608 Sig('-z', metavar='Z' * 25),
3609 Sig('a' * 25),
3610 Sig('b' * 25),
3611 Sig('c' * 25),
3612 ]
3613 argument_group_signatures = []
3614 usage = '''\
3615 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3616[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3617 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3618 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3619 ccccccccccccccccccccccccc
3620 '''
3621 help = usage + '''\
3622
3623 positional arguments:
3624 aaaaaaaaaaaaaaaaaaaaaaaaa
3625 bbbbbbbbbbbbbbbbbbbbbbbbb
3626 ccccccccccccccccccccccccc
3627
3628 optional arguments:
3629 -h, --help show this help message and exit
3630 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3631 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3632 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3633 '''
3634 version = ''
3635
3636
3637class TestHelpUsageOptionalsOnlyWrap(HelpTestCase):
3638 """Test usage messages where there are only optionals and they wrap"""
3639
3640 parser_signature = Sig(prog='PROG')
3641 argument_signatures = [
3642 Sig('-x', metavar='X' * 25),
3643 Sig('-y', metavar='Y' * 25),
3644 Sig('-z', metavar='Z' * 25),
3645 ]
3646 argument_group_signatures = []
3647 usage = '''\
3648 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3649[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3650 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3651 '''
3652 help = usage + '''\
3653
3654 optional arguments:
3655 -h, --help show this help message and exit
3656 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3657 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3658 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3659 '''
3660 version = ''
3661
3662
3663class TestHelpUsagePositionalsOnlyWrap(HelpTestCase):
3664 """Test usage messages where there are only positionals and they wrap"""
3665
3666 parser_signature = Sig(prog='PROG', add_help=False)
3667 argument_signatures = [
3668 Sig('a' * 25),
3669 Sig('b' * 25),
3670 Sig('c' * 25),
3671 ]
3672 argument_group_signatures = []
3673 usage = '''\
3674 usage: PROG aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3675 ccccccccccccccccccccccccc
3676 '''
3677 help = usage + '''\
3678
3679 positional arguments:
3680 aaaaaaaaaaaaaaaaaaaaaaaaa
3681 bbbbbbbbbbbbbbbbbbbbbbbbb
3682 ccccccccccccccccccccccccc
3683 '''
3684 version = ''
3685
3686
3687class TestHelpVariableExpansion(HelpTestCase):
3688 """Test that variables are expanded properly in help messages"""
3689
3690 parser_signature = Sig(prog='PROG')
3691 argument_signatures = [
3692 Sig('-x', type=int,
3693 help='x %(prog)s %(default)s %(type)s %%'),
3694 Sig('-y', action='store_const', default=42, const='XXX',
3695 help='y %(prog)s %(default)s %(const)s'),
3696 Sig('--foo', choices='abc',
3697 help='foo %(prog)s %(default)s %(choices)s'),
3698 Sig('--bar', default='baz', choices=[1, 2], metavar='BBB',
3699 help='bar %(prog)s %(default)s %(dest)s'),
3700 Sig('spam', help='spam %(prog)s %(default)s'),
3701 Sig('badger', default=0.5, help='badger %(prog)s %(default)s'),
3702 ]
3703 argument_group_signatures = [
3704 (Sig('group'), [
3705 Sig('-a', help='a %(prog)s %(default)s'),
3706 Sig('-b', default=-1, help='b %(prog)s %(default)s'),
3707 ])
3708 ]
3709 usage = ('''\
3710 usage: PROG [-h] [-x X] [-y] [--foo {a,b,c}] [--bar BBB] [-a A] [-b B]
3711 spam badger
3712 ''')
3713 help = usage + '''\
3714
3715 positional arguments:
3716 spam spam PROG None
3717 badger badger PROG 0.5
3718
3719 optional arguments:
3720 -h, --help show this help message and exit
3721 -x X x PROG None int %
3722 -y y PROG 42 XXX
3723 --foo {a,b,c} foo PROG None a, b, c
3724 --bar BBB bar PROG baz bar
3725
3726 group:
3727 -a A a PROG None
3728 -b B b PROG -1
3729 '''
3730 version = ''
3731
3732
3733class TestHelpVariableExpansionUsageSupplied(HelpTestCase):
3734 """Test that variables are expanded properly when usage= is present"""
3735
3736 parser_signature = Sig(prog='PROG', usage='%(prog)s FOO')
3737 argument_signatures = []
3738 argument_group_signatures = []
3739 usage = ('''\
3740 usage: PROG FOO
3741 ''')
3742 help = usage + '''\
3743
3744 optional arguments:
3745 -h, --help show this help message and exit
3746 '''
3747 version = ''
3748
3749
3750class TestHelpVariableExpansionNoArguments(HelpTestCase):
3751 """Test that variables are expanded properly with no arguments"""
3752
3753 parser_signature = Sig(prog='PROG', add_help=False)
3754 argument_signatures = []
3755 argument_group_signatures = []
3756 usage = ('''\
3757 usage: PROG
3758 ''')
3759 help = usage
3760 version = ''
3761
3762
3763class TestHelpSuppressUsage(HelpTestCase):
3764 """Test that items can be suppressed in usage messages"""
3765
3766 parser_signature = Sig(prog='PROG', usage=argparse.SUPPRESS)
3767 argument_signatures = [
3768 Sig('--foo', help='foo help'),
3769 Sig('spam', help='spam help'),
3770 ]
3771 argument_group_signatures = []
3772 help = '''\
3773 positional arguments:
3774 spam spam help
3775
3776 optional arguments:
3777 -h, --help show this help message and exit
3778 --foo FOO foo help
3779 '''
3780 usage = ''
3781 version = ''
3782
3783
3784class TestHelpSuppressOptional(HelpTestCase):
3785 """Test that optional arguments can be suppressed in help messages"""
3786
3787 parser_signature = Sig(prog='PROG', add_help=False)
3788 argument_signatures = [
3789 Sig('--foo', help=argparse.SUPPRESS),
3790 Sig('spam', help='spam help'),
3791 ]
3792 argument_group_signatures = []
3793 usage = '''\
3794 usage: PROG spam
3795 '''
3796 help = usage + '''\
3797
3798 positional arguments:
3799 spam spam help
3800 '''
3801 version = ''
3802
3803
3804class TestHelpSuppressOptionalGroup(HelpTestCase):
3805 """Test that optional groups can be suppressed in help messages"""
3806
3807 parser_signature = Sig(prog='PROG')
3808 argument_signatures = [
3809 Sig('--foo', help='foo help'),
3810 Sig('spam', help='spam help'),
3811 ]
3812 argument_group_signatures = [
3813 (Sig('group'), [Sig('--bar', help=argparse.SUPPRESS)]),
3814 ]
3815 usage = '''\
3816 usage: PROG [-h] [--foo FOO] spam
3817 '''
3818 help = usage + '''\
3819
3820 positional arguments:
3821 spam spam help
3822
3823 optional arguments:
3824 -h, --help show this help message and exit
3825 --foo FOO foo help
3826 '''
3827 version = ''
3828
3829
3830class TestHelpSuppressPositional(HelpTestCase):
3831 """Test that positional arguments can be suppressed in help messages"""
3832
3833 parser_signature = Sig(prog='PROG')
3834 argument_signatures = [
3835 Sig('--foo', help='foo help'),
3836 Sig('spam', help=argparse.SUPPRESS),
3837 ]
3838 argument_group_signatures = []
3839 usage = '''\
3840 usage: PROG [-h] [--foo FOO]
3841 '''
3842 help = usage + '''\
3843
3844 optional arguments:
3845 -h, --help show this help message and exit
3846 --foo FOO foo help
3847 '''
3848 version = ''
3849
3850
3851class TestHelpRequiredOptional(HelpTestCase):
3852 """Test that required options don't look optional"""
3853
3854 parser_signature = Sig(prog='PROG')
3855 argument_signatures = [
3856 Sig('--foo', required=True, help='foo help'),
3857 ]
3858 argument_group_signatures = []
3859 usage = '''\
3860 usage: PROG [-h] --foo FOO
3861 '''
3862 help = usage + '''\
3863
3864 optional arguments:
3865 -h, --help show this help message and exit
3866 --foo FOO foo help
3867 '''
3868 version = ''
3869
3870
3871class TestHelpAlternatePrefixChars(HelpTestCase):
3872 """Test that options display with different prefix characters"""
3873
3874 parser_signature = Sig(prog='PROG', prefix_chars='^;', add_help=False)
3875 argument_signatures = [
3876 Sig('^^foo', action='store_true', help='foo help'),
3877 Sig(';b', ';;bar', help='bar help'),
3878 ]
3879 argument_group_signatures = []
3880 usage = '''\
3881 usage: PROG [^^foo] [;b BAR]
3882 '''
3883 help = usage + '''\
3884
3885 optional arguments:
3886 ^^foo foo help
3887 ;b BAR, ;;bar BAR bar help
3888 '''
3889 version = ''
3890
3891
3892class TestHelpNoHelpOptional(HelpTestCase):
3893 """Test that the --help argument can be suppressed help messages"""
3894
3895 parser_signature = Sig(prog='PROG', add_help=False)
3896 argument_signatures = [
3897 Sig('--foo', help='foo help'),
3898 Sig('spam', help='spam help'),
3899 ]
3900 argument_group_signatures = []
3901 usage = '''\
3902 usage: PROG [--foo FOO] spam
3903 '''
3904 help = usage + '''\
3905
3906 positional arguments:
3907 spam spam help
3908
3909 optional arguments:
3910 --foo FOO foo help
3911 '''
3912 version = ''
3913
3914
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003915class TestHelpNone(HelpTestCase):
3916 """Test that no errors occur if no help is specified"""
3917
3918 parser_signature = Sig(prog='PROG')
3919 argument_signatures = [
3920 Sig('--foo'),
3921 Sig('spam'),
3922 ]
3923 argument_group_signatures = []
3924 usage = '''\
3925 usage: PROG [-h] [--foo FOO] spam
3926 '''
3927 help = usage + '''\
3928
3929 positional arguments:
3930 spam
3931
3932 optional arguments:
3933 -h, --help show this help message and exit
3934 --foo FOO
3935 '''
3936 version = ''
3937
3938
3939class TestHelpTupleMetavar(HelpTestCase):
3940 """Test specifying metavar as a tuple"""
3941
3942 parser_signature = Sig(prog='PROG')
3943 argument_signatures = [
3944 Sig('-w', help='w', nargs='+', metavar=('W1', 'W2')),
3945 Sig('-x', help='x', nargs='*', metavar=('X1', 'X2')),
3946 Sig('-y', help='y', nargs=3, metavar=('Y1', 'Y2', 'Y3')),
3947 Sig('-z', help='z', nargs='?', metavar=('Z1', )),
3948 ]
3949 argument_group_signatures = []
3950 usage = '''\
3951 usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] \
3952[-z [Z1]]
3953 '''
3954 help = usage + '''\
3955
3956 optional arguments:
3957 -h, --help show this help message and exit
3958 -w W1 [W2 ...] w
3959 -x [X1 [X2 ...]] x
3960 -y Y1 Y2 Y3 y
3961 -z [Z1] z
3962 '''
3963 version = ''
3964
3965
3966class TestHelpRawText(HelpTestCase):
3967 """Test the RawTextHelpFormatter"""
3968
3969 parser_signature = Sig(
3970 prog='PROG', formatter_class=argparse.RawTextHelpFormatter,
3971 description='Keep the formatting\n'
3972 ' exactly as it is written\n'
3973 '\n'
3974 'here\n')
3975
3976 argument_signatures = [
3977 Sig('--foo', help=' foo help should also\n'
3978 'appear as given here'),
3979 Sig('spam', help='spam help'),
3980 ]
3981 argument_group_signatures = [
3982 (Sig('title', description=' This text\n'
3983 ' should be indented\n'
3984 ' exactly like it is here\n'),
3985 [Sig('--bar', help='bar help')]),
3986 ]
3987 usage = '''\
3988 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
3989 '''
3990 help = usage + '''\
3991
3992 Keep the formatting
3993 exactly as it is written
3994
3995 here
3996
3997 positional arguments:
3998 spam spam help
3999
4000 optional arguments:
4001 -h, --help show this help message and exit
4002 --foo FOO foo help should also
4003 appear as given here
4004
4005 title:
4006 This text
4007 should be indented
4008 exactly like it is here
4009
4010 --bar BAR bar help
4011 '''
4012 version = ''
4013
4014
4015class TestHelpRawDescription(HelpTestCase):
4016 """Test the RawTextHelpFormatter"""
4017
4018 parser_signature = Sig(
4019 prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter,
4020 description='Keep the formatting\n'
4021 ' exactly as it is written\n'
4022 '\n'
4023 'here\n')
4024
4025 argument_signatures = [
4026 Sig('--foo', help=' foo help should not\n'
4027 ' retain this odd formatting'),
4028 Sig('spam', help='spam help'),
4029 ]
4030 argument_group_signatures = [
4031 (Sig('title', description=' This text\n'
4032 ' should be indented\n'
4033 ' exactly like it is here\n'),
4034 [Sig('--bar', help='bar help')]),
4035 ]
4036 usage = '''\
4037 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
4038 '''
4039 help = usage + '''\
4040
4041 Keep the formatting
4042 exactly as it is written
4043
4044 here
4045
4046 positional arguments:
4047 spam spam help
4048
4049 optional arguments:
4050 -h, --help show this help message and exit
4051 --foo FOO foo help should not retain this odd formatting
4052
4053 title:
4054 This text
4055 should be indented
4056 exactly like it is here
4057
4058 --bar BAR bar help
4059 '''
4060 version = ''
4061
4062
4063class TestHelpArgumentDefaults(HelpTestCase):
4064 """Test the ArgumentDefaultsHelpFormatter"""
4065
4066 parser_signature = Sig(
4067 prog='PROG', formatter_class=argparse.ArgumentDefaultsHelpFormatter,
4068 description='description')
4069
4070 argument_signatures = [
4071 Sig('--foo', help='foo help - oh and by the way, %(default)s'),
4072 Sig('--bar', action='store_true', help='bar help'),
4073 Sig('spam', help='spam help'),
4074 Sig('badger', nargs='?', default='wooden', help='badger help'),
4075 ]
4076 argument_group_signatures = [
4077 (Sig('title', description='description'),
4078 [Sig('--baz', type=int, default=42, help='baz help')]),
4079 ]
4080 usage = '''\
4081 usage: PROG [-h] [--foo FOO] [--bar] [--baz BAZ] spam [badger]
4082 '''
4083 help = usage + '''\
4084
4085 description
4086
4087 positional arguments:
4088 spam spam help
4089 badger badger help (default: wooden)
4090
4091 optional arguments:
4092 -h, --help show this help message and exit
4093 --foo FOO foo help - oh and by the way, None
4094 --bar bar help (default: False)
4095
4096 title:
4097 description
4098
4099 --baz BAZ baz help (default: 42)
4100 '''
4101 version = ''
4102
Steven Bethard50fe5932010-05-24 03:47:38 +00004103class TestHelpVersionAction(HelpTestCase):
4104 """Test the default help for the version action"""
4105
4106 parser_signature = Sig(prog='PROG', description='description')
4107 argument_signatures = [Sig('-V', '--version', action='version', version='3.6')]
4108 argument_group_signatures = []
4109 usage = '''\
4110 usage: PROG [-h] [-V]
4111 '''
4112 help = usage + '''\
4113
4114 description
4115
4116 optional arguments:
4117 -h, --help show this help message and exit
4118 -V, --version show program's version number and exit
4119 '''
4120 version = ''
4121
Berker Peksagecb75e22015-04-10 16:11:12 +03004122
4123class TestHelpVersionActionSuppress(HelpTestCase):
4124 """Test that the --version argument can be suppressed in help messages"""
4125
4126 parser_signature = Sig(prog='PROG')
4127 argument_signatures = [
4128 Sig('-v', '--version', action='version', version='1.0',
4129 help=argparse.SUPPRESS),
4130 Sig('--foo', help='foo help'),
4131 Sig('spam', help='spam help'),
4132 ]
4133 argument_group_signatures = []
4134 usage = '''\
4135 usage: PROG [-h] [--foo FOO] spam
4136 '''
4137 help = usage + '''\
4138
4139 positional arguments:
4140 spam spam help
4141
4142 optional arguments:
4143 -h, --help show this help message and exit
4144 --foo FOO foo help
4145 '''
4146
4147
Steven Bethard8a6a1982011-03-27 13:53:53 +02004148class TestHelpSubparsersOrdering(HelpTestCase):
4149 """Test ordering of subcommands in help matches the code"""
4150 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004151 description='display some subcommands')
4152 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004153
4154 subparsers_signatures = [Sig(name=name)
4155 for name in ('a', 'b', 'c', 'd', 'e')]
4156
4157 usage = '''\
4158 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4159 '''
4160
4161 help = usage + '''\
4162
4163 display some subcommands
4164
4165 positional arguments:
4166 {a,b,c,d,e}
4167
4168 optional arguments:
4169 -h, --help show this help message and exit
4170 -v, --version show program's version number and exit
4171 '''
4172
4173 version = '''\
4174 0.1
4175 '''
4176
4177class TestHelpSubparsersWithHelpOrdering(HelpTestCase):
4178 """Test ordering of subcommands in help matches the code"""
4179 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004180 description='display some subcommands')
4181 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004182
4183 subcommand_data = (('a', 'a subcommand help'),
4184 ('b', 'b subcommand help'),
4185 ('c', 'c subcommand help'),
4186 ('d', 'd subcommand help'),
4187 ('e', 'e subcommand help'),
4188 )
4189
4190 subparsers_signatures = [Sig(name=name, help=help)
4191 for name, help in subcommand_data]
4192
4193 usage = '''\
4194 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4195 '''
4196
4197 help = usage + '''\
4198
4199 display some subcommands
4200
4201 positional arguments:
4202 {a,b,c,d,e}
4203 a a subcommand help
4204 b b subcommand help
4205 c c subcommand help
4206 d d subcommand help
4207 e e subcommand help
4208
4209 optional arguments:
4210 -h, --help show this help message and exit
4211 -v, --version show program's version number and exit
4212 '''
4213
4214 version = '''\
4215 0.1
4216 '''
4217
4218
Steven Bethard0331e902011-03-26 14:48:04 +01004219
4220class TestHelpMetavarTypeFormatter(HelpTestCase):
4221 """"""
4222
4223 def custom_type(string):
4224 return string
4225
4226 parser_signature = Sig(prog='PROG', description='description',
4227 formatter_class=argparse.MetavarTypeHelpFormatter)
4228 argument_signatures = [Sig('a', type=int),
4229 Sig('-b', type=custom_type),
4230 Sig('-c', type=float, metavar='SOME FLOAT')]
4231 argument_group_signatures = []
4232 usage = '''\
4233 usage: PROG [-h] [-b custom_type] [-c SOME FLOAT] int
4234 '''
4235 help = usage + '''\
4236
4237 description
4238
4239 positional arguments:
4240 int
4241
4242 optional arguments:
4243 -h, --help show this help message and exit
4244 -b custom_type
4245 -c SOME FLOAT
4246 '''
4247 version = ''
4248
4249
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004250# =====================================
4251# Optional/Positional constructor tests
4252# =====================================
4253
4254class TestInvalidArgumentConstructors(TestCase):
4255 """Test a bunch of invalid Argument constructors"""
4256
4257 def assertTypeError(self, *args, **kwargs):
4258 parser = argparse.ArgumentParser()
4259 self.assertRaises(TypeError, parser.add_argument,
4260 *args, **kwargs)
4261
4262 def assertValueError(self, *args, **kwargs):
4263 parser = argparse.ArgumentParser()
4264 self.assertRaises(ValueError, parser.add_argument,
4265 *args, **kwargs)
4266
4267 def test_invalid_keyword_arguments(self):
4268 self.assertTypeError('-x', bar=None)
4269 self.assertTypeError('-y', callback='foo')
4270 self.assertTypeError('-y', callback_args=())
4271 self.assertTypeError('-y', callback_kwargs={})
4272
4273 def test_missing_destination(self):
4274 self.assertTypeError()
4275 for action in ['append', 'store']:
4276 self.assertTypeError(action=action)
4277
4278 def test_invalid_option_strings(self):
4279 self.assertValueError('--')
4280 self.assertValueError('---')
4281
4282 def test_invalid_type(self):
4283 self.assertValueError('--foo', type='int')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004284 self.assertValueError('--foo', type=(int, float))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004285
4286 def test_invalid_action(self):
4287 self.assertValueError('-x', action='foo')
4288 self.assertValueError('foo', action='baz')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004289 self.assertValueError('--foo', action=('store', 'append'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004290 parser = argparse.ArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004291 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004292 parser.add_argument("--foo", action="store-true")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004293 self.assertIn('unknown action', str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004294
4295 def test_multiple_dest(self):
4296 parser = argparse.ArgumentParser()
4297 parser.add_argument(dest='foo')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004298 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004299 parser.add_argument('bar', dest='baz')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004300 self.assertIn('dest supplied twice for positional argument',
4301 str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004302
4303 def test_no_argument_actions(self):
4304 for action in ['store_const', 'store_true', 'store_false',
4305 'append_const', 'count']:
4306 for attrs in [dict(type=int), dict(nargs='+'),
4307 dict(choices='ab')]:
4308 self.assertTypeError('-x', action=action, **attrs)
4309
4310 def test_no_argument_no_const_actions(self):
4311 # options with zero arguments
4312 for action in ['store_true', 'store_false', 'count']:
4313
4314 # const is always disallowed
4315 self.assertTypeError('-x', const='foo', action=action)
4316
4317 # nargs is always disallowed
4318 self.assertTypeError('-x', nargs='*', action=action)
4319
4320 def test_more_than_one_argument_actions(self):
4321 for action in ['store', 'append']:
4322
4323 # nargs=0 is disallowed
4324 self.assertValueError('-x', nargs=0, action=action)
4325 self.assertValueError('spam', nargs=0, action=action)
4326
4327 # const is disallowed with non-optional arguments
4328 for nargs in [1, '*', '+']:
4329 self.assertValueError('-x', const='foo',
4330 nargs=nargs, action=action)
4331 self.assertValueError('spam', const='foo',
4332 nargs=nargs, action=action)
4333
4334 def test_required_const_actions(self):
4335 for action in ['store_const', 'append_const']:
4336
4337 # nargs is always disallowed
4338 self.assertTypeError('-x', nargs='+', action=action)
4339
4340 def test_parsers_action_missing_params(self):
4341 self.assertTypeError('command', action='parsers')
4342 self.assertTypeError('command', action='parsers', prog='PROG')
4343 self.assertTypeError('command', action='parsers',
4344 parser_class=argparse.ArgumentParser)
4345
4346 def test_required_positional(self):
4347 self.assertTypeError('foo', required=True)
4348
4349 def test_user_defined_action(self):
4350
4351 class Success(Exception):
4352 pass
4353
4354 class Action(object):
4355
4356 def __init__(self,
4357 option_strings,
4358 dest,
4359 const,
4360 default,
4361 required=False):
4362 if dest == 'spam':
4363 if const is Success:
4364 if default is Success:
4365 raise Success()
4366
4367 def __call__(self, *args, **kwargs):
4368 pass
4369
4370 parser = argparse.ArgumentParser()
4371 self.assertRaises(Success, parser.add_argument, '--spam',
4372 action=Action, default=Success, const=Success)
4373 self.assertRaises(Success, parser.add_argument, 'spam',
4374 action=Action, default=Success, const=Success)
4375
4376# ================================
4377# Actions returned by add_argument
4378# ================================
4379
4380class TestActionsReturned(TestCase):
4381
4382 def test_dest(self):
4383 parser = argparse.ArgumentParser()
4384 action = parser.add_argument('--foo')
4385 self.assertEqual(action.dest, 'foo')
4386 action = parser.add_argument('-b', '--bar')
4387 self.assertEqual(action.dest, 'bar')
4388 action = parser.add_argument('-x', '-y')
4389 self.assertEqual(action.dest, 'x')
4390
4391 def test_misc(self):
4392 parser = argparse.ArgumentParser()
4393 action = parser.add_argument('--foo', nargs='?', const=42,
4394 default=84, type=int, choices=[1, 2],
4395 help='FOO', metavar='BAR', dest='baz')
4396 self.assertEqual(action.nargs, '?')
4397 self.assertEqual(action.const, 42)
4398 self.assertEqual(action.default, 84)
4399 self.assertEqual(action.type, int)
4400 self.assertEqual(action.choices, [1, 2])
4401 self.assertEqual(action.help, 'FOO')
4402 self.assertEqual(action.metavar, 'BAR')
4403 self.assertEqual(action.dest, 'baz')
4404
4405
4406# ================================
4407# Argument conflict handling tests
4408# ================================
4409
4410class TestConflictHandling(TestCase):
4411
4412 def test_bad_type(self):
4413 self.assertRaises(ValueError, argparse.ArgumentParser,
4414 conflict_handler='foo')
4415
4416 def test_conflict_error(self):
4417 parser = argparse.ArgumentParser()
4418 parser.add_argument('-x')
4419 self.assertRaises(argparse.ArgumentError,
4420 parser.add_argument, '-x')
4421 parser.add_argument('--spam')
4422 self.assertRaises(argparse.ArgumentError,
4423 parser.add_argument, '--spam')
4424
4425 def test_resolve_error(self):
4426 get_parser = argparse.ArgumentParser
4427 parser = get_parser(prog='PROG', conflict_handler='resolve')
4428
4429 parser.add_argument('-x', help='OLD X')
4430 parser.add_argument('-x', help='NEW X')
4431 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4432 usage: PROG [-h] [-x X]
4433
4434 optional arguments:
4435 -h, --help show this help message and exit
4436 -x X NEW X
4437 '''))
4438
4439 parser.add_argument('--spam', metavar='OLD_SPAM')
4440 parser.add_argument('--spam', metavar='NEW_SPAM')
4441 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4442 usage: PROG [-h] [-x X] [--spam NEW_SPAM]
4443
4444 optional arguments:
4445 -h, --help show this help message and exit
4446 -x X NEW X
4447 --spam NEW_SPAM
4448 '''))
4449
4450
4451# =============================
4452# Help and Version option tests
4453# =============================
4454
4455class TestOptionalsHelpVersionActions(TestCase):
4456 """Test the help and version actions"""
4457
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004458 def assertPrintHelpExit(self, parser, args_str):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004459 with self.assertRaises(ArgumentParserError) as cm:
4460 parser.parse_args(args_str.split())
4461 self.assertEqual(parser.format_help(), cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004462
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004463 def assertArgumentParserError(self, parser, *args):
4464 self.assertRaises(ArgumentParserError, parser.parse_args, args)
4465
4466 def test_version(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004467 parser = ErrorRaisingArgumentParser()
4468 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004469 self.assertPrintHelpExit(parser, '-h')
4470 self.assertPrintHelpExit(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004471 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004472
4473 def test_version_format(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004474 parser = ErrorRaisingArgumentParser(prog='PPP')
4475 parser.add_argument('-v', '--version', action='version', version='%(prog)s 3.5')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004476 with self.assertRaises(ArgumentParserError) as cm:
4477 parser.parse_args(['-v'])
4478 self.assertEqual('PPP 3.5\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004479
4480 def test_version_no_help(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004481 parser = ErrorRaisingArgumentParser(add_help=False)
4482 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004483 self.assertArgumentParserError(parser, '-h')
4484 self.assertArgumentParserError(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004485 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004486
4487 def test_version_action(self):
4488 parser = ErrorRaisingArgumentParser(prog='XXX')
4489 parser.add_argument('-V', action='version', version='%(prog)s 3.7')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004490 with self.assertRaises(ArgumentParserError) as cm:
4491 parser.parse_args(['-V'])
4492 self.assertEqual('XXX 3.7\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004493
4494 def test_no_help(self):
4495 parser = ErrorRaisingArgumentParser(add_help=False)
4496 self.assertArgumentParserError(parser, '-h')
4497 self.assertArgumentParserError(parser, '--help')
4498 self.assertArgumentParserError(parser, '-v')
4499 self.assertArgumentParserError(parser, '--version')
4500
4501 def test_alternate_help_version(self):
4502 parser = ErrorRaisingArgumentParser()
4503 parser.add_argument('-x', action='help')
4504 parser.add_argument('-y', action='version')
4505 self.assertPrintHelpExit(parser, '-x')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004506 self.assertArgumentParserError(parser, '-v')
4507 self.assertArgumentParserError(parser, '--version')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004508 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004509
4510 def test_help_version_extra_arguments(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004511 parser = ErrorRaisingArgumentParser()
4512 parser.add_argument('--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004513 parser.add_argument('-x', action='store_true')
4514 parser.add_argument('y')
4515
4516 # try all combinations of valid prefixes and suffixes
4517 valid_prefixes = ['', '-x', 'foo', '-x bar', 'baz -x']
4518 valid_suffixes = valid_prefixes + ['--bad-option', 'foo bar baz']
4519 for prefix in valid_prefixes:
4520 for suffix in valid_suffixes:
4521 format = '%s %%s %s' % (prefix, suffix)
4522 self.assertPrintHelpExit(parser, format % '-h')
4523 self.assertPrintHelpExit(parser, format % '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004524 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004525
4526
4527# ======================
4528# str() and repr() tests
4529# ======================
4530
4531class TestStrings(TestCase):
4532 """Test str() and repr() on Optionals and Positionals"""
4533
4534 def assertStringEqual(self, obj, result_string):
4535 for func in [str, repr]:
4536 self.assertEqual(func(obj), result_string)
4537
4538 def test_optional(self):
4539 option = argparse.Action(
4540 option_strings=['--foo', '-a', '-b'],
4541 dest='b',
4542 type='int',
4543 nargs='+',
4544 default=42,
4545 choices=[1, 2, 3],
4546 help='HELP',
4547 metavar='METAVAR')
4548 string = (
4549 "Action(option_strings=['--foo', '-a', '-b'], dest='b', "
4550 "nargs='+', const=None, default=42, type='int', "
4551 "choices=[1, 2, 3], help='HELP', metavar='METAVAR')")
4552 self.assertStringEqual(option, string)
4553
4554 def test_argument(self):
4555 argument = argparse.Action(
4556 option_strings=[],
4557 dest='x',
4558 type=float,
4559 nargs='?',
4560 default=2.5,
4561 choices=[0.5, 1.5, 2.5],
4562 help='H HH H',
4563 metavar='MV MV MV')
4564 string = (
4565 "Action(option_strings=[], dest='x', nargs='?', "
4566 "const=None, default=2.5, type=%r, choices=[0.5, 1.5, 2.5], "
4567 "help='H HH H', metavar='MV MV MV')" % float)
4568 self.assertStringEqual(argument, string)
4569
4570 def test_namespace(self):
4571 ns = argparse.Namespace(foo=42, bar='spam')
4572 string = "Namespace(bar='spam', foo=42)"
4573 self.assertStringEqual(ns, string)
4574
Berker Peksag76b17142015-07-29 23:51:47 +03004575 def test_namespace_starkwargs_notidentifier(self):
4576 ns = argparse.Namespace(**{'"': 'quote'})
4577 string = """Namespace(**{'"': 'quote'})"""
4578 self.assertStringEqual(ns, string)
4579
4580 def test_namespace_kwargs_and_starkwargs_notidentifier(self):
4581 ns = argparse.Namespace(a=1, **{'"': 'quote'})
4582 string = """Namespace(a=1, **{'"': 'quote'})"""
4583 self.assertStringEqual(ns, string)
4584
4585 def test_namespace_starkwargs_identifier(self):
4586 ns = argparse.Namespace(**{'valid': True})
4587 string = "Namespace(valid=True)"
4588 self.assertStringEqual(ns, string)
4589
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004590 def test_parser(self):
4591 parser = argparse.ArgumentParser(prog='PROG')
4592 string = (
4593 "ArgumentParser(prog='PROG', usage=None, description=None, "
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004594 "formatter_class=%r, conflict_handler='error', "
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004595 "add_help=True)" % argparse.HelpFormatter)
4596 self.assertStringEqual(parser, string)
4597
4598# ===============
4599# Namespace tests
4600# ===============
4601
4602class TestNamespace(TestCase):
4603
4604 def test_constructor(self):
4605 ns = argparse.Namespace()
4606 self.assertRaises(AttributeError, getattr, ns, 'x')
4607
4608 ns = argparse.Namespace(a=42, b='spam')
4609 self.assertEqual(ns.a, 42)
4610 self.assertEqual(ns.b, 'spam')
4611
4612 def test_equality(self):
4613 ns1 = argparse.Namespace(a=1, b=2)
4614 ns2 = argparse.Namespace(b=2, a=1)
4615 ns3 = argparse.Namespace(a=1)
4616 ns4 = argparse.Namespace(b=2)
4617
4618 self.assertEqual(ns1, ns2)
4619 self.assertNotEqual(ns1, ns3)
4620 self.assertNotEqual(ns1, ns4)
4621 self.assertNotEqual(ns2, ns3)
4622 self.assertNotEqual(ns2, ns4)
4623 self.assertTrue(ns1 != ns3)
4624 self.assertTrue(ns1 != ns4)
4625 self.assertTrue(ns2 != ns3)
4626 self.assertTrue(ns2 != ns4)
4627
Berker Peksagc16387b2016-09-28 17:21:52 +03004628 def test_equality_returns_notimplemented(self):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07004629 # See issue 21481
4630 ns = argparse.Namespace(a=1, b=2)
4631 self.assertIs(ns.__eq__(None), NotImplemented)
4632 self.assertIs(ns.__ne__(None), NotImplemented)
4633
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004634
4635# ===================
4636# File encoding tests
4637# ===================
4638
4639class TestEncoding(TestCase):
4640
4641 def _test_module_encoding(self, path):
4642 path, _ = os.path.splitext(path)
4643 path += ".py"
Victor Stinner272d8882017-06-16 08:59:01 +02004644 with open(path, 'r', encoding='utf-8') as f:
Antoine Pitroub86680e2010-10-14 21:15:17 +00004645 f.read()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004646
4647 def test_argparse_module_encoding(self):
4648 self._test_module_encoding(argparse.__file__)
4649
4650 def test_test_argparse_module_encoding(self):
4651 self._test_module_encoding(__file__)
4652
4653# ===================
4654# ArgumentError tests
4655# ===================
4656
4657class TestArgumentError(TestCase):
4658
4659 def test_argument_error(self):
4660 msg = "my error here"
4661 error = argparse.ArgumentError(None, msg)
4662 self.assertEqual(str(error), msg)
4663
4664# =======================
4665# ArgumentTypeError tests
4666# =======================
4667
R. David Murray722b5fd2010-11-20 03:48:58 +00004668class TestArgumentTypeError(TestCase):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004669
4670 def test_argument_type_error(self):
4671
4672 def spam(string):
4673 raise argparse.ArgumentTypeError('spam!')
4674
4675 parser = ErrorRaisingArgumentParser(prog='PROG', add_help=False)
4676 parser.add_argument('x', type=spam)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004677 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004678 parser.parse_args(['XXX'])
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004679 self.assertEqual('usage: PROG x\nPROG: error: argument x: spam!\n',
4680 cm.exception.stderr)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004681
R David Murrayf97c59a2011-06-09 12:34:07 -04004682# =========================
4683# MessageContentError tests
4684# =========================
4685
4686class TestMessageContentError(TestCase):
4687
4688 def test_missing_argument_name_in_message(self):
4689 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4690 parser.add_argument('req_pos', type=str)
4691 parser.add_argument('-req_opt', type=int, required=True)
4692 parser.add_argument('need_one', type=str, nargs='+')
4693
4694 with self.assertRaises(ArgumentParserError) as cm:
4695 parser.parse_args([])
4696 msg = str(cm.exception)
4697 self.assertRegex(msg, 'req_pos')
4698 self.assertRegex(msg, 'req_opt')
4699 self.assertRegex(msg, 'need_one')
4700 with self.assertRaises(ArgumentParserError) as cm:
4701 parser.parse_args(['myXargument'])
4702 msg = str(cm.exception)
4703 self.assertNotIn(msg, 'req_pos')
4704 self.assertRegex(msg, 'req_opt')
4705 self.assertRegex(msg, 'need_one')
4706 with self.assertRaises(ArgumentParserError) as cm:
4707 parser.parse_args(['myXargument', '-req_opt=1'])
4708 msg = str(cm.exception)
4709 self.assertNotIn(msg, 'req_pos')
4710 self.assertNotIn(msg, 'req_opt')
4711 self.assertRegex(msg, 'need_one')
4712
4713 def test_optional_optional_not_in_message(self):
4714 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4715 parser.add_argument('req_pos', type=str)
4716 parser.add_argument('--req_opt', type=int, required=True)
4717 parser.add_argument('--opt_opt', type=bool, nargs='?',
4718 default=True)
4719 with self.assertRaises(ArgumentParserError) as cm:
4720 parser.parse_args([])
4721 msg = str(cm.exception)
4722 self.assertRegex(msg, 'req_pos')
4723 self.assertRegex(msg, 'req_opt')
4724 self.assertNotIn(msg, 'opt_opt')
4725 with self.assertRaises(ArgumentParserError) as cm:
4726 parser.parse_args(['--req_opt=1'])
4727 msg = str(cm.exception)
4728 self.assertRegex(msg, 'req_pos')
4729 self.assertNotIn(msg, 'req_opt')
4730 self.assertNotIn(msg, 'opt_opt')
4731
4732 def test_optional_positional_not_in_message(self):
4733 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4734 parser.add_argument('req_pos')
4735 parser.add_argument('optional_positional', nargs='?', default='eggs')
4736 with self.assertRaises(ArgumentParserError) as cm:
4737 parser.parse_args([])
4738 msg = str(cm.exception)
4739 self.assertRegex(msg, 'req_pos')
4740 self.assertNotIn(msg, 'optional_positional')
4741
4742
R David Murray6fb8fb12012-08-31 22:45:20 -04004743# ================================================
4744# Check that the type function is called only once
4745# ================================================
4746
4747class TestTypeFunctionCallOnlyOnce(TestCase):
4748
4749 def test_type_function_call_only_once(self):
4750 def spam(string_to_convert):
4751 self.assertEqual(string_to_convert, 'spam!')
4752 return 'foo_converted'
4753
4754 parser = argparse.ArgumentParser()
4755 parser.add_argument('--foo', type=spam, default='bar')
4756 args = parser.parse_args('--foo spam!'.split())
4757 self.assertEqual(NS(foo='foo_converted'), args)
4758
Barry Warsaweaae1b72012-09-12 14:34:50 -04004759# ==================================================================
4760# Check semantics regarding the default argument and type conversion
4761# ==================================================================
R David Murray6fb8fb12012-08-31 22:45:20 -04004762
Barry Warsaweaae1b72012-09-12 14:34:50 -04004763class TestTypeFunctionCalledOnDefault(TestCase):
R David Murray6fb8fb12012-08-31 22:45:20 -04004764
4765 def test_type_function_call_with_non_string_default(self):
4766 def spam(int_to_convert):
4767 self.assertEqual(int_to_convert, 0)
4768 return 'foo_converted'
4769
4770 parser = argparse.ArgumentParser()
4771 parser.add_argument('--foo', type=spam, default=0)
4772 args = parser.parse_args([])
Barry Warsaweaae1b72012-09-12 14:34:50 -04004773 # foo should *not* be converted because its default is not a string.
4774 self.assertEqual(NS(foo=0), args)
4775
4776 def test_type_function_call_with_string_default(self):
4777 def spam(int_to_convert):
4778 return 'foo_converted'
4779
4780 parser = argparse.ArgumentParser()
4781 parser.add_argument('--foo', type=spam, default='0')
4782 args = parser.parse_args([])
4783 # foo is converted because its default is a string.
R David Murray6fb8fb12012-08-31 22:45:20 -04004784 self.assertEqual(NS(foo='foo_converted'), args)
4785
Barry Warsaweaae1b72012-09-12 14:34:50 -04004786 def test_no_double_type_conversion_of_default(self):
4787 def extend(str_to_convert):
4788 return str_to_convert + '*'
4789
4790 parser = argparse.ArgumentParser()
4791 parser.add_argument('--test', type=extend, default='*')
4792 args = parser.parse_args([])
4793 # The test argument will be two stars, one coming from the default
4794 # value and one coming from the type conversion being called exactly
4795 # once.
4796 self.assertEqual(NS(test='**'), args)
4797
Barry Warsaw4b2f9e92012-09-11 22:38:47 -04004798 def test_issue_15906(self):
4799 # Issue #15906: When action='append', type=str, default=[] are
4800 # providing, the dest value was the string representation "[]" when it
4801 # should have been an empty list.
4802 parser = argparse.ArgumentParser()
4803 parser.add_argument('--test', dest='test', type=str,
4804 default=[], action='append')
4805 args = parser.parse_args([])
4806 self.assertEqual(args.test, [])
4807
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004808# ======================
4809# parse_known_args tests
4810# ======================
4811
4812class TestParseKnownArgs(TestCase):
4813
R David Murrayb5228282012-09-08 12:08:01 -04004814 def test_arguments_tuple(self):
4815 parser = argparse.ArgumentParser()
4816 parser.parse_args(())
4817
4818 def test_arguments_list(self):
4819 parser = argparse.ArgumentParser()
4820 parser.parse_args([])
4821
4822 def test_arguments_tuple_positional(self):
4823 parser = argparse.ArgumentParser()
4824 parser.add_argument('x')
4825 parser.parse_args(('x',))
4826
4827 def test_arguments_list_positional(self):
4828 parser = argparse.ArgumentParser()
4829 parser.add_argument('x')
4830 parser.parse_args(['x'])
4831
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004832 def test_optionals(self):
4833 parser = argparse.ArgumentParser()
4834 parser.add_argument('--foo')
4835 args, extras = parser.parse_known_args('--foo F --bar --baz'.split())
4836 self.assertEqual(NS(foo='F'), args)
4837 self.assertEqual(['--bar', '--baz'], extras)
4838
4839 def test_mixed(self):
4840 parser = argparse.ArgumentParser()
4841 parser.add_argument('-v', nargs='?', const=1, type=int)
4842 parser.add_argument('--spam', action='store_false')
4843 parser.add_argument('badger')
4844
4845 argv = ["B", "C", "--foo", "-v", "3", "4"]
4846 args, extras = parser.parse_known_args(argv)
4847 self.assertEqual(NS(v=3, spam=True, badger="B"), args)
4848 self.assertEqual(["C", "--foo", "4"], extras)
4849
R. David Murray0f6b9d22017-09-06 20:25:40 -04004850# ===========================
4851# parse_intermixed_args tests
4852# ===========================
4853
4854class TestIntermixedArgs(TestCase):
4855 def test_basic(self):
4856 # test parsing intermixed optionals and positionals
4857 parser = argparse.ArgumentParser(prog='PROG')
4858 parser.add_argument('--foo', dest='foo')
4859 bar = parser.add_argument('--bar', dest='bar', required=True)
4860 parser.add_argument('cmd')
4861 parser.add_argument('rest', nargs='*', type=int)
4862 argv = 'cmd --foo x 1 --bar y 2 3'.split()
4863 args = parser.parse_intermixed_args(argv)
4864 # rest gets [1,2,3] despite the foo and bar strings
4865 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args)
4866
4867 args, extras = parser.parse_known_args(argv)
4868 # cannot parse the '1,2,3'
4869 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[]), args)
4870 self.assertEqual(["1", "2", "3"], extras)
4871
4872 argv = 'cmd --foo x 1 --error 2 --bar y 3'.split()
4873 args, extras = parser.parse_known_intermixed_args(argv)
4874 # unknown optionals go into extras
4875 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1]), args)
4876 self.assertEqual(['--error', '2', '3'], extras)
4877
4878 # restores attributes that were temporarily changed
4879 self.assertIsNone(parser.usage)
4880 self.assertEqual(bar.required, True)
4881
4882 def test_remainder(self):
4883 # Intermixed and remainder are incompatible
4884 parser = ErrorRaisingArgumentParser(prog='PROG')
4885 parser.add_argument('-z')
4886 parser.add_argument('x')
4887 parser.add_argument('y', nargs='...')
4888 argv = 'X A B -z Z'.split()
4889 # intermixed fails with '...' (also 'A...')
4890 # self.assertRaises(TypeError, parser.parse_intermixed_args, argv)
4891 with self.assertRaises(TypeError) as cm:
4892 parser.parse_intermixed_args(argv)
4893 self.assertRegex(str(cm.exception), r'\.\.\.')
4894
4895 def test_exclusive(self):
4896 # mutually exclusive group; intermixed works fine
4897 parser = ErrorRaisingArgumentParser(prog='PROG')
4898 group = parser.add_mutually_exclusive_group(required=True)
4899 group.add_argument('--foo', action='store_true', help='FOO')
4900 group.add_argument('--spam', help='SPAM')
4901 parser.add_argument('badger', nargs='*', default='X', help='BADGER')
4902 args = parser.parse_intermixed_args('1 --foo 2'.split())
4903 self.assertEqual(NS(badger=['1', '2'], foo=True, spam=None), args)
4904 self.assertRaises(ArgumentParserError, parser.parse_intermixed_args, '1 2'.split())
4905 self.assertEqual(group.required, True)
4906
4907 def test_exclusive_incompatible(self):
4908 # mutually exclusive group including positional - fail
4909 parser = ErrorRaisingArgumentParser(prog='PROG')
4910 group = parser.add_mutually_exclusive_group(required=True)
4911 group.add_argument('--foo', action='store_true', help='FOO')
4912 group.add_argument('--spam', help='SPAM')
4913 group.add_argument('badger', nargs='*', default='X', help='BADGER')
4914 self.assertRaises(TypeError, parser.parse_intermixed_args, [])
4915 self.assertEqual(group.required, True)
4916
4917class TestIntermixedMessageContentError(TestCase):
4918 # case where Intermixed gives different error message
4919 # error is raised by 1st parsing step
4920 def test_missing_argument_name_in_message(self):
4921 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4922 parser.add_argument('req_pos', type=str)
4923 parser.add_argument('-req_opt', type=int, required=True)
4924
4925 with self.assertRaises(ArgumentParserError) as cm:
4926 parser.parse_args([])
4927 msg = str(cm.exception)
4928 self.assertRegex(msg, 'req_pos')
4929 self.assertRegex(msg, 'req_opt')
4930
4931 with self.assertRaises(ArgumentParserError) as cm:
4932 parser.parse_intermixed_args([])
4933 msg = str(cm.exception)
4934 self.assertNotRegex(msg, 'req_pos')
4935 self.assertRegex(msg, 'req_opt')
4936
Steven Bethard8d9a4622011-03-26 17:33:56 +01004937# ==========================
4938# add_argument metavar tests
4939# ==========================
4940
4941class TestAddArgumentMetavar(TestCase):
4942
4943 EXPECTED_MESSAGE = "length of metavar tuple does not match nargs"
4944
4945 def do_test_no_exception(self, nargs, metavar):
4946 parser = argparse.ArgumentParser()
4947 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
4948
4949 def do_test_exception(self, nargs, metavar):
4950 parser = argparse.ArgumentParser()
4951 with self.assertRaises(ValueError) as cm:
4952 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
4953 self.assertEqual(cm.exception.args[0], self.EXPECTED_MESSAGE)
4954
4955 # Unit tests for different values of metavar when nargs=None
4956
4957 def test_nargs_None_metavar_string(self):
4958 self.do_test_no_exception(nargs=None, metavar="1")
4959
4960 def test_nargs_None_metavar_length0(self):
4961 self.do_test_exception(nargs=None, metavar=tuple())
4962
4963 def test_nargs_None_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05004964 self.do_test_no_exception(nargs=None, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01004965
4966 def test_nargs_None_metavar_length2(self):
4967 self.do_test_exception(nargs=None, metavar=("1", "2"))
4968
4969 def test_nargs_None_metavar_length3(self):
4970 self.do_test_exception(nargs=None, metavar=("1", "2", "3"))
4971
4972 # Unit tests for different values of metavar when nargs=?
4973
4974 def test_nargs_optional_metavar_string(self):
4975 self.do_test_no_exception(nargs="?", metavar="1")
4976
4977 def test_nargs_optional_metavar_length0(self):
4978 self.do_test_exception(nargs="?", metavar=tuple())
4979
4980 def test_nargs_optional_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05004981 self.do_test_no_exception(nargs="?", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01004982
4983 def test_nargs_optional_metavar_length2(self):
4984 self.do_test_exception(nargs="?", metavar=("1", "2"))
4985
4986 def test_nargs_optional_metavar_length3(self):
4987 self.do_test_exception(nargs="?", metavar=("1", "2", "3"))
4988
4989 # Unit tests for different values of metavar when nargs=*
4990
4991 def test_nargs_zeroormore_metavar_string(self):
4992 self.do_test_no_exception(nargs="*", metavar="1")
4993
4994 def test_nargs_zeroormore_metavar_length0(self):
4995 self.do_test_exception(nargs="*", metavar=tuple())
4996
4997 def test_nargs_zeroormore_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05004998 self.do_test_exception(nargs="*", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01004999
5000 def test_nargs_zeroormore_metavar_length2(self):
5001 self.do_test_no_exception(nargs="*", metavar=("1", "2"))
5002
5003 def test_nargs_zeroormore_metavar_length3(self):
5004 self.do_test_exception(nargs="*", metavar=("1", "2", "3"))
5005
5006 # Unit tests for different values of metavar when nargs=+
5007
5008 def test_nargs_oneormore_metavar_string(self):
5009 self.do_test_no_exception(nargs="+", metavar="1")
5010
5011 def test_nargs_oneormore_metavar_length0(self):
5012 self.do_test_exception(nargs="+", metavar=tuple())
5013
5014 def test_nargs_oneormore_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005015 self.do_test_exception(nargs="+", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005016
5017 def test_nargs_oneormore_metavar_length2(self):
5018 self.do_test_no_exception(nargs="+", metavar=("1", "2"))
5019
5020 def test_nargs_oneormore_metavar_length3(self):
5021 self.do_test_exception(nargs="+", metavar=("1", "2", "3"))
5022
5023 # Unit tests for different values of metavar when nargs=...
5024
5025 def test_nargs_remainder_metavar_string(self):
5026 self.do_test_no_exception(nargs="...", metavar="1")
5027
5028 def test_nargs_remainder_metavar_length0(self):
5029 self.do_test_no_exception(nargs="...", metavar=tuple())
5030
5031 def test_nargs_remainder_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005032 self.do_test_no_exception(nargs="...", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005033
5034 def test_nargs_remainder_metavar_length2(self):
5035 self.do_test_no_exception(nargs="...", metavar=("1", "2"))
5036
5037 def test_nargs_remainder_metavar_length3(self):
5038 self.do_test_no_exception(nargs="...", metavar=("1", "2", "3"))
5039
5040 # Unit tests for different values of metavar when nargs=A...
5041
5042 def test_nargs_parser_metavar_string(self):
5043 self.do_test_no_exception(nargs="A...", metavar="1")
5044
5045 def test_nargs_parser_metavar_length0(self):
5046 self.do_test_exception(nargs="A...", metavar=tuple())
5047
5048 def test_nargs_parser_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005049 self.do_test_no_exception(nargs="A...", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005050
5051 def test_nargs_parser_metavar_length2(self):
5052 self.do_test_exception(nargs="A...", metavar=("1", "2"))
5053
5054 def test_nargs_parser_metavar_length3(self):
5055 self.do_test_exception(nargs="A...", metavar=("1", "2", "3"))
5056
5057 # Unit tests for different values of metavar when nargs=1
5058
5059 def test_nargs_1_metavar_string(self):
5060 self.do_test_no_exception(nargs=1, metavar="1")
5061
5062 def test_nargs_1_metavar_length0(self):
5063 self.do_test_exception(nargs=1, metavar=tuple())
5064
5065 def test_nargs_1_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005066 self.do_test_no_exception(nargs=1, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005067
5068 def test_nargs_1_metavar_length2(self):
5069 self.do_test_exception(nargs=1, metavar=("1", "2"))
5070
5071 def test_nargs_1_metavar_length3(self):
5072 self.do_test_exception(nargs=1, metavar=("1", "2", "3"))
5073
5074 # Unit tests for different values of metavar when nargs=2
5075
5076 def test_nargs_2_metavar_string(self):
5077 self.do_test_no_exception(nargs=2, metavar="1")
5078
5079 def test_nargs_2_metavar_length0(self):
5080 self.do_test_exception(nargs=2, metavar=tuple())
5081
5082 def test_nargs_2_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005083 self.do_test_exception(nargs=2, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005084
5085 def test_nargs_2_metavar_length2(self):
5086 self.do_test_no_exception(nargs=2, metavar=("1", "2"))
5087
5088 def test_nargs_2_metavar_length3(self):
5089 self.do_test_exception(nargs=2, metavar=("1", "2", "3"))
5090
5091 # Unit tests for different values of metavar when nargs=3
5092
5093 def test_nargs_3_metavar_string(self):
5094 self.do_test_no_exception(nargs=3, metavar="1")
5095
5096 def test_nargs_3_metavar_length0(self):
5097 self.do_test_exception(nargs=3, metavar=tuple())
5098
5099 def test_nargs_3_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005100 self.do_test_exception(nargs=3, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005101
5102 def test_nargs_3_metavar_length2(self):
5103 self.do_test_exception(nargs=3, metavar=("1", "2"))
5104
5105 def test_nargs_3_metavar_length3(self):
5106 self.do_test_no_exception(nargs=3, metavar=("1", "2", "3"))
5107
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005108# ============================
5109# from argparse import * tests
5110# ============================
5111
5112class TestImportStar(TestCase):
5113
5114 def test(self):
5115 for name in argparse.__all__:
5116 self.assertTrue(hasattr(argparse, name))
5117
Steven Bethard72c55382010-11-01 15:23:12 +00005118 def test_all_exports_everything_but_modules(self):
5119 items = [
5120 name
5121 for name, value in vars(argparse).items()
Éric Araujo12159152010-12-04 17:31:49 +00005122 if not (name.startswith("_") or name == 'ngettext')
Steven Bethard72c55382010-11-01 15:23:12 +00005123 if not inspect.ismodule(value)
5124 ]
5125 self.assertEqual(sorted(items), sorted(argparse.__all__))
5126
wim glenn66f02aa2018-06-08 05:12:49 -05005127
5128class TestWrappingMetavar(TestCase):
5129
5130 def setUp(self):
Berker Peksag74102c92018-07-25 18:23:44 +03005131 super().setUp()
wim glenn66f02aa2018-06-08 05:12:49 -05005132 self.parser = ErrorRaisingArgumentParser(
5133 'this_is_spammy_prog_with_a_long_name_sorry_about_the_name'
5134 )
5135 # this metavar was triggering library assertion errors due to usage
5136 # message formatting incorrectly splitting on the ] chars within
5137 metavar = '<http[s]://example:1234>'
5138 self.parser.add_argument('--proxy', metavar=metavar)
5139
5140 def test_help_with_metavar(self):
5141 help_text = self.parser.format_help()
5142 self.assertEqual(help_text, textwrap.dedent('''\
5143 usage: this_is_spammy_prog_with_a_long_name_sorry_about_the_name
5144 [-h] [--proxy <http[s]://example:1234>]
5145
5146 optional arguments:
5147 -h, --help show this help message and exit
5148 --proxy <http[s]://example:1234>
5149 '''))
5150
5151
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005152def test_main():
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02005153 support.run_unittest(__name__)
Benjamin Peterson4fd181c2010-03-02 23:46:42 +00005154 # Remove global references to avoid looking like we have refleaks.
5155 RFile.seen = {}
5156 WFile.seen = set()
5157
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005158
5159
5160if __name__ == '__main__':
5161 test_main()