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