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