blob: 4d0316f73edcd29cf8b16e0e5f8f69f4b92b5af5 [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
Steven Bethard72c55382010-11-01 15:23:12 +00003import inspect
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004import os
5import shutil
Steven Bethardb0270112011-01-24 21:02:50 +00006import stat
Benjamin Peterson698a18a2010-03-02 22:34:37 +00007import sys
8import textwrap
9import tempfile
10import unittest
Benjamin Peterson698a18a2010-03-02 22:34:37 +000011import argparse
12
Benjamin Peterson16f2fd02010-03-02 23:09:38 +000013from io import StringIO
14
Benjamin Peterson698a18a2010-03-02 22:34:37 +000015from test import support
Hai Shi46605972020-08-04 00:49:18 +080016from test.support import os_helper
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.
Hai Shi46605972020-08-04 00:49:18 +080027 env = os_helper.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)
Inada Naoki8bbfeb32021-04-02 12:53:46 +090048 with open(file_path, 'w', encoding="utf-8") as file:
Steven Bethardb0270112011-01-24 21:02:50 +000049 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()
alclarksd4331c52020-02-21 08:48:36 +0000109 raise ArgumentParserError(
110 "SystemExit", stdout, stderr, code) from None
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000111 finally:
112 sys.stdout = old_stdout
113 sys.stderr = old_stderr
114
115
116class ErrorRaisingArgumentParser(argparse.ArgumentParser):
117
118 def parse_args(self, *args, **kwargs):
119 parse_args = super(ErrorRaisingArgumentParser, self).parse_args
120 return stderr_to_parser_error(parse_args, *args, **kwargs)
121
122 def exit(self, *args, **kwargs):
123 exit = super(ErrorRaisingArgumentParser, self).exit
124 return stderr_to_parser_error(exit, *args, **kwargs)
125
126 def error(self, *args, **kwargs):
127 error = super(ErrorRaisingArgumentParser, self).error
128 return stderr_to_parser_error(error, *args, **kwargs)
129
130
131class ParserTesterMetaclass(type):
132 """Adds parser tests using the class attributes.
133
134 Classes of this type should specify the following attributes:
135
136 argument_signatures -- a list of Sig objects which specify
137 the signatures of Argument objects to be created
138 failures -- a list of args lists that should cause the parser
139 to fail
140 successes -- a list of (initial_args, options, remaining_args) tuples
141 where initial_args specifies the string args to be parsed,
142 options is a dict that should match the vars() of the options
143 parsed out of initial_args, and remaining_args should be any
144 remaining unparsed arguments
145 """
146
147 def __init__(cls, name, bases, bodydict):
148 if name == 'ParserTestCase':
149 return
150
151 # default parser signature is empty
152 if not hasattr(cls, 'parser_signature'):
153 cls.parser_signature = Sig()
154 if not hasattr(cls, 'parser_class'):
155 cls.parser_class = ErrorRaisingArgumentParser
156
157 # ---------------------------------------
158 # functions for adding optional arguments
159 # ---------------------------------------
160 def no_groups(parser, argument_signatures):
161 """Add all arguments directly to the parser"""
162 for sig in argument_signatures:
163 parser.add_argument(*sig.args, **sig.kwargs)
164
165 def one_group(parser, argument_signatures):
166 """Add all arguments under a single group in the parser"""
167 group = parser.add_argument_group('foo')
168 for sig in argument_signatures:
169 group.add_argument(*sig.args, **sig.kwargs)
170
171 def many_groups(parser, argument_signatures):
172 """Add each argument in its own group to the parser"""
173 for i, sig in enumerate(argument_signatures):
174 group = parser.add_argument_group('foo:%i' % i)
175 group.add_argument(*sig.args, **sig.kwargs)
176
177 # --------------------------
178 # functions for parsing args
179 # --------------------------
180 def listargs(parser, args):
181 """Parse the args by passing in a list"""
182 return parser.parse_args(args)
183
184 def sysargs(parser, args):
185 """Parse the args by defaulting to sys.argv"""
186 old_sys_argv = sys.argv
187 sys.argv = [old_sys_argv[0]] + args
188 try:
189 return parser.parse_args()
190 finally:
191 sys.argv = old_sys_argv
192
193 # class that holds the combination of one optional argument
194 # addition method and one arg parsing method
195 class AddTests(object):
196
197 def __init__(self, tester_cls, add_arguments, parse_args):
198 self._add_arguments = add_arguments
199 self._parse_args = parse_args
200
201 add_arguments_name = self._add_arguments.__name__
202 parse_args_name = self._parse_args.__name__
203 for test_func in [self.test_failures, self.test_successes]:
204 func_name = test_func.__name__
205 names = func_name, add_arguments_name, parse_args_name
206 test_name = '_'.join(names)
207
208 def wrapper(self, test_func=test_func):
209 test_func(self)
210 try:
211 wrapper.__name__ = test_name
212 except TypeError:
213 pass
214 setattr(tester_cls, test_name, wrapper)
215
216 def _get_parser(self, tester):
217 args = tester.parser_signature.args
218 kwargs = tester.parser_signature.kwargs
219 parser = tester.parser_class(*args, **kwargs)
220 self._add_arguments(parser, tester.argument_signatures)
221 return parser
222
223 def test_failures(self, tester):
224 parser = self._get_parser(tester)
225 for args_str in tester.failures:
226 args = args_str.split()
Ezio Melotti12b7f482014-08-05 02:24:03 +0300227 with tester.assertRaises(ArgumentParserError, msg=args):
228 parser.parse_args(args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000229
230 def test_successes(self, tester):
231 parser = self._get_parser(tester)
232 for args, expected_ns in tester.successes:
233 if isinstance(args, str):
234 args = args.split()
235 result_ns = self._parse_args(parser, args)
236 tester.assertEqual(expected_ns, result_ns)
237
238 # add tests for each combination of an optionals adding method
239 # and an arg parsing method
240 for add_arguments in [no_groups, one_group, many_groups]:
241 for parse_args in [listargs, sysargs]:
242 AddTests(cls, add_arguments, parse_args)
243
244bases = TestCase,
245ParserTestCase = ParserTesterMetaclass('ParserTestCase', bases, {})
246
247# ===============
248# Optionals tests
249# ===============
250
251class TestOptionalsSingleDash(ParserTestCase):
252 """Test an Optional with a single-dash option string"""
253
254 argument_signatures = [Sig('-x')]
255 failures = ['-x', 'a', '--foo', '-x --foo', '-x -y']
256 successes = [
257 ('', NS(x=None)),
258 ('-x a', NS(x='a')),
259 ('-xa', NS(x='a')),
260 ('-x -1', NS(x='-1')),
261 ('-x-1', NS(x='-1')),
262 ]
263
264
265class TestOptionalsSingleDashCombined(ParserTestCase):
266 """Test an Optional with a single-dash option string"""
267
268 argument_signatures = [
269 Sig('-x', action='store_true'),
270 Sig('-yyy', action='store_const', const=42),
271 Sig('-z'),
272 ]
273 failures = ['a', '--foo', '-xa', '-x --foo', '-x -z', '-z -x',
274 '-yx', '-yz a', '-yyyx', '-yyyza', '-xyza']
275 successes = [
276 ('', NS(x=False, yyy=None, z=None)),
277 ('-x', NS(x=True, yyy=None, z=None)),
278 ('-za', NS(x=False, yyy=None, z='a')),
279 ('-z a', NS(x=False, yyy=None, z='a')),
280 ('-xza', NS(x=True, yyy=None, z='a')),
281 ('-xz a', NS(x=True, yyy=None, z='a')),
282 ('-x -za', NS(x=True, yyy=None, z='a')),
283 ('-x -z a', NS(x=True, yyy=None, z='a')),
284 ('-y', NS(x=False, yyy=42, z=None)),
285 ('-yyy', NS(x=False, yyy=42, z=None)),
286 ('-x -yyy -za', NS(x=True, yyy=42, z='a')),
287 ('-x -yyy -z a', NS(x=True, yyy=42, z='a')),
288 ]
289
290
291class TestOptionalsSingleDashLong(ParserTestCase):
292 """Test an Optional with a multi-character single-dash option string"""
293
294 argument_signatures = [Sig('-foo')]
295 failures = ['-foo', 'a', '--foo', '-foo --foo', '-foo -y', '-fooa']
296 successes = [
297 ('', NS(foo=None)),
298 ('-foo a', NS(foo='a')),
299 ('-foo -1', NS(foo='-1')),
300 ('-fo a', NS(foo='a')),
301 ('-f a', NS(foo='a')),
302 ]
303
304
305class TestOptionalsSingleDashSubsetAmbiguous(ParserTestCase):
306 """Test Optionals where option strings are subsets of each other"""
307
308 argument_signatures = [Sig('-f'), Sig('-foobar'), Sig('-foorab')]
309 failures = ['-f', '-foo', '-fo', '-foo b', '-foob', '-fooba', '-foora']
310 successes = [
311 ('', NS(f=None, foobar=None, foorab=None)),
312 ('-f a', NS(f='a', foobar=None, foorab=None)),
313 ('-fa', NS(f='a', foobar=None, foorab=None)),
314 ('-foa', NS(f='oa', foobar=None, foorab=None)),
315 ('-fooa', NS(f='ooa', foobar=None, foorab=None)),
316 ('-foobar a', NS(f=None, foobar='a', foorab=None)),
317 ('-foorab a', NS(f=None, foobar=None, foorab='a')),
318 ]
319
320
321class TestOptionalsSingleDashAmbiguous(ParserTestCase):
322 """Test Optionals that partially match but are not subsets"""
323
324 argument_signatures = [Sig('-foobar'), Sig('-foorab')]
325 failures = ['-f', '-f a', '-fa', '-foa', '-foo', '-fo', '-foo b']
326 successes = [
327 ('', NS(foobar=None, foorab=None)),
328 ('-foob a', NS(foobar='a', foorab=None)),
329 ('-foor a', NS(foobar=None, foorab='a')),
330 ('-fooba a', NS(foobar='a', foorab=None)),
331 ('-foora a', NS(foobar=None, foorab='a')),
332 ('-foobar a', NS(foobar='a', foorab=None)),
333 ('-foorab a', NS(foobar=None, foorab='a')),
334 ]
335
336
337class TestOptionalsNumeric(ParserTestCase):
338 """Test an Optional with a short opt string"""
339
340 argument_signatures = [Sig('-1', dest='one')]
341 failures = ['-1', 'a', '-1 --foo', '-1 -y', '-1 -1', '-1 -2']
342 successes = [
343 ('', NS(one=None)),
344 ('-1 a', NS(one='a')),
345 ('-1a', NS(one='a')),
346 ('-1-2', NS(one='-2')),
347 ]
348
349
350class TestOptionalsDoubleDash(ParserTestCase):
351 """Test an Optional with a double-dash option string"""
352
353 argument_signatures = [Sig('--foo')]
354 failures = ['--foo', '-f', '-f a', 'a', '--foo -x', '--foo --bar']
355 successes = [
356 ('', NS(foo=None)),
357 ('--foo a', NS(foo='a')),
358 ('--foo=a', NS(foo='a')),
359 ('--foo -2.5', NS(foo='-2.5')),
360 ('--foo=-2.5', NS(foo='-2.5')),
361 ]
362
363
364class TestOptionalsDoubleDashPartialMatch(ParserTestCase):
365 """Tests partial matching with a double-dash option string"""
366
367 argument_signatures = [
368 Sig('--badger', action='store_true'),
369 Sig('--bat'),
370 ]
371 failures = ['--bar', '--b', '--ba', '--b=2', '--ba=4', '--badge 5']
372 successes = [
373 ('', NS(badger=False, bat=None)),
374 ('--bat X', NS(badger=False, bat='X')),
375 ('--bad', NS(badger=True, bat=None)),
376 ('--badg', NS(badger=True, bat=None)),
377 ('--badge', NS(badger=True, bat=None)),
378 ('--badger', NS(badger=True, bat=None)),
379 ]
380
381
382class TestOptionalsDoubleDashPrefixMatch(ParserTestCase):
383 """Tests when one double-dash option string is a prefix of another"""
384
385 argument_signatures = [
386 Sig('--badger', action='store_true'),
387 Sig('--ba'),
388 ]
389 failures = ['--bar', '--b', '--ba', '--b=2', '--badge 5']
390 successes = [
391 ('', NS(badger=False, ba=None)),
392 ('--ba X', NS(badger=False, ba='X')),
393 ('--ba=X', NS(badger=False, ba='X')),
394 ('--bad', NS(badger=True, ba=None)),
395 ('--badg', NS(badger=True, ba=None)),
396 ('--badge', NS(badger=True, ba=None)),
397 ('--badger', NS(badger=True, ba=None)),
398 ]
399
400
401class TestOptionalsSingleDoubleDash(ParserTestCase):
402 """Test an Optional with single- and double-dash option strings"""
403
404 argument_signatures = [
405 Sig('-f', action='store_true'),
406 Sig('--bar'),
407 Sig('-baz', action='store_const', const=42),
408 ]
409 failures = ['--bar', '-fbar', '-fbaz', '-bazf', '-b B', 'B']
410 successes = [
411 ('', NS(f=False, bar=None, baz=None)),
412 ('-f', NS(f=True, bar=None, baz=None)),
413 ('--ba B', NS(f=False, bar='B', baz=None)),
414 ('-f --bar B', NS(f=True, bar='B', baz=None)),
415 ('-f -b', NS(f=True, bar=None, baz=42)),
416 ('-ba -f', NS(f=True, bar=None, baz=42)),
417 ]
418
419
420class TestOptionalsAlternatePrefixChars(ParserTestCase):
R. David Murray88c49fe2010-08-03 17:56:09 +0000421 """Test an Optional with option strings with custom prefixes"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000422
423 parser_signature = Sig(prefix_chars='+:/', add_help=False)
424 argument_signatures = [
425 Sig('+f', action='store_true'),
426 Sig('::bar'),
427 Sig('/baz', action='store_const', const=42),
428 ]
R. David Murray88c49fe2010-08-03 17:56:09 +0000429 failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz', '-h', '--help', '+h', '::help', '/help']
430 successes = [
431 ('', NS(f=False, bar=None, baz=None)),
432 ('+f', NS(f=True, bar=None, baz=None)),
433 ('::ba B', NS(f=False, bar='B', baz=None)),
434 ('+f ::bar B', NS(f=True, bar='B', baz=None)),
435 ('+f /b', NS(f=True, bar=None, baz=42)),
436 ('/ba +f', NS(f=True, bar=None, baz=42)),
437 ]
438
439
440class TestOptionalsAlternatePrefixCharsAddedHelp(ParserTestCase):
441 """When ``-`` not in prefix_chars, default operators created for help
442 should use the prefix_chars in use rather than - or --
443 http://bugs.python.org/issue9444"""
444
445 parser_signature = Sig(prefix_chars='+:/', add_help=True)
446 argument_signatures = [
447 Sig('+f', action='store_true'),
448 Sig('::bar'),
449 Sig('/baz', action='store_const', const=42),
450 ]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000451 failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz']
452 successes = [
453 ('', NS(f=False, bar=None, baz=None)),
454 ('+f', NS(f=True, bar=None, baz=None)),
455 ('::ba B', NS(f=False, bar='B', baz=None)),
456 ('+f ::bar B', NS(f=True, bar='B', baz=None)),
457 ('+f /b', NS(f=True, bar=None, baz=42)),
R. David Murray88c49fe2010-08-03 17:56:09 +0000458 ('/ba +f', NS(f=True, bar=None, baz=42))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000459 ]
460
Steven Bethard1ca45a52010-11-01 15:57:36 +0000461
462class TestOptionalsAlternatePrefixCharsMultipleShortArgs(ParserTestCase):
463 """Verify that Optionals must be called with their defined prefixes"""
464
465 parser_signature = Sig(prefix_chars='+-', add_help=False)
466 argument_signatures = [
467 Sig('-x', action='store_true'),
468 Sig('+y', action='store_true'),
469 Sig('+z', action='store_true'),
470 ]
471 failures = ['-w',
472 '-xyz',
473 '+x',
474 '-y',
475 '+xyz',
476 ]
477 successes = [
478 ('', NS(x=False, y=False, z=False)),
479 ('-x', NS(x=True, y=False, z=False)),
480 ('+y -x', NS(x=True, y=True, z=False)),
481 ('+yz -x', NS(x=True, y=True, z=True)),
482 ]
483
484
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000485class TestOptionalsShortLong(ParserTestCase):
486 """Test a combination of single- and double-dash option strings"""
487
488 argument_signatures = [
489 Sig('-v', '--verbose', '-n', '--noisy', action='store_true'),
490 ]
491 failures = ['--x --verbose', '-N', 'a', '-v x']
492 successes = [
493 ('', NS(verbose=False)),
494 ('-v', NS(verbose=True)),
495 ('--verbose', NS(verbose=True)),
496 ('-n', NS(verbose=True)),
497 ('--noisy', NS(verbose=True)),
498 ]
499
500
501class TestOptionalsDest(ParserTestCase):
502 """Tests various means of setting destination"""
503
504 argument_signatures = [Sig('--foo-bar'), Sig('--baz', dest='zabbaz')]
505 failures = ['a']
506 successes = [
507 ('--foo-bar f', NS(foo_bar='f', zabbaz=None)),
508 ('--baz g', NS(foo_bar=None, zabbaz='g')),
509 ('--foo-bar h --baz i', NS(foo_bar='h', zabbaz='i')),
510 ('--baz j --foo-bar k', NS(foo_bar='k', zabbaz='j')),
511 ]
512
513
514class TestOptionalsDefault(ParserTestCase):
515 """Tests specifying a default for an Optional"""
516
517 argument_signatures = [Sig('-x'), Sig('-y', default=42)]
518 failures = ['a']
519 successes = [
520 ('', NS(x=None, y=42)),
521 ('-xx', NS(x='x', y=42)),
522 ('-yy', NS(x=None, y='y')),
523 ]
524
525
526class TestOptionalsNargsDefault(ParserTestCase):
527 """Tests not specifying the number of args for an Optional"""
528
529 argument_signatures = [Sig('-x')]
530 failures = ['a', '-x']
531 successes = [
532 ('', NS(x=None)),
533 ('-x a', NS(x='a')),
534 ]
535
536
537class TestOptionalsNargs1(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +0000538 """Tests specifying 1 arg for an Optional"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000539
540 argument_signatures = [Sig('-x', nargs=1)]
541 failures = ['a', '-x']
542 successes = [
543 ('', NS(x=None)),
544 ('-x a', NS(x=['a'])),
545 ]
546
547
548class TestOptionalsNargs3(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +0000549 """Tests specifying 3 args for an Optional"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000550
551 argument_signatures = [Sig('-x', nargs=3)]
552 failures = ['a', '-x', '-x a', '-x a b', 'a -x', 'a -x b']
553 successes = [
554 ('', NS(x=None)),
555 ('-x a b c', NS(x=['a', 'b', 'c'])),
556 ]
557
558
559class TestOptionalsNargsOptional(ParserTestCase):
560 """Tests specifying an Optional arg for an Optional"""
561
562 argument_signatures = [
563 Sig('-w', nargs='?'),
564 Sig('-x', nargs='?', const=42),
565 Sig('-y', nargs='?', default='spam'),
566 Sig('-z', nargs='?', type=int, const='42', default='84'),
567 ]
568 failures = ['2']
569 successes = [
570 ('', NS(w=None, x=None, y='spam', z=84)),
571 ('-w', NS(w=None, x=None, y='spam', z=84)),
572 ('-w 2', NS(w='2', x=None, y='spam', z=84)),
573 ('-x', NS(w=None, x=42, y='spam', z=84)),
574 ('-x 2', NS(w=None, x='2', y='spam', z=84)),
575 ('-y', NS(w=None, x=None, y=None, z=84)),
576 ('-y 2', NS(w=None, x=None, y='2', z=84)),
577 ('-z', NS(w=None, x=None, y='spam', z=42)),
578 ('-z 2', NS(w=None, x=None, y='spam', z=2)),
579 ]
580
581
582class TestOptionalsNargsZeroOrMore(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +0000583 """Tests specifying args for an Optional that accepts zero or more"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000584
585 argument_signatures = [
586 Sig('-x', nargs='*'),
587 Sig('-y', nargs='*', default='spam'),
588 ]
589 failures = ['a']
590 successes = [
591 ('', NS(x=None, y='spam')),
592 ('-x', NS(x=[], y='spam')),
593 ('-x a', NS(x=['a'], y='spam')),
594 ('-x a b', NS(x=['a', 'b'], y='spam')),
595 ('-y', NS(x=None, y=[])),
596 ('-y a', NS(x=None, y=['a'])),
597 ('-y a b', NS(x=None, y=['a', 'b'])),
598 ]
599
600
601class TestOptionalsNargsOneOrMore(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +0000602 """Tests specifying args for an Optional that accepts one or more"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000603
604 argument_signatures = [
605 Sig('-x', nargs='+'),
606 Sig('-y', nargs='+', default='spam'),
607 ]
608 failures = ['a', '-x', '-y', 'a -x', 'a -y b']
609 successes = [
610 ('', NS(x=None, y='spam')),
611 ('-x a', NS(x=['a'], y='spam')),
612 ('-x a b', NS(x=['a', 'b'], y='spam')),
613 ('-y a', NS(x=None, y=['a'])),
614 ('-y a b', NS(x=None, y=['a', 'b'])),
615 ]
616
617
618class TestOptionalsChoices(ParserTestCase):
619 """Tests specifying the choices for an Optional"""
620
621 argument_signatures = [
622 Sig('-f', choices='abc'),
623 Sig('-g', type=int, choices=range(5))]
624 failures = ['a', '-f d', '-fad', '-ga', '-g 6']
625 successes = [
626 ('', NS(f=None, g=None)),
627 ('-f a', NS(f='a', g=None)),
628 ('-f c', NS(f='c', g=None)),
629 ('-g 0', NS(f=None, g=0)),
630 ('-g 03', NS(f=None, g=3)),
631 ('-fb -g4', NS(f='b', g=4)),
632 ]
633
634
635class TestOptionalsRequired(ParserTestCase):
Benjamin Peterson82f34ad2015-01-13 09:17:24 -0500636 """Tests an optional action that is required"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000637
638 argument_signatures = [
639 Sig('-x', type=int, required=True),
640 ]
641 failures = ['a', '']
642 successes = [
643 ('-x 1', NS(x=1)),
644 ('-x42', NS(x=42)),
645 ]
646
647
648class TestOptionalsActionStore(ParserTestCase):
649 """Tests the store action for an Optional"""
650
651 argument_signatures = [Sig('-x', action='store')]
652 failures = ['a', 'a -x']
653 successes = [
654 ('', NS(x=None)),
655 ('-xfoo', NS(x='foo')),
656 ]
657
658
659class TestOptionalsActionStoreConst(ParserTestCase):
660 """Tests the store_const action for an Optional"""
661
662 argument_signatures = [Sig('-y', action='store_const', const=object)]
663 failures = ['a']
664 successes = [
665 ('', NS(y=None)),
666 ('-y', NS(y=object)),
667 ]
668
669
670class TestOptionalsActionStoreFalse(ParserTestCase):
671 """Tests the store_false action for an Optional"""
672
673 argument_signatures = [Sig('-z', action='store_false')]
674 failures = ['a', '-za', '-z a']
675 successes = [
676 ('', NS(z=True)),
677 ('-z', NS(z=False)),
678 ]
679
680
681class TestOptionalsActionStoreTrue(ParserTestCase):
682 """Tests the store_true action for an Optional"""
683
684 argument_signatures = [Sig('--apple', action='store_true')]
685 failures = ['a', '--apple=b', '--apple b']
686 successes = [
687 ('', NS(apple=False)),
688 ('--apple', NS(apple=True)),
689 ]
690
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200691class TestBooleanOptionalAction(ParserTestCase):
692 """Tests BooleanOptionalAction"""
693
694 argument_signatures = [Sig('--foo', action=argparse.BooleanOptionalAction)]
695 failures = ['--foo bar', '--foo=bar']
696 successes = [
697 ('', NS(foo=None)),
698 ('--foo', NS(foo=True)),
699 ('--no-foo', NS(foo=False)),
700 ('--foo --no-foo', NS(foo=False)), # useful for aliases
701 ('--no-foo --foo', NS(foo=True)),
702 ]
703
Rémi Lapeyreb084d1b2020-06-06 00:00:42 +0200704 def test_const(self):
705 # See bpo-40862
706 parser = argparse.ArgumentParser()
707 with self.assertRaises(TypeError) as cm:
708 parser.add_argument('--foo', const=True, action=argparse.BooleanOptionalAction)
709
710 self.assertIn("got an unexpected keyword argument 'const'", str(cm.exception))
711
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200712class TestBooleanOptionalActionRequired(ParserTestCase):
713 """Tests BooleanOptionalAction required"""
714
715 argument_signatures = [
716 Sig('--foo', required=True, action=argparse.BooleanOptionalAction)
717 ]
718 failures = ['']
719 successes = [
720 ('--foo', NS(foo=True)),
721 ('--no-foo', NS(foo=False)),
722 ]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000723
724class TestOptionalsActionAppend(ParserTestCase):
725 """Tests the append action for an Optional"""
726
727 argument_signatures = [Sig('--baz', action='append')]
728 failures = ['a', '--baz', 'a --baz', '--baz a b']
729 successes = [
730 ('', NS(baz=None)),
731 ('--baz a', NS(baz=['a'])),
732 ('--baz a --baz b', NS(baz=['a', 'b'])),
733 ]
734
735
736class TestOptionalsActionAppendWithDefault(ParserTestCase):
737 """Tests the append action for an Optional"""
738
739 argument_signatures = [Sig('--baz', action='append', default=['X'])]
740 failures = ['a', '--baz', 'a --baz', '--baz a b']
741 successes = [
742 ('', NS(baz=['X'])),
743 ('--baz a', NS(baz=['X', 'a'])),
744 ('--baz a --baz b', NS(baz=['X', 'a', 'b'])),
745 ]
746
747
748class TestOptionalsActionAppendConst(ParserTestCase):
749 """Tests the append_const action for an Optional"""
750
751 argument_signatures = [
752 Sig('-b', action='append_const', const=Exception),
753 Sig('-c', action='append', dest='b'),
754 ]
755 failures = ['a', '-c', 'a -c', '-bx', '-b x']
756 successes = [
757 ('', NS(b=None)),
758 ('-b', NS(b=[Exception])),
759 ('-b -cx -b -cyz', NS(b=[Exception, 'x', Exception, 'yz'])),
760 ]
761
762
763class TestOptionalsActionAppendConstWithDefault(ParserTestCase):
764 """Tests the append_const action for an Optional"""
765
766 argument_signatures = [
767 Sig('-b', action='append_const', const=Exception, default=['X']),
768 Sig('-c', action='append', dest='b'),
769 ]
770 failures = ['a', '-c', 'a -c', '-bx', '-b x']
771 successes = [
772 ('', NS(b=['X'])),
773 ('-b', NS(b=['X', Exception])),
774 ('-b -cx -b -cyz', NS(b=['X', Exception, 'x', Exception, 'yz'])),
775 ]
776
777
778class TestOptionalsActionCount(ParserTestCase):
779 """Tests the count action for an Optional"""
780
781 argument_signatures = [Sig('-x', action='count')]
782 failures = ['a', '-x a', '-x b', '-x a -x b']
783 successes = [
784 ('', NS(x=None)),
785 ('-x', NS(x=1)),
786 ]
787
788
Berker Peksag8089cd62015-02-14 01:39:17 +0200789class TestOptionalsAllowLongAbbreviation(ParserTestCase):
790 """Allow long options to be abbreviated unambiguously"""
791
792 argument_signatures = [
793 Sig('--foo'),
794 Sig('--foobaz'),
795 Sig('--fooble', action='store_true'),
796 ]
797 failures = ['--foob 5', '--foob']
798 successes = [
799 ('', NS(foo=None, foobaz=None, fooble=False)),
800 ('--foo 7', NS(foo='7', foobaz=None, fooble=False)),
801 ('--fooba a', NS(foo=None, foobaz='a', fooble=False)),
802 ('--foobl --foo g', NS(foo='g', foobaz=None, fooble=True)),
803 ]
804
805
806class TestOptionalsDisallowLongAbbreviation(ParserTestCase):
807 """Do not allow abbreviations of long options at all"""
808
809 parser_signature = Sig(allow_abbrev=False)
810 argument_signatures = [
811 Sig('--foo'),
812 Sig('--foodle', action='store_true'),
813 Sig('--foonly'),
814 ]
815 failures = ['-foon 3', '--foon 3', '--food', '--food --foo 2']
816 successes = [
817 ('', NS(foo=None, foodle=False, foonly=None)),
818 ('--foo 3', NS(foo='3', foodle=False, foonly=None)),
819 ('--foonly 7 --foodle --foo 2', NS(foo='2', foodle=True, foonly='7')),
820 ]
821
Zac Hatfield-Doddsdffca9e2019-07-14 00:35:58 -0500822
Kyle Meyer8edfc472020-02-18 04:48:57 -0500823class TestOptionalsDisallowLongAbbreviationPrefixChars(ParserTestCase):
824 """Disallowing abbreviations works with alternative prefix characters"""
825
826 parser_signature = Sig(prefix_chars='+', allow_abbrev=False)
827 argument_signatures = [
828 Sig('++foo'),
829 Sig('++foodle', action='store_true'),
830 Sig('++foonly'),
831 ]
832 failures = ['+foon 3', '++foon 3', '++food', '++food ++foo 2']
833 successes = [
834 ('', NS(foo=None, foodle=False, foonly=None)),
835 ('++foo 3', NS(foo='3', foodle=False, foonly=None)),
836 ('++foonly 7 ++foodle ++foo 2', NS(foo='2', foodle=True, foonly='7')),
837 ]
838
839
Zac Hatfield-Doddsdffca9e2019-07-14 00:35:58 -0500840class TestDisallowLongAbbreviationAllowsShortGrouping(ParserTestCase):
841 """Do not allow abbreviations of long options at all"""
842
843 parser_signature = Sig(allow_abbrev=False)
844 argument_signatures = [
845 Sig('-r'),
846 Sig('-c', action='count'),
847 ]
848 failures = ['-r', '-c -r']
849 successes = [
850 ('', NS(r=None, c=None)),
851 ('-ra', NS(r='a', c=None)),
852 ('-rcc', NS(r='cc', c=None)),
853 ('-cc', NS(r=None, c=2)),
854 ('-cc -ra', NS(r='a', c=2)),
855 ('-ccrcc', NS(r='cc', c=2)),
856 ]
857
Kyle Meyer8edfc472020-02-18 04:48:57 -0500858
859class TestDisallowLongAbbreviationAllowsShortGroupingPrefix(ParserTestCase):
860 """Short option grouping works with custom prefix and allow_abbrev=False"""
861
862 parser_signature = Sig(prefix_chars='+', allow_abbrev=False)
863 argument_signatures = [
864 Sig('+r'),
865 Sig('+c', action='count'),
866 ]
867 failures = ['+r', '+c +r']
868 successes = [
869 ('', NS(r=None, c=None)),
870 ('+ra', NS(r='a', c=None)),
871 ('+rcc', NS(r='cc', c=None)),
872 ('+cc', NS(r=None, c=2)),
873 ('+cc +ra', NS(r='a', c=2)),
874 ('+ccrcc', NS(r='cc', c=2)),
875 ]
876
877
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000878# ================
879# Positional tests
880# ================
881
882class TestPositionalsNargsNone(ParserTestCase):
883 """Test a Positional that doesn't specify nargs"""
884
885 argument_signatures = [Sig('foo')]
886 failures = ['', '-x', 'a b']
887 successes = [
888 ('a', NS(foo='a')),
889 ]
890
891
892class TestPositionalsNargs1(ParserTestCase):
893 """Test a Positional that specifies an nargs of 1"""
894
895 argument_signatures = [Sig('foo', nargs=1)]
896 failures = ['', '-x', 'a b']
897 successes = [
898 ('a', NS(foo=['a'])),
899 ]
900
901
902class TestPositionalsNargs2(ParserTestCase):
903 """Test a Positional that specifies an nargs of 2"""
904
905 argument_signatures = [Sig('foo', nargs=2)]
906 failures = ['', 'a', '-x', 'a b c']
907 successes = [
908 ('a b', NS(foo=['a', 'b'])),
909 ]
910
911
912class TestPositionalsNargsZeroOrMore(ParserTestCase):
913 """Test a Positional that specifies unlimited nargs"""
914
915 argument_signatures = [Sig('foo', nargs='*')]
916 failures = ['-x']
917 successes = [
918 ('', NS(foo=[])),
919 ('a', NS(foo=['a'])),
920 ('a b', NS(foo=['a', 'b'])),
921 ]
922
923
924class TestPositionalsNargsZeroOrMoreDefault(ParserTestCase):
925 """Test a Positional that specifies unlimited nargs and a default"""
926
927 argument_signatures = [Sig('foo', nargs='*', default='bar')]
928 failures = ['-x']
929 successes = [
930 ('', NS(foo='bar')),
931 ('a', NS(foo=['a'])),
932 ('a b', NS(foo=['a', 'b'])),
933 ]
934
935
936class TestPositionalsNargsOneOrMore(ParserTestCase):
937 """Test a Positional that specifies one or more nargs"""
938
939 argument_signatures = [Sig('foo', nargs='+')]
940 failures = ['', '-x']
941 successes = [
942 ('a', NS(foo=['a'])),
943 ('a b', NS(foo=['a', 'b'])),
944 ]
945
946
947class TestPositionalsNargsOptional(ParserTestCase):
948 """Tests an Optional Positional"""
949
950 argument_signatures = [Sig('foo', nargs='?')]
951 failures = ['-x', 'a b']
952 successes = [
953 ('', NS(foo=None)),
954 ('a', NS(foo='a')),
955 ]
956
957
958class TestPositionalsNargsOptionalDefault(ParserTestCase):
959 """Tests an Optional Positional with a default value"""
960
961 argument_signatures = [Sig('foo', nargs='?', default=42)]
962 failures = ['-x', 'a b']
963 successes = [
964 ('', NS(foo=42)),
965 ('a', NS(foo='a')),
966 ]
967
968
969class TestPositionalsNargsOptionalConvertedDefault(ParserTestCase):
970 """Tests an Optional Positional with a default value
971 that needs to be converted to the appropriate type.
972 """
973
974 argument_signatures = [
975 Sig('foo', nargs='?', type=int, default='42'),
976 ]
977 failures = ['-x', 'a b', '1 2']
978 successes = [
979 ('', NS(foo=42)),
980 ('1', NS(foo=1)),
981 ]
982
983
984class TestPositionalsNargsNoneNone(ParserTestCase):
985 """Test two Positionals that don't specify nargs"""
986
987 argument_signatures = [Sig('foo'), Sig('bar')]
988 failures = ['', '-x', 'a', 'a b c']
989 successes = [
990 ('a b', NS(foo='a', bar='b')),
991 ]
992
993
994class TestPositionalsNargsNone1(ParserTestCase):
995 """Test a Positional with no nargs followed by one with 1"""
996
997 argument_signatures = [Sig('foo'), Sig('bar', nargs=1)]
998 failures = ['', '--foo', 'a', 'a b c']
999 successes = [
1000 ('a b', NS(foo='a', bar=['b'])),
1001 ]
1002
1003
1004class TestPositionalsNargs2None(ParserTestCase):
1005 """Test a Positional with 2 nargs followed by one with none"""
1006
1007 argument_signatures = [Sig('foo', nargs=2), Sig('bar')]
1008 failures = ['', '--foo', 'a', 'a b', 'a b c d']
1009 successes = [
1010 ('a b c', NS(foo=['a', 'b'], bar='c')),
1011 ]
1012
1013
1014class TestPositionalsNargsNoneZeroOrMore(ParserTestCase):
1015 """Test a Positional with no nargs followed by one with unlimited"""
1016
1017 argument_signatures = [Sig('foo'), Sig('bar', nargs='*')]
1018 failures = ['', '--foo']
1019 successes = [
1020 ('a', NS(foo='a', bar=[])),
1021 ('a b', NS(foo='a', bar=['b'])),
1022 ('a b c', NS(foo='a', bar=['b', 'c'])),
1023 ]
1024
1025
1026class TestPositionalsNargsNoneOneOrMore(ParserTestCase):
1027 """Test a Positional with no nargs followed by one with one or more"""
1028
1029 argument_signatures = [Sig('foo'), Sig('bar', nargs='+')]
1030 failures = ['', '--foo', 'a']
1031 successes = [
1032 ('a b', NS(foo='a', bar=['b'])),
1033 ('a b c', NS(foo='a', bar=['b', 'c'])),
1034 ]
1035
1036
1037class TestPositionalsNargsNoneOptional(ParserTestCase):
1038 """Test a Positional with no nargs followed by one with an Optional"""
1039
1040 argument_signatures = [Sig('foo'), Sig('bar', nargs='?')]
1041 failures = ['', '--foo', 'a b c']
1042 successes = [
1043 ('a', NS(foo='a', bar=None)),
1044 ('a b', NS(foo='a', bar='b')),
1045 ]
1046
1047
1048class TestPositionalsNargsZeroOrMoreNone(ParserTestCase):
1049 """Test a Positional with unlimited nargs followed by one with none"""
1050
1051 argument_signatures = [Sig('foo', nargs='*'), Sig('bar')]
1052 failures = ['', '--foo']
1053 successes = [
1054 ('a', NS(foo=[], bar='a')),
1055 ('a b', NS(foo=['a'], bar='b')),
1056 ('a b c', NS(foo=['a', 'b'], bar='c')),
1057 ]
1058
1059
1060class TestPositionalsNargsOneOrMoreNone(ParserTestCase):
1061 """Test a Positional with one or more nargs followed by one with none"""
1062
1063 argument_signatures = [Sig('foo', nargs='+'), Sig('bar')]
1064 failures = ['', '--foo', 'a']
1065 successes = [
1066 ('a b', NS(foo=['a'], bar='b')),
1067 ('a b c', NS(foo=['a', 'b'], bar='c')),
1068 ]
1069
1070
1071class TestPositionalsNargsOptionalNone(ParserTestCase):
1072 """Test a Positional with an Optional nargs followed by one with none"""
1073
1074 argument_signatures = [Sig('foo', nargs='?', default=42), Sig('bar')]
1075 failures = ['', '--foo', 'a b c']
1076 successes = [
1077 ('a', NS(foo=42, bar='a')),
1078 ('a b', NS(foo='a', bar='b')),
1079 ]
1080
1081
1082class TestPositionalsNargs2ZeroOrMore(ParserTestCase):
1083 """Test a Positional with 2 nargs followed by one with unlimited"""
1084
1085 argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='*')]
1086 failures = ['', '--foo', 'a']
1087 successes = [
1088 ('a b', NS(foo=['a', 'b'], bar=[])),
1089 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1090 ]
1091
1092
1093class TestPositionalsNargs2OneOrMore(ParserTestCase):
1094 """Test a Positional with 2 nargs followed by one with one or more"""
1095
1096 argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='+')]
1097 failures = ['', '--foo', 'a', 'a b']
1098 successes = [
1099 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1100 ]
1101
1102
1103class TestPositionalsNargs2Optional(ParserTestCase):
1104 """Test a Positional with 2 nargs followed by one optional"""
1105
1106 argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='?')]
1107 failures = ['', '--foo', 'a', 'a b c d']
1108 successes = [
1109 ('a b', NS(foo=['a', 'b'], bar=None)),
1110 ('a b c', NS(foo=['a', 'b'], bar='c')),
1111 ]
1112
1113
1114class TestPositionalsNargsZeroOrMore1(ParserTestCase):
1115 """Test a Positional with unlimited nargs followed by one with 1"""
1116
1117 argument_signatures = [Sig('foo', nargs='*'), Sig('bar', nargs=1)]
1118 failures = ['', '--foo', ]
1119 successes = [
1120 ('a', NS(foo=[], bar=['a'])),
1121 ('a b', NS(foo=['a'], bar=['b'])),
1122 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1123 ]
1124
1125
1126class TestPositionalsNargsOneOrMore1(ParserTestCase):
1127 """Test a Positional with one or more nargs followed by one with 1"""
1128
1129 argument_signatures = [Sig('foo', nargs='+'), Sig('bar', nargs=1)]
1130 failures = ['', '--foo', 'a']
1131 successes = [
1132 ('a b', NS(foo=['a'], bar=['b'])),
1133 ('a b c', NS(foo=['a', 'b'], bar=['c'])),
1134 ]
1135
1136
1137class TestPositionalsNargsOptional1(ParserTestCase):
1138 """Test a Positional with an Optional nargs followed by one with 1"""
1139
1140 argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs=1)]
1141 failures = ['', '--foo', 'a b c']
1142 successes = [
1143 ('a', NS(foo=None, bar=['a'])),
1144 ('a b', NS(foo='a', bar=['b'])),
1145 ]
1146
1147
1148class TestPositionalsNargsNoneZeroOrMore1(ParserTestCase):
1149 """Test three Positionals: no nargs, unlimited nargs and 1 nargs"""
1150
1151 argument_signatures = [
1152 Sig('foo'),
1153 Sig('bar', nargs='*'),
1154 Sig('baz', nargs=1),
1155 ]
1156 failures = ['', '--foo', 'a']
1157 successes = [
1158 ('a b', NS(foo='a', bar=[], baz=['b'])),
1159 ('a b c', NS(foo='a', bar=['b'], baz=['c'])),
1160 ]
1161
1162
1163class TestPositionalsNargsNoneOneOrMore1(ParserTestCase):
1164 """Test three Positionals: no nargs, one or more nargs and 1 nargs"""
1165
1166 argument_signatures = [
1167 Sig('foo'),
1168 Sig('bar', nargs='+'),
1169 Sig('baz', nargs=1),
1170 ]
1171 failures = ['', '--foo', 'a', 'b']
1172 successes = [
1173 ('a b c', NS(foo='a', bar=['b'], baz=['c'])),
1174 ('a b c d', NS(foo='a', bar=['b', 'c'], baz=['d'])),
1175 ]
1176
1177
1178class TestPositionalsNargsNoneOptional1(ParserTestCase):
1179 """Test three Positionals: no nargs, optional narg and 1 nargs"""
1180
1181 argument_signatures = [
1182 Sig('foo'),
1183 Sig('bar', nargs='?', default=0.625),
1184 Sig('baz', nargs=1),
1185 ]
1186 failures = ['', '--foo', 'a']
1187 successes = [
1188 ('a b', NS(foo='a', bar=0.625, baz=['b'])),
1189 ('a b c', NS(foo='a', bar='b', baz=['c'])),
1190 ]
1191
1192
1193class TestPositionalsNargsOptionalOptional(ParserTestCase):
1194 """Test two optional nargs"""
1195
1196 argument_signatures = [
1197 Sig('foo', nargs='?'),
1198 Sig('bar', nargs='?', default=42),
1199 ]
1200 failures = ['--foo', 'a b c']
1201 successes = [
1202 ('', NS(foo=None, bar=42)),
1203 ('a', NS(foo='a', bar=42)),
1204 ('a b', NS(foo='a', bar='b')),
1205 ]
1206
1207
1208class TestPositionalsNargsOptionalZeroOrMore(ParserTestCase):
1209 """Test an Optional narg followed by unlimited nargs"""
1210
1211 argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs='*')]
1212 failures = ['--foo']
1213 successes = [
1214 ('', NS(foo=None, bar=[])),
1215 ('a', NS(foo='a', bar=[])),
1216 ('a b', NS(foo='a', bar=['b'])),
1217 ('a b c', NS(foo='a', bar=['b', 'c'])),
1218 ]
1219
1220
1221class TestPositionalsNargsOptionalOneOrMore(ParserTestCase):
1222 """Test an Optional narg followed by one or more nargs"""
1223
1224 argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs='+')]
1225 failures = ['', '--foo']
1226 successes = [
1227 ('a', NS(foo=None, bar=['a'])),
1228 ('a b', NS(foo='a', bar=['b'])),
1229 ('a b c', NS(foo='a', bar=['b', 'c'])),
1230 ]
1231
1232
1233class TestPositionalsChoicesString(ParserTestCase):
1234 """Test a set of single-character choices"""
1235
1236 argument_signatures = [Sig('spam', choices=set('abcdefg'))]
1237 failures = ['', '--foo', 'h', '42', 'ef']
1238 successes = [
1239 ('a', NS(spam='a')),
1240 ('g', NS(spam='g')),
1241 ]
1242
1243
1244class TestPositionalsChoicesInt(ParserTestCase):
1245 """Test a set of integer choices"""
1246
1247 argument_signatures = [Sig('spam', type=int, choices=range(20))]
1248 failures = ['', '--foo', 'h', '42', 'ef']
1249 successes = [
1250 ('4', NS(spam=4)),
1251 ('15', NS(spam=15)),
1252 ]
1253
1254
1255class TestPositionalsActionAppend(ParserTestCase):
1256 """Test the 'append' action"""
1257
1258 argument_signatures = [
1259 Sig('spam', action='append'),
1260 Sig('spam', action='append', nargs=2),
1261 ]
1262 failures = ['', '--foo', 'a', 'a b', 'a b c d']
1263 successes = [
1264 ('a b c', NS(spam=['a', ['b', 'c']])),
1265 ]
1266
1267# ========================================
1268# Combined optionals and positionals tests
1269# ========================================
1270
1271class TestOptionalsNumericAndPositionals(ParserTestCase):
1272 """Tests negative number args when numeric options are present"""
1273
1274 argument_signatures = [
1275 Sig('x', nargs='?'),
1276 Sig('-4', dest='y', action='store_true'),
1277 ]
1278 failures = ['-2', '-315']
1279 successes = [
1280 ('', NS(x=None, y=False)),
1281 ('a', NS(x='a', y=False)),
1282 ('-4', NS(x=None, y=True)),
1283 ('-4 a', NS(x='a', y=True)),
1284 ]
1285
1286
1287class TestOptionalsAlmostNumericAndPositionals(ParserTestCase):
1288 """Tests negative number args when almost numeric options are present"""
1289
1290 argument_signatures = [
1291 Sig('x', nargs='?'),
1292 Sig('-k4', dest='y', action='store_true'),
1293 ]
1294 failures = ['-k3']
1295 successes = [
1296 ('', NS(x=None, y=False)),
1297 ('-2', NS(x='-2', y=False)),
1298 ('a', NS(x='a', y=False)),
1299 ('-k4', NS(x=None, y=True)),
1300 ('-k4 a', NS(x='a', y=True)),
1301 ]
1302
1303
1304class TestEmptyAndSpaceContainingArguments(ParserTestCase):
1305
1306 argument_signatures = [
1307 Sig('x', nargs='?'),
1308 Sig('-y', '--yyy', dest='y'),
1309 ]
1310 failures = ['-y']
1311 successes = [
1312 ([''], NS(x='', y=None)),
1313 (['a badger'], NS(x='a badger', y=None)),
1314 (['-a badger'], NS(x='-a badger', y=None)),
1315 (['-y', ''], NS(x=None, y='')),
1316 (['-y', 'a badger'], NS(x=None, y='a badger')),
1317 (['-y', '-a badger'], NS(x=None, y='-a badger')),
1318 (['--yyy=a badger'], NS(x=None, y='a badger')),
1319 (['--yyy=-a badger'], NS(x=None, y='-a badger')),
1320 ]
1321
1322
1323class TestPrefixCharacterOnlyArguments(ParserTestCase):
1324
1325 parser_signature = Sig(prefix_chars='-+')
1326 argument_signatures = [
1327 Sig('-', dest='x', nargs='?', const='badger'),
1328 Sig('+', dest='y', type=int, default=42),
1329 Sig('-+-', dest='z', action='store_true'),
1330 ]
1331 failures = ['-y', '+ -']
1332 successes = [
1333 ('', NS(x=None, y=42, z=False)),
1334 ('-', NS(x='badger', y=42, z=False)),
1335 ('- X', NS(x='X', y=42, z=False)),
1336 ('+ -3', NS(x=None, y=-3, z=False)),
1337 ('-+-', NS(x=None, y=42, z=True)),
1338 ('- ===', NS(x='===', y=42, z=False)),
1339 ]
1340
1341
1342class TestNargsZeroOrMore(ParserTestCase):
Martin Pantercc71a792016-04-05 06:19:42 +00001343 """Tests specifying args for an Optional that accepts zero or more"""
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001344
1345 argument_signatures = [Sig('-x', nargs='*'), Sig('y', nargs='*')]
1346 failures = []
1347 successes = [
1348 ('', NS(x=None, y=[])),
1349 ('-x', NS(x=[], y=[])),
1350 ('-x a', NS(x=['a'], y=[])),
1351 ('-x a -- b', NS(x=['a'], y=['b'])),
1352 ('a', NS(x=None, y=['a'])),
1353 ('a -x', NS(x=[], y=['a'])),
1354 ('a -x b', NS(x=['b'], y=['a'])),
1355 ]
1356
1357
1358class TestNargsRemainder(ParserTestCase):
1359 """Tests specifying a positional with nargs=REMAINDER"""
1360
1361 argument_signatures = [Sig('x'), Sig('y', nargs='...'), Sig('-z')]
1362 failures = ['', '-z', '-z Z']
1363 successes = [
1364 ('X', NS(x='X', y=[], z=None)),
1365 ('-z Z X', NS(x='X', y=[], z='Z')),
1366 ('X A B -z Z', NS(x='X', y=['A', 'B', '-z', 'Z'], z=None)),
1367 ('X Y --foo', NS(x='X', y=['Y', '--foo'], z=None)),
1368 ]
1369
1370
1371class TestOptionLike(ParserTestCase):
1372 """Tests options that may or may not be arguments"""
1373
1374 argument_signatures = [
1375 Sig('-x', type=float),
1376 Sig('-3', type=float, dest='y'),
1377 Sig('z', nargs='*'),
1378 ]
1379 failures = ['-x', '-y2.5', '-xa', '-x -a',
1380 '-x -3', '-x -3.5', '-3 -3.5',
1381 '-x -2.5', '-x -2.5 a', '-3 -.5',
1382 'a x -1', '-x -1 a', '-3 -1 a']
1383 successes = [
1384 ('', NS(x=None, y=None, z=[])),
1385 ('-x 2.5', NS(x=2.5, y=None, z=[])),
1386 ('-x 2.5 a', NS(x=2.5, y=None, z=['a'])),
1387 ('-3.5', NS(x=None, y=0.5, z=[])),
1388 ('-3-.5', NS(x=None, y=-0.5, z=[])),
1389 ('-3 .5', NS(x=None, y=0.5, z=[])),
1390 ('a -3.5', NS(x=None, y=0.5, z=['a'])),
1391 ('a', NS(x=None, y=None, z=['a'])),
1392 ('a -x 1', NS(x=1.0, y=None, z=['a'])),
1393 ('-x 1 a', NS(x=1.0, y=None, z=['a'])),
1394 ('-3 1 a', NS(x=None, y=1.0, z=['a'])),
1395 ]
1396
1397
1398class TestDefaultSuppress(ParserTestCase):
1399 """Test actions with suppressed defaults"""
1400
1401 argument_signatures = [
1402 Sig('foo', nargs='?', default=argparse.SUPPRESS),
1403 Sig('bar', nargs='*', default=argparse.SUPPRESS),
1404 Sig('--baz', action='store_true', default=argparse.SUPPRESS),
1405 ]
1406 failures = ['-x']
1407 successes = [
1408 ('', NS()),
1409 ('a', NS(foo='a')),
1410 ('a b', NS(foo='a', bar=['b'])),
1411 ('--baz', NS(baz=True)),
1412 ('a --baz', NS(foo='a', baz=True)),
1413 ('--baz a b', NS(foo='a', bar=['b'], baz=True)),
1414 ]
1415
1416
1417class TestParserDefaultSuppress(ParserTestCase):
1418 """Test actions with a parser-level default of SUPPRESS"""
1419
1420 parser_signature = Sig(argument_default=argparse.SUPPRESS)
1421 argument_signatures = [
1422 Sig('foo', nargs='?'),
1423 Sig('bar', nargs='*'),
1424 Sig('--baz', action='store_true'),
1425 ]
1426 failures = ['-x']
1427 successes = [
1428 ('', NS()),
1429 ('a', NS(foo='a')),
1430 ('a b', NS(foo='a', bar=['b'])),
1431 ('--baz', NS(baz=True)),
1432 ('a --baz', NS(foo='a', baz=True)),
1433 ('--baz a b', NS(foo='a', bar=['b'], baz=True)),
1434 ]
1435
1436
1437class TestParserDefault42(ParserTestCase):
1438 """Test actions with a parser-level default of 42"""
1439
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001440 parser_signature = Sig(argument_default=42)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001441 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001442 Sig('--version', action='version', version='1.0'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001443 Sig('foo', nargs='?'),
1444 Sig('bar', nargs='*'),
1445 Sig('--baz', action='store_true'),
1446 ]
1447 failures = ['-x']
1448 successes = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001449 ('', NS(foo=42, bar=42, baz=42, version=42)),
1450 ('a', NS(foo='a', bar=42, baz=42, version=42)),
1451 ('a b', NS(foo='a', bar=['b'], baz=42, version=42)),
1452 ('--baz', NS(foo=42, bar=42, baz=True, version=42)),
1453 ('a --baz', NS(foo='a', bar=42, baz=True, version=42)),
1454 ('--baz a b', NS(foo='a', bar=['b'], baz=True, version=42)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001455 ]
1456
1457
1458class TestArgumentsFromFile(TempDirMixin, ParserTestCase):
1459 """Test reading arguments from a file"""
1460
1461 def setUp(self):
1462 super(TestArgumentsFromFile, self).setUp()
1463 file_texts = [
1464 ('hello', 'hello world!\n'),
1465 ('recursive', '-a\n'
1466 'A\n'
1467 '@hello'),
1468 ('invalid', '@no-such-path\n'),
1469 ]
1470 for path, text in file_texts:
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001471 with open(path, 'w', encoding="utf-8") as file:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001472 file.write(text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001473
1474 parser_signature = Sig(fromfile_prefix_chars='@')
1475 argument_signatures = [
1476 Sig('-a'),
1477 Sig('x'),
1478 Sig('y', nargs='+'),
1479 ]
1480 failures = ['', '-b', 'X', '@invalid', '@missing']
1481 successes = [
1482 ('X Y', NS(a=None, x='X', y=['Y'])),
1483 ('X -a A Y Z', NS(a='A', x='X', y=['Y', 'Z'])),
1484 ('@hello X', NS(a=None, x='hello world!', y=['X'])),
1485 ('X @hello', NS(a=None, x='X', y=['hello world!'])),
1486 ('-a B @recursive Y Z', NS(a='A', x='hello world!', y=['Y', 'Z'])),
1487 ('X @recursive Z -a B', NS(a='B', x='X', y=['hello world!', 'Z'])),
R David Murrayb94082a2012-07-21 22:20:11 -04001488 (["-a", "", "X", "Y"], NS(a='', x='X', y=['Y'])),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001489 ]
1490
1491
1492class TestArgumentsFromFileConverter(TempDirMixin, ParserTestCase):
1493 """Test reading arguments from a file"""
1494
1495 def setUp(self):
1496 super(TestArgumentsFromFileConverter, self).setUp()
1497 file_texts = [
1498 ('hello', 'hello world!\n'),
1499 ]
1500 for path, text in file_texts:
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001501 with open(path, 'w', encoding="utf-8") as file:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001502 file.write(text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001503
1504 class FromFileConverterArgumentParser(ErrorRaisingArgumentParser):
1505
1506 def convert_arg_line_to_args(self, arg_line):
1507 for arg in arg_line.split():
1508 if not arg.strip():
1509 continue
1510 yield arg
1511 parser_class = FromFileConverterArgumentParser
1512 parser_signature = Sig(fromfile_prefix_chars='@')
1513 argument_signatures = [
1514 Sig('y', nargs='+'),
1515 ]
1516 failures = []
1517 successes = [
1518 ('@hello X', NS(y=['hello', 'world!', 'X'])),
1519 ]
1520
1521
1522# =====================
1523# Type conversion tests
1524# =====================
1525
1526class TestFileTypeRepr(TestCase):
1527
1528 def test_r(self):
1529 type = argparse.FileType('r')
1530 self.assertEqual("FileType('r')", repr(type))
1531
1532 def test_wb_1(self):
1533 type = argparse.FileType('wb', 1)
1534 self.assertEqual("FileType('wb', 1)", repr(type))
1535
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001536 def test_r_latin(self):
1537 type = argparse.FileType('r', encoding='latin_1')
1538 self.assertEqual("FileType('r', encoding='latin_1')", repr(type))
1539
1540 def test_w_big5_ignore(self):
1541 type = argparse.FileType('w', encoding='big5', errors='ignore')
1542 self.assertEqual("FileType('w', encoding='big5', errors='ignore')",
1543 repr(type))
1544
1545 def test_r_1_replace(self):
1546 type = argparse.FileType('r', 1, errors='replace')
1547 self.assertEqual("FileType('r', 1, errors='replace')", repr(type))
1548
Steve Dowerd0f49d22018-09-18 09:10:26 -07001549class StdStreamComparer:
1550 def __init__(self, attr):
1551 self.attr = attr
1552
1553 def __eq__(self, other):
1554 return other == getattr(sys, self.attr)
1555
1556eq_stdin = StdStreamComparer('stdin')
1557eq_stdout = StdStreamComparer('stdout')
1558eq_stderr = StdStreamComparer('stderr')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001559
1560class RFile(object):
1561 seen = {}
1562
1563 def __init__(self, name):
1564 self.name = name
1565
1566 def __eq__(self, other):
1567 if other in self.seen:
1568 text = self.seen[other]
1569 else:
1570 text = self.seen[other] = other.read()
1571 other.close()
1572 if not isinstance(text, str):
1573 text = text.decode('ascii')
1574 return self.name == other.name == text
1575
1576
1577class TestFileTypeR(TempDirMixin, ParserTestCase):
1578 """Test the FileType option/argument type for reading files"""
1579
1580 def setUp(self):
1581 super(TestFileTypeR, self).setUp()
1582 for file_name in ['foo', 'bar']:
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001583 with open(os.path.join(self.temp_dir, file_name),
1584 'w', encoding="utf-8") as file:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001585 file.write(file_name)
Steven Bethardb0270112011-01-24 21:02:50 +00001586 self.create_readonly_file('readonly')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001587
1588 argument_signatures = [
1589 Sig('-x', type=argparse.FileType()),
1590 Sig('spam', type=argparse.FileType('r')),
1591 ]
Steven Bethardb0270112011-01-24 21:02:50 +00001592 failures = ['-x', '', 'non-existent-file.txt']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001593 successes = [
1594 ('foo', NS(x=None, spam=RFile('foo'))),
1595 ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
1596 ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001597 ('-x - -', NS(x=eq_stdin, spam=eq_stdin)),
Steven Bethardb0270112011-01-24 21:02:50 +00001598 ('readonly', NS(x=None, spam=RFile('readonly'))),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001599 ]
1600
R David Murray6fb8fb12012-08-31 22:45:20 -04001601class TestFileTypeDefaults(TempDirMixin, ParserTestCase):
1602 """Test that a file is not created unless the default is needed"""
1603 def setUp(self):
1604 super(TestFileTypeDefaults, self).setUp()
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001605 file = open(os.path.join(self.temp_dir, 'good'), 'w', encoding="utf-8")
R David Murray6fb8fb12012-08-31 22:45:20 -04001606 file.write('good')
1607 file.close()
1608
1609 argument_signatures = [
1610 Sig('-c', type=argparse.FileType('r'), default='no-file.txt'),
1611 ]
1612 # should provoke no such file error
1613 failures = ['']
1614 # should not provoke error because default file is created
1615 successes = [('-c good', NS(c=RFile('good')))]
1616
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001617
1618class TestFileTypeRB(TempDirMixin, ParserTestCase):
1619 """Test the FileType option/argument type for reading files"""
1620
1621 def setUp(self):
1622 super(TestFileTypeRB, self).setUp()
1623 for file_name in ['foo', 'bar']:
Inada Naoki8bbfeb32021-04-02 12:53:46 +09001624 with open(os.path.join(self.temp_dir, file_name),
1625 'w', encoding="utf-8") as file:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +02001626 file.write(file_name)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001627
1628 argument_signatures = [
1629 Sig('-x', type=argparse.FileType('rb')),
1630 Sig('spam', type=argparse.FileType('rb')),
1631 ]
1632 failures = ['-x', '']
1633 successes = [
1634 ('foo', NS(x=None, spam=RFile('foo'))),
1635 ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
1636 ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001637 ('-x - -', NS(x=eq_stdin, spam=eq_stdin)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001638 ]
1639
1640
1641class WFile(object):
1642 seen = set()
1643
1644 def __init__(self, name):
1645 self.name = name
1646
1647 def __eq__(self, other):
1648 if other not in self.seen:
1649 text = 'Check that file is writable.'
1650 if 'b' in other.mode:
1651 text = text.encode('ascii')
1652 other.write(text)
1653 other.close()
1654 self.seen.add(other)
1655 return self.name == other.name
1656
1657
Victor Stinnera04b39b2011-11-20 23:09:09 +01001658@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
1659 "non-root user required")
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001660class TestFileTypeW(TempDirMixin, ParserTestCase):
1661 """Test the FileType option/argument type for writing files"""
1662
Steven Bethardb0270112011-01-24 21:02:50 +00001663 def setUp(self):
1664 super(TestFileTypeW, self).setUp()
1665 self.create_readonly_file('readonly')
1666
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001667 argument_signatures = [
1668 Sig('-x', type=argparse.FileType('w')),
1669 Sig('spam', type=argparse.FileType('w')),
1670 ]
Steven Bethardb0270112011-01-24 21:02:50 +00001671 failures = ['-x', '', 'readonly']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001672 successes = [
1673 ('foo', NS(x=None, spam=WFile('foo'))),
1674 ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
1675 ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001676 ('-x - -', NS(x=eq_stdout, spam=eq_stdout)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001677 ]
1678
1679
1680class TestFileTypeWB(TempDirMixin, ParserTestCase):
1681
1682 argument_signatures = [
1683 Sig('-x', type=argparse.FileType('wb')),
1684 Sig('spam', type=argparse.FileType('wb')),
1685 ]
1686 failures = ['-x', '']
1687 successes = [
1688 ('foo', NS(x=None, spam=WFile('foo'))),
1689 ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
1690 ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))),
Steve Dowerd0f49d22018-09-18 09:10:26 -07001691 ('-x - -', NS(x=eq_stdout, spam=eq_stdout)),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001692 ]
1693
1694
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001695class TestFileTypeOpenArgs(TestCase):
1696 """Test that open (the builtin) is correctly called"""
1697
1698 def test_open_args(self):
1699 FT = argparse.FileType
1700 cases = [
1701 (FT('rb'), ('rb', -1, None, None)),
1702 (FT('w', 1), ('w', 1, None, None)),
1703 (FT('w', errors='replace'), ('w', -1, None, 'replace')),
1704 (FT('wb', encoding='big5'), ('wb', -1, 'big5', None)),
1705 (FT('w', 0, 'l1', 'strict'), ('w', 0, 'l1', 'strict')),
1706 ]
1707 with mock.patch('builtins.open') as m:
1708 for type, args in cases:
1709 type('foo')
1710 m.assert_called_with('foo', *args)
1711
1712
zygocephalus03d58312019-06-07 23:08:36 +03001713class TestFileTypeMissingInitialization(TestCase):
1714 """
1715 Test that add_argument throws an error if FileType class
1716 object was passed instead of instance of FileType
1717 """
1718
1719 def test(self):
1720 parser = argparse.ArgumentParser()
1721 with self.assertRaises(ValueError) as cm:
1722 parser.add_argument('-x', type=argparse.FileType)
1723
1724 self.assertEqual(
1725 '%r is a FileType class object, instance of it must be passed'
1726 % (argparse.FileType,),
1727 str(cm.exception)
1728 )
1729
1730
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001731class TestTypeCallable(ParserTestCase):
1732 """Test some callables as option/argument types"""
1733
1734 argument_signatures = [
1735 Sig('--eggs', type=complex),
1736 Sig('spam', type=float),
1737 ]
1738 failures = ['a', '42j', '--eggs a', '--eggs 2i']
1739 successes = [
1740 ('--eggs=42 42', NS(eggs=42, spam=42.0)),
1741 ('--eggs 2j -- -1.5', NS(eggs=2j, spam=-1.5)),
1742 ('1024.675', NS(eggs=None, spam=1024.675)),
1743 ]
1744
1745
1746class TestTypeUserDefined(ParserTestCase):
1747 """Test a user-defined option/argument type"""
1748
1749 class MyType(TestCase):
1750
1751 def __init__(self, value):
1752 self.value = value
1753
1754 def __eq__(self, other):
1755 return (type(self), self.value) == (type(other), other.value)
1756
1757 argument_signatures = [
1758 Sig('-x', type=MyType),
1759 Sig('spam', type=MyType),
1760 ]
1761 failures = []
1762 successes = [
1763 ('a -x b', NS(x=MyType('b'), spam=MyType('a'))),
1764 ('-xf g', NS(x=MyType('f'), spam=MyType('g'))),
1765 ]
1766
1767
1768class TestTypeClassicClass(ParserTestCase):
1769 """Test a classic class type"""
1770
1771 class C:
1772
1773 def __init__(self, value):
1774 self.value = value
1775
1776 def __eq__(self, other):
1777 return (type(self), self.value) == (type(other), other.value)
1778
1779 argument_signatures = [
1780 Sig('-x', type=C),
1781 Sig('spam', type=C),
1782 ]
1783 failures = []
1784 successes = [
1785 ('a -x b', NS(x=C('b'), spam=C('a'))),
1786 ('-xf g', NS(x=C('f'), spam=C('g'))),
1787 ]
1788
1789
1790class TestTypeRegistration(TestCase):
1791 """Test a user-defined type by registering it"""
1792
1793 def test(self):
1794
1795 def get_my_type(string):
1796 return 'my_type{%s}' % string
1797
1798 parser = argparse.ArgumentParser()
1799 parser.register('type', 'my_type', get_my_type)
1800 parser.add_argument('-x', type='my_type')
1801 parser.add_argument('y', type='my_type')
1802
1803 self.assertEqual(parser.parse_args('1'.split()),
1804 NS(x=None, y='my_type{1}'))
1805 self.assertEqual(parser.parse_args('-x 1 42'.split()),
1806 NS(x='my_type{1}', y='my_type{42}'))
1807
1808
1809# ============
1810# Action tests
1811# ============
1812
1813class TestActionUserDefined(ParserTestCase):
1814 """Test a user-defined option/argument action"""
1815
1816 class OptionalAction(argparse.Action):
1817
1818 def __call__(self, parser, namespace, value, option_string=None):
1819 try:
1820 # check destination and option string
1821 assert self.dest == 'spam', 'dest: %s' % self.dest
1822 assert option_string == '-s', 'flag: %s' % option_string
1823 # when option is before argument, badger=2, and when
1824 # option is after argument, badger=<whatever was set>
1825 expected_ns = NS(spam=0.25)
1826 if value in [0.125, 0.625]:
1827 expected_ns.badger = 2
1828 elif value in [2.0]:
1829 expected_ns.badger = 84
1830 else:
1831 raise AssertionError('value: %s' % value)
1832 assert expected_ns == namespace, ('expected %s, got %s' %
1833 (expected_ns, namespace))
1834 except AssertionError:
1835 e = sys.exc_info()[1]
1836 raise ArgumentParserError('opt_action failed: %s' % e)
1837 setattr(namespace, 'spam', value)
1838
1839 class PositionalAction(argparse.Action):
1840
1841 def __call__(self, parser, namespace, value, option_string=None):
1842 try:
1843 assert option_string is None, ('option_string: %s' %
1844 option_string)
1845 # check destination
1846 assert self.dest == 'badger', 'dest: %s' % self.dest
1847 # when argument is before option, spam=0.25, and when
1848 # option is after argument, spam=<whatever was set>
1849 expected_ns = NS(badger=2)
1850 if value in [42, 84]:
1851 expected_ns.spam = 0.25
1852 elif value in [1]:
1853 expected_ns.spam = 0.625
1854 elif value in [2]:
1855 expected_ns.spam = 0.125
1856 else:
1857 raise AssertionError('value: %s' % value)
1858 assert expected_ns == namespace, ('expected %s, got %s' %
1859 (expected_ns, namespace))
1860 except AssertionError:
1861 e = sys.exc_info()[1]
1862 raise ArgumentParserError('arg_action failed: %s' % e)
1863 setattr(namespace, 'badger', value)
1864
1865 argument_signatures = [
1866 Sig('-s', dest='spam', action=OptionalAction,
1867 type=float, default=0.25),
1868 Sig('badger', action=PositionalAction,
1869 type=int, nargs='?', default=2),
1870 ]
1871 failures = []
1872 successes = [
1873 ('-s0.125', NS(spam=0.125, badger=2)),
1874 ('42', NS(spam=0.25, badger=42)),
1875 ('-s 0.625 1', NS(spam=0.625, badger=1)),
1876 ('84 -s2', NS(spam=2.0, badger=84)),
1877 ]
1878
1879
1880class TestActionRegistration(TestCase):
1881 """Test a user-defined action supplied by registering it"""
1882
1883 class MyAction(argparse.Action):
1884
1885 def __call__(self, parser, namespace, values, option_string=None):
1886 setattr(namespace, self.dest, 'foo[%s]' % values)
1887
1888 def test(self):
1889
1890 parser = argparse.ArgumentParser()
1891 parser.register('action', 'my_action', self.MyAction)
1892 parser.add_argument('badger', action='my_action')
1893
1894 self.assertEqual(parser.parse_args(['1']), NS(badger='foo[1]'))
1895 self.assertEqual(parser.parse_args(['42']), NS(badger='foo[42]'))
1896
1897
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001898class TestActionExtend(ParserTestCase):
1899 argument_signatures = [
1900 Sig('--foo', action="extend", nargs="+", type=str),
1901 ]
1902 failures = ()
1903 successes = [
1904 ('--foo f1 --foo f2 f3 f4', NS(foo=['f1', 'f2', 'f3', 'f4'])),
1905 ]
1906
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001907# ================
1908# Subparsers tests
1909# ================
1910
1911class TestAddSubparsers(TestCase):
1912 """Test the add_subparsers method"""
1913
1914 def assertArgumentParserError(self, *args, **kwargs):
1915 self.assertRaises(ArgumentParserError, *args, **kwargs)
1916
Steven Bethardfd311a72010-12-18 11:19:23 +00001917 def _get_parser(self, subparser_help=False, prefix_chars=None,
1918 aliases=False):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001919 # create a parser with a subparsers argument
R. David Murray88c49fe2010-08-03 17:56:09 +00001920 if prefix_chars:
1921 parser = ErrorRaisingArgumentParser(
1922 prog='PROG', description='main description', prefix_chars=prefix_chars)
1923 parser.add_argument(
1924 prefix_chars[0] * 2 + 'foo', action='store_true', help='foo help')
1925 else:
1926 parser = ErrorRaisingArgumentParser(
1927 prog='PROG', description='main description')
1928 parser.add_argument(
1929 '--foo', action='store_true', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001930 parser.add_argument(
1931 'bar', type=float, help='bar help')
1932
1933 # check that only one subparsers argument can be added
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001934 subparsers_kwargs = {'required': False}
Steven Bethardfd311a72010-12-18 11:19:23 +00001935 if aliases:
1936 subparsers_kwargs['metavar'] = 'COMMAND'
1937 subparsers_kwargs['title'] = 'commands'
1938 else:
1939 subparsers_kwargs['help'] = 'command help'
1940 subparsers = parser.add_subparsers(**subparsers_kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001941 self.assertArgumentParserError(parser.add_subparsers)
1942
1943 # add first sub-parser
1944 parser1_kwargs = dict(description='1 description')
1945 if subparser_help:
1946 parser1_kwargs['help'] = '1 help'
Steven Bethardfd311a72010-12-18 11:19:23 +00001947 if aliases:
1948 parser1_kwargs['aliases'] = ['1alias1', '1alias2']
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001949 parser1 = subparsers.add_parser('1', **parser1_kwargs)
1950 parser1.add_argument('-w', type=int, help='w help')
1951 parser1.add_argument('x', choices='abc', help='x help')
1952
1953 # add second sub-parser
1954 parser2_kwargs = dict(description='2 description')
1955 if subparser_help:
1956 parser2_kwargs['help'] = '2 help'
1957 parser2 = subparsers.add_parser('2', **parser2_kwargs)
1958 parser2.add_argument('-y', choices='123', help='y help')
1959 parser2.add_argument('z', type=complex, nargs='*', help='z help')
1960
R David Murray00528e82012-07-21 22:48:35 -04001961 # add third sub-parser
1962 parser3_kwargs = dict(description='3 description')
1963 if subparser_help:
1964 parser3_kwargs['help'] = '3 help'
1965 parser3 = subparsers.add_parser('3', **parser3_kwargs)
1966 parser3.add_argument('t', type=int, help='t help')
1967 parser3.add_argument('u', nargs='...', help='u help')
1968
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001969 # return the main parser
1970 return parser
1971
1972 def setUp(self):
Steven Bethard1f1c2472010-11-01 13:56:09 +00001973 super().setUp()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001974 self.parser = self._get_parser()
1975 self.command_help_parser = self._get_parser(subparser_help=True)
1976
1977 def test_parse_args_failures(self):
1978 # check some failure cases:
1979 for args_str in ['', 'a', 'a a', '0.5 a', '0.5 1',
1980 '0.5 1 -y', '0.5 2 -w']:
1981 args = args_str.split()
1982 self.assertArgumentParserError(self.parser.parse_args, args)
1983
1984 def test_parse_args(self):
1985 # check some non-failure cases:
1986 self.assertEqual(
1987 self.parser.parse_args('0.5 1 b -w 7'.split()),
1988 NS(foo=False, bar=0.5, w=7, x='b'),
1989 )
1990 self.assertEqual(
1991 self.parser.parse_args('0.25 --foo 2 -y 2 3j -- -1j'.split()),
1992 NS(foo=True, bar=0.25, y='2', z=[3j, -1j]),
1993 )
1994 self.assertEqual(
1995 self.parser.parse_args('--foo 0.125 1 c'.split()),
1996 NS(foo=True, bar=0.125, w=None, x='c'),
1997 )
R David Murray00528e82012-07-21 22:48:35 -04001998 self.assertEqual(
1999 self.parser.parse_args('-1.5 3 11 -- a --foo 7 -- b'.split()),
2000 NS(foo=False, bar=-1.5, t=11, u=['a', '--foo', '7', '--', 'b']),
2001 )
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002002
Steven Bethardfca2e8a2010-11-02 12:47:22 +00002003 def test_parse_known_args(self):
2004 self.assertEqual(
2005 self.parser.parse_known_args('0.5 1 b -w 7'.split()),
2006 (NS(foo=False, bar=0.5, w=7, x='b'), []),
2007 )
2008 self.assertEqual(
2009 self.parser.parse_known_args('0.5 -p 1 b -w 7'.split()),
2010 (NS(foo=False, bar=0.5, w=7, x='b'), ['-p']),
2011 )
2012 self.assertEqual(
2013 self.parser.parse_known_args('0.5 1 b -w 7 -p'.split()),
2014 (NS(foo=False, bar=0.5, w=7, x='b'), ['-p']),
2015 )
2016 self.assertEqual(
2017 self.parser.parse_known_args('0.5 1 b -q -rs -w 7'.split()),
2018 (NS(foo=False, bar=0.5, w=7, x='b'), ['-q', '-rs']),
2019 )
2020 self.assertEqual(
2021 self.parser.parse_known_args('0.5 -W 1 b -X Y -w 7 Z'.split()),
2022 (NS(foo=False, bar=0.5, w=7, x='b'), ['-W', '-X', 'Y', 'Z']),
2023 )
2024
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002025 def test_dest(self):
2026 parser = ErrorRaisingArgumentParser()
2027 parser.add_argument('--foo', action='store_true')
2028 subparsers = parser.add_subparsers(dest='bar')
2029 parser1 = subparsers.add_parser('1')
2030 parser1.add_argument('baz')
2031 self.assertEqual(NS(foo=False, bar='1', baz='2'),
2032 parser.parse_args('1 2'.split()))
2033
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07002034 def _test_required_subparsers(self, parser):
2035 # Should parse the sub command
2036 ret = parser.parse_args(['run'])
2037 self.assertEqual(ret.command, 'run')
2038
2039 # Error when the command is missing
2040 self.assertArgumentParserError(parser.parse_args, ())
2041
2042 def test_required_subparsers_via_attribute(self):
2043 parser = ErrorRaisingArgumentParser()
2044 subparsers = parser.add_subparsers(dest='command')
2045 subparsers.required = True
2046 subparsers.add_parser('run')
2047 self._test_required_subparsers(parser)
2048
2049 def test_required_subparsers_via_kwarg(self):
2050 parser = ErrorRaisingArgumentParser()
2051 subparsers = parser.add_subparsers(dest='command', required=True)
2052 subparsers.add_parser('run')
2053 self._test_required_subparsers(parser)
2054
2055 def test_required_subparsers_default(self):
2056 parser = ErrorRaisingArgumentParser()
2057 subparsers = parser.add_subparsers(dest='command')
2058 subparsers.add_parser('run')
Ned Deily8ebf5ce2018-05-23 21:55:15 -04002059 # No error here
2060 ret = parser.parse_args(())
2061 self.assertIsNone(ret.command)
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07002062
2063 def test_optional_subparsers(self):
2064 parser = ErrorRaisingArgumentParser()
2065 subparsers = parser.add_subparsers(dest='command', required=False)
2066 subparsers.add_parser('run')
2067 # No error here
2068 ret = parser.parse_args(())
2069 self.assertIsNone(ret.command)
2070
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002071 def test_help(self):
2072 self.assertEqual(self.parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002073 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002074 self.assertEqual(self.parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002075 usage: PROG [-h] [--foo] bar {1,2,3} ...
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002076
2077 main description
2078
2079 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002080 bar bar help
2081 {1,2,3} command help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002082
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002083 options:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002084 -h, --help show this help message and exit
2085 --foo foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002086 '''))
2087
R. David Murray88c49fe2010-08-03 17:56:09 +00002088 def test_help_extra_prefix_chars(self):
2089 # Make sure - is still used for help if it is a non-first prefix char
2090 parser = self._get_parser(prefix_chars='+:-')
2091 self.assertEqual(parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002092 'usage: PROG [-h] [++foo] bar {1,2,3} ...\n')
R. David Murray88c49fe2010-08-03 17:56:09 +00002093 self.assertEqual(parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002094 usage: PROG [-h] [++foo] bar {1,2,3} ...
R. David Murray88c49fe2010-08-03 17:56:09 +00002095
2096 main description
2097
2098 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002099 bar bar help
2100 {1,2,3} command help
R. David Murray88c49fe2010-08-03 17:56:09 +00002101
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002102 options:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002103 -h, --help show this help message and exit
2104 ++foo foo help
R. David Murray88c49fe2010-08-03 17:56:09 +00002105 '''))
2106
Xiang Zhang7fe28ad2017-01-22 14:37:22 +08002107 def test_help_non_breaking_spaces(self):
2108 parser = ErrorRaisingArgumentParser(
2109 prog='PROG', description='main description')
2110 parser.add_argument(
2111 "--non-breaking", action='store_false',
2112 help='help message containing non-breaking spaces shall not '
2113 'wrap\N{NO-BREAK SPACE}at non-breaking spaces')
2114 self.assertEqual(parser.format_help(), textwrap.dedent('''\
2115 usage: PROG [-h] [--non-breaking]
2116
2117 main description
2118
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002119 options:
Xiang Zhang7fe28ad2017-01-22 14:37:22 +08002120 -h, --help show this help message and exit
2121 --non-breaking help message containing non-breaking spaces shall not
2122 wrap\N{NO-BREAK SPACE}at non-breaking spaces
2123 '''))
R. David Murray88c49fe2010-08-03 17:56:09 +00002124
2125 def test_help_alternate_prefix_chars(self):
2126 parser = self._get_parser(prefix_chars='+:/')
2127 self.assertEqual(parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002128 'usage: PROG [+h] [++foo] bar {1,2,3} ...\n')
R. David Murray88c49fe2010-08-03 17:56:09 +00002129 self.assertEqual(parser.format_help(), textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002130 usage: PROG [+h] [++foo] bar {1,2,3} ...
R. David Murray88c49fe2010-08-03 17:56:09 +00002131
2132 main description
2133
2134 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002135 bar bar help
2136 {1,2,3} command help
R. David Murray88c49fe2010-08-03 17:56:09 +00002137
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002138 options:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002139 +h, ++help show this help message and exit
2140 ++foo foo help
R. David Murray88c49fe2010-08-03 17:56:09 +00002141 '''))
2142
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002143 def test_parser_command_help(self):
2144 self.assertEqual(self.command_help_parser.format_usage(),
Vinay Sajip9ae50502016-08-23 08:43:16 +01002145 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002146 self.assertEqual(self.command_help_parser.format_help(),
2147 textwrap.dedent('''\
Vinay Sajip9ae50502016-08-23 08:43:16 +01002148 usage: PROG [-h] [--foo] bar {1,2,3} ...
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002149
2150 main description
2151
2152 positional arguments:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002153 bar bar help
2154 {1,2,3} command help
2155 1 1 help
2156 2 2 help
2157 3 3 help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002158
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002159 options:
Vinay Sajip9ae50502016-08-23 08:43:16 +01002160 -h, --help show this help message and exit
2161 --foo foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002162 '''))
2163
2164 def test_subparser_title_help(self):
2165 parser = ErrorRaisingArgumentParser(prog='PROG',
2166 description='main description')
2167 parser.add_argument('--foo', action='store_true', help='foo help')
2168 parser.add_argument('bar', help='bar help')
2169 subparsers = parser.add_subparsers(title='subcommands',
2170 description='command help',
2171 help='additional text')
2172 parser1 = subparsers.add_parser('1')
2173 parser2 = subparsers.add_parser('2')
2174 self.assertEqual(parser.format_usage(),
2175 'usage: PROG [-h] [--foo] bar {1,2} ...\n')
2176 self.assertEqual(parser.format_help(), textwrap.dedent('''\
2177 usage: PROG [-h] [--foo] bar {1,2} ...
2178
2179 main description
2180
2181 positional arguments:
2182 bar bar help
2183
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002184 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002185 -h, --help show this help message and exit
2186 --foo foo help
2187
2188 subcommands:
2189 command help
2190
2191 {1,2} additional text
2192 '''))
2193
2194 def _test_subparser_help(self, args_str, expected_help):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002195 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002196 self.parser.parse_args(args_str.split())
Berker Peksag1c5f56a2014-07-06 09:33:20 +03002197 self.assertEqual(expected_help, cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002198
2199 def test_subparser1_help(self):
2200 self._test_subparser_help('5.0 1 -h', textwrap.dedent('''\
2201 usage: PROG bar 1 [-h] [-w W] {a,b,c}
2202
2203 1 description
2204
2205 positional arguments:
2206 {a,b,c} x help
2207
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002208 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002209 -h, --help show this help message and exit
2210 -w W w help
2211 '''))
2212
2213 def test_subparser2_help(self):
2214 self._test_subparser_help('5.0 2 -h', textwrap.dedent('''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08002215 usage: PROG bar 2 [-h] [-y {1,2,3}] [z ...]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002216
2217 2 description
2218
2219 positional arguments:
2220 z z help
2221
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002222 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002223 -h, --help show this help message and exit
2224 -y {1,2,3} y help
2225 '''))
2226
Steven Bethardfd311a72010-12-18 11:19:23 +00002227 def test_alias_invocation(self):
2228 parser = self._get_parser(aliases=True)
2229 self.assertEqual(
2230 parser.parse_known_args('0.5 1alias1 b'.split()),
2231 (NS(foo=False, bar=0.5, w=None, x='b'), []),
2232 )
2233 self.assertEqual(
2234 parser.parse_known_args('0.5 1alias2 b'.split()),
2235 (NS(foo=False, bar=0.5, w=None, x='b'), []),
2236 )
2237
2238 def test_error_alias_invocation(self):
2239 parser = self._get_parser(aliases=True)
2240 self.assertArgumentParserError(parser.parse_args,
2241 '0.5 1alias3 b'.split())
2242
2243 def test_alias_help(self):
2244 parser = self._get_parser(aliases=True, subparser_help=True)
2245 self.maxDiff = None
2246 self.assertEqual(parser.format_help(), textwrap.dedent("""\
2247 usage: PROG [-h] [--foo] bar COMMAND ...
2248
2249 main description
2250
2251 positional arguments:
2252 bar bar help
2253
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002254 options:
Steven Bethardfd311a72010-12-18 11:19:23 +00002255 -h, --help show this help message and exit
2256 --foo foo help
2257
2258 commands:
2259 COMMAND
2260 1 (1alias1, 1alias2)
2261 1 help
2262 2 2 help
R David Murray00528e82012-07-21 22:48:35 -04002263 3 3 help
Steven Bethardfd311a72010-12-18 11:19:23 +00002264 """))
2265
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002266# ============
2267# Groups tests
2268# ============
2269
2270class TestPositionalsGroups(TestCase):
2271 """Tests that order of group positionals matches construction order"""
2272
2273 def test_nongroup_first(self):
2274 parser = ErrorRaisingArgumentParser()
2275 parser.add_argument('foo')
2276 group = parser.add_argument_group('g')
2277 group.add_argument('bar')
2278 parser.add_argument('baz')
2279 expected = NS(foo='1', bar='2', baz='3')
2280 result = parser.parse_args('1 2 3'.split())
2281 self.assertEqual(expected, result)
2282
2283 def test_group_first(self):
2284 parser = ErrorRaisingArgumentParser()
2285 group = parser.add_argument_group('xxx')
2286 group.add_argument('foo')
2287 parser.add_argument('bar')
2288 parser.add_argument('baz')
2289 expected = NS(foo='1', bar='2', baz='3')
2290 result = parser.parse_args('1 2 3'.split())
2291 self.assertEqual(expected, result)
2292
2293 def test_interleaved_groups(self):
2294 parser = ErrorRaisingArgumentParser()
2295 group = parser.add_argument_group('xxx')
2296 parser.add_argument('foo')
2297 group.add_argument('bar')
2298 parser.add_argument('baz')
2299 group = parser.add_argument_group('yyy')
2300 group.add_argument('frell')
2301 expected = NS(foo='1', bar='2', baz='3', frell='4')
2302 result = parser.parse_args('1 2 3 4'.split())
2303 self.assertEqual(expected, result)
2304
2305# ===================
2306# Parent parser tests
2307# ===================
2308
2309class TestParentParsers(TestCase):
2310 """Tests that parsers can be created with parent parsers"""
2311
2312 def assertArgumentParserError(self, *args, **kwargs):
2313 self.assertRaises(ArgumentParserError, *args, **kwargs)
2314
2315 def setUp(self):
Steven Bethard1f1c2472010-11-01 13:56:09 +00002316 super().setUp()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002317 self.wxyz_parent = ErrorRaisingArgumentParser(add_help=False)
2318 self.wxyz_parent.add_argument('--w')
2319 x_group = self.wxyz_parent.add_argument_group('x')
2320 x_group.add_argument('-y')
2321 self.wxyz_parent.add_argument('z')
2322
2323 self.abcd_parent = ErrorRaisingArgumentParser(add_help=False)
2324 self.abcd_parent.add_argument('a')
2325 self.abcd_parent.add_argument('-b')
2326 c_group = self.abcd_parent.add_argument_group('c')
2327 c_group.add_argument('--d')
2328
2329 self.w_parent = ErrorRaisingArgumentParser(add_help=False)
2330 self.w_parent.add_argument('--w')
2331
2332 self.z_parent = ErrorRaisingArgumentParser(add_help=False)
2333 self.z_parent.add_argument('z')
2334
2335 # parents with mutually exclusive groups
2336 self.ab_mutex_parent = ErrorRaisingArgumentParser(add_help=False)
2337 group = self.ab_mutex_parent.add_mutually_exclusive_group()
2338 group.add_argument('-a', action='store_true')
2339 group.add_argument('-b', action='store_true')
2340
2341 self.main_program = os.path.basename(sys.argv[0])
2342
2343 def test_single_parent(self):
2344 parser = ErrorRaisingArgumentParser(parents=[self.wxyz_parent])
2345 self.assertEqual(parser.parse_args('-y 1 2 --w 3'.split()),
2346 NS(w='3', y='1', z='2'))
2347
2348 def test_single_parent_mutex(self):
2349 self._test_mutex_ab(self.ab_mutex_parent.parse_args)
2350 parser = ErrorRaisingArgumentParser(parents=[self.ab_mutex_parent])
2351 self._test_mutex_ab(parser.parse_args)
2352
2353 def test_single_granparent_mutex(self):
2354 parents = [self.ab_mutex_parent]
2355 parser = ErrorRaisingArgumentParser(add_help=False, parents=parents)
2356 parser = ErrorRaisingArgumentParser(parents=[parser])
2357 self._test_mutex_ab(parser.parse_args)
2358
2359 def _test_mutex_ab(self, parse_args):
2360 self.assertEqual(parse_args([]), NS(a=False, b=False))
2361 self.assertEqual(parse_args(['-a']), NS(a=True, b=False))
2362 self.assertEqual(parse_args(['-b']), NS(a=False, b=True))
2363 self.assertArgumentParserError(parse_args, ['-a', '-b'])
2364 self.assertArgumentParserError(parse_args, ['-b', '-a'])
2365 self.assertArgumentParserError(parse_args, ['-c'])
2366 self.assertArgumentParserError(parse_args, ['-a', '-c'])
2367 self.assertArgumentParserError(parse_args, ['-b', '-c'])
2368
2369 def test_multiple_parents(self):
2370 parents = [self.abcd_parent, self.wxyz_parent]
2371 parser = ErrorRaisingArgumentParser(parents=parents)
2372 self.assertEqual(parser.parse_args('--d 1 --w 2 3 4'.split()),
2373 NS(a='3', b=None, d='1', w='2', y=None, z='4'))
2374
2375 def test_multiple_parents_mutex(self):
2376 parents = [self.ab_mutex_parent, self.wxyz_parent]
2377 parser = ErrorRaisingArgumentParser(parents=parents)
2378 self.assertEqual(parser.parse_args('-a --w 2 3'.split()),
2379 NS(a=True, b=False, w='2', y=None, z='3'))
2380 self.assertArgumentParserError(
2381 parser.parse_args, '-a --w 2 3 -b'.split())
2382 self.assertArgumentParserError(
2383 parser.parse_args, '-a -b --w 2 3'.split())
2384
2385 def test_conflicting_parents(self):
2386 self.assertRaises(
2387 argparse.ArgumentError,
2388 argparse.ArgumentParser,
2389 parents=[self.w_parent, self.wxyz_parent])
2390
2391 def test_conflicting_parents_mutex(self):
2392 self.assertRaises(
2393 argparse.ArgumentError,
2394 argparse.ArgumentParser,
2395 parents=[self.abcd_parent, self.ab_mutex_parent])
2396
2397 def test_same_argument_name_parents(self):
2398 parents = [self.wxyz_parent, self.z_parent]
2399 parser = ErrorRaisingArgumentParser(parents=parents)
2400 self.assertEqual(parser.parse_args('1 2'.split()),
2401 NS(w=None, y=None, z='2'))
2402
2403 def test_subparser_parents(self):
2404 parser = ErrorRaisingArgumentParser()
2405 subparsers = parser.add_subparsers()
2406 abcde_parser = subparsers.add_parser('bar', parents=[self.abcd_parent])
2407 abcde_parser.add_argument('e')
2408 self.assertEqual(parser.parse_args('bar -b 1 --d 2 3 4'.split()),
2409 NS(a='3', b='1', d='2', e='4'))
2410
2411 def test_subparser_parents_mutex(self):
2412 parser = ErrorRaisingArgumentParser()
2413 subparsers = parser.add_subparsers()
2414 parents = [self.ab_mutex_parent]
2415 abc_parser = subparsers.add_parser('foo', parents=parents)
2416 c_group = abc_parser.add_argument_group('c_group')
2417 c_group.add_argument('c')
2418 parents = [self.wxyz_parent, self.ab_mutex_parent]
2419 wxyzabe_parser = subparsers.add_parser('bar', parents=parents)
2420 wxyzabe_parser.add_argument('e')
2421 self.assertEqual(parser.parse_args('foo -a 4'.split()),
2422 NS(a=True, b=False, c='4'))
2423 self.assertEqual(parser.parse_args('bar -b --w 2 3 4'.split()),
2424 NS(a=False, b=True, w='2', y=None, z='3', e='4'))
2425 self.assertArgumentParserError(
2426 parser.parse_args, 'foo -a -b 4'.split())
2427 self.assertArgumentParserError(
2428 parser.parse_args, 'bar -b -a 4'.split())
2429
2430 def test_parent_help(self):
2431 parents = [self.abcd_parent, self.wxyz_parent]
2432 parser = ErrorRaisingArgumentParser(parents=parents)
2433 parser_help = parser.format_help()
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002434 progname = self.main_program
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002435 self.assertEqual(parser_help, textwrap.dedent('''\
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002436 usage: {}{}[-h] [-b B] [--d D] [--w W] [-y Y] a z
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002437
2438 positional arguments:
2439 a
2440 z
2441
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002442 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002443 -h, --help show this help message and exit
2444 -b B
2445 --w W
2446
2447 c:
2448 --d D
2449
2450 x:
2451 -y Y
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002452 '''.format(progname, ' ' if progname else '' )))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002453
2454 def test_groups_parents(self):
2455 parent = ErrorRaisingArgumentParser(add_help=False)
2456 g = parent.add_argument_group(title='g', description='gd')
2457 g.add_argument('-w')
2458 g.add_argument('-x')
2459 m = parent.add_mutually_exclusive_group()
2460 m.add_argument('-y')
2461 m.add_argument('-z')
2462 parser = ErrorRaisingArgumentParser(parents=[parent])
2463
2464 self.assertRaises(ArgumentParserError, parser.parse_args,
2465 ['-y', 'Y', '-z', 'Z'])
2466
2467 parser_help = parser.format_help()
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002468 progname = self.main_program
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002469 self.assertEqual(parser_help, textwrap.dedent('''\
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002470 usage: {}{}[-h] [-w W] [-x X] [-y Y | -z Z]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002471
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002472 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002473 -h, --help show this help message and exit
2474 -y Y
2475 -z Z
2476
2477 g:
2478 gd
2479
2480 -w W
2481 -x X
Terry Jan Reedyee91e092012-01-09 18:20:09 -05002482 '''.format(progname, ' ' if progname else '' )))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002483
2484# ==============================
2485# Mutually exclusive group tests
2486# ==============================
2487
2488class TestMutuallyExclusiveGroupErrors(TestCase):
2489
2490 def test_invalid_add_argument_group(self):
2491 parser = ErrorRaisingArgumentParser()
2492 raises = self.assertRaises
2493 raises(TypeError, parser.add_mutually_exclusive_group, title='foo')
2494
2495 def test_invalid_add_argument(self):
2496 parser = ErrorRaisingArgumentParser()
2497 group = parser.add_mutually_exclusive_group()
2498 add_argument = group.add_argument
2499 raises = self.assertRaises
2500 raises(ValueError, add_argument, '--foo', required=True)
2501 raises(ValueError, add_argument, 'bar')
2502 raises(ValueError, add_argument, 'bar', nargs='+')
2503 raises(ValueError, add_argument, 'bar', nargs=1)
2504 raises(ValueError, add_argument, 'bar', nargs=argparse.PARSER)
2505
Steven Bethard49998ee2010-11-01 16:29:26 +00002506 def test_help(self):
2507 parser = ErrorRaisingArgumentParser(prog='PROG')
2508 group1 = parser.add_mutually_exclusive_group()
2509 group1.add_argument('--foo', action='store_true')
2510 group1.add_argument('--bar', action='store_false')
2511 group2 = parser.add_mutually_exclusive_group()
2512 group2.add_argument('--soup', action='store_true')
2513 group2.add_argument('--nuts', action='store_false')
2514 expected = '''\
2515 usage: PROG [-h] [--foo | --bar] [--soup | --nuts]
2516
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002517 options:
Steven Bethard49998ee2010-11-01 16:29:26 +00002518 -h, --help show this help message and exit
2519 --foo
2520 --bar
2521 --soup
2522 --nuts
2523 '''
2524 self.assertEqual(parser.format_help(), textwrap.dedent(expected))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002525
2526class MEMixin(object):
2527
2528 def test_failures_when_not_required(self):
2529 parse_args = self.get_parser(required=False).parse_args
2530 error = ArgumentParserError
2531 for args_string in self.failures:
2532 self.assertRaises(error, parse_args, args_string.split())
2533
2534 def test_failures_when_required(self):
2535 parse_args = self.get_parser(required=True).parse_args
2536 error = ArgumentParserError
2537 for args_string in self.failures + ['']:
2538 self.assertRaises(error, parse_args, args_string.split())
2539
2540 def test_successes_when_not_required(self):
2541 parse_args = self.get_parser(required=False).parse_args
2542 successes = self.successes + self.successes_when_not_required
2543 for args_string, expected_ns in successes:
2544 actual_ns = parse_args(args_string.split())
2545 self.assertEqual(actual_ns, expected_ns)
2546
2547 def test_successes_when_required(self):
2548 parse_args = self.get_parser(required=True).parse_args
2549 for args_string, expected_ns in self.successes:
2550 actual_ns = parse_args(args_string.split())
2551 self.assertEqual(actual_ns, expected_ns)
2552
2553 def test_usage_when_not_required(self):
2554 format_usage = self.get_parser(required=False).format_usage
2555 expected_usage = self.usage_when_not_required
2556 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))
2557
2558 def test_usage_when_required(self):
2559 format_usage = self.get_parser(required=True).format_usage
2560 expected_usage = self.usage_when_required
2561 self.assertEqual(format_usage(), textwrap.dedent(expected_usage))
2562
2563 def test_help_when_not_required(self):
2564 format_help = self.get_parser(required=False).format_help
2565 help = self.usage_when_not_required + self.help
2566 self.assertEqual(format_help(), textwrap.dedent(help))
2567
2568 def test_help_when_required(self):
2569 format_help = self.get_parser(required=True).format_help
2570 help = self.usage_when_required + self.help
2571 self.assertEqual(format_help(), textwrap.dedent(help))
2572
2573
2574class TestMutuallyExclusiveSimple(MEMixin, TestCase):
2575
2576 def get_parser(self, required=None):
2577 parser = ErrorRaisingArgumentParser(prog='PROG')
2578 group = parser.add_mutually_exclusive_group(required=required)
2579 group.add_argument('--bar', help='bar help')
2580 group.add_argument('--baz', nargs='?', const='Z', help='baz help')
2581 return parser
2582
2583 failures = ['--bar X --baz Y', '--bar X --baz']
2584 successes = [
2585 ('--bar X', NS(bar='X', baz=None)),
2586 ('--bar X --bar Z', NS(bar='Z', baz=None)),
2587 ('--baz Y', NS(bar=None, baz='Y')),
2588 ('--baz', NS(bar=None, baz='Z')),
2589 ]
2590 successes_when_not_required = [
2591 ('', NS(bar=None, baz=None)),
2592 ]
2593
2594 usage_when_not_required = '''\
2595 usage: PROG [-h] [--bar BAR | --baz [BAZ]]
2596 '''
2597 usage_when_required = '''\
2598 usage: PROG [-h] (--bar BAR | --baz [BAZ])
2599 '''
2600 help = '''\
2601
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002602 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002603 -h, --help show this help message and exit
2604 --bar BAR bar help
2605 --baz [BAZ] baz help
2606 '''
2607
2608
2609class TestMutuallyExclusiveLong(MEMixin, TestCase):
2610
2611 def get_parser(self, required=None):
2612 parser = ErrorRaisingArgumentParser(prog='PROG')
2613 parser.add_argument('--abcde', help='abcde help')
2614 parser.add_argument('--fghij', help='fghij help')
2615 group = parser.add_mutually_exclusive_group(required=required)
2616 group.add_argument('--klmno', help='klmno help')
2617 group.add_argument('--pqrst', help='pqrst help')
2618 return parser
2619
2620 failures = ['--klmno X --pqrst Y']
2621 successes = [
2622 ('--klmno X', NS(abcde=None, fghij=None, klmno='X', pqrst=None)),
2623 ('--abcde Y --klmno X',
2624 NS(abcde='Y', fghij=None, klmno='X', pqrst=None)),
2625 ('--pqrst X', NS(abcde=None, fghij=None, klmno=None, pqrst='X')),
2626 ('--pqrst X --fghij Y',
2627 NS(abcde=None, fghij='Y', klmno=None, pqrst='X')),
2628 ]
2629 successes_when_not_required = [
2630 ('', NS(abcde=None, fghij=None, klmno=None, pqrst=None)),
2631 ]
2632
2633 usage_when_not_required = '''\
2634 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]
2635 [--klmno KLMNO | --pqrst PQRST]
2636 '''
2637 usage_when_required = '''\
2638 usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ]
2639 (--klmno KLMNO | --pqrst PQRST)
2640 '''
2641 help = '''\
2642
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002643 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002644 -h, --help show this help message and exit
2645 --abcde ABCDE abcde help
2646 --fghij FGHIJ fghij help
2647 --klmno KLMNO klmno help
2648 --pqrst PQRST pqrst help
2649 '''
2650
2651
2652class TestMutuallyExclusiveFirstSuppressed(MEMixin, TestCase):
2653
2654 def get_parser(self, required):
2655 parser = ErrorRaisingArgumentParser(prog='PROG')
2656 group = parser.add_mutually_exclusive_group(required=required)
2657 group.add_argument('-x', help=argparse.SUPPRESS)
2658 group.add_argument('-y', action='store_false', help='y help')
2659 return parser
2660
2661 failures = ['-x X -y']
2662 successes = [
2663 ('-x X', NS(x='X', y=True)),
2664 ('-x X -x Y', NS(x='Y', y=True)),
2665 ('-y', NS(x=None, y=False)),
2666 ]
2667 successes_when_not_required = [
2668 ('', NS(x=None, y=True)),
2669 ]
2670
2671 usage_when_not_required = '''\
2672 usage: PROG [-h] [-y]
2673 '''
2674 usage_when_required = '''\
2675 usage: PROG [-h] -y
2676 '''
2677 help = '''\
2678
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002679 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002680 -h, --help show this help message and exit
2681 -y y help
2682 '''
2683
2684
2685class TestMutuallyExclusiveManySuppressed(MEMixin, TestCase):
2686
2687 def get_parser(self, required):
2688 parser = ErrorRaisingArgumentParser(prog='PROG')
2689 group = parser.add_mutually_exclusive_group(required=required)
2690 add = group.add_argument
2691 add('--spam', action='store_true', help=argparse.SUPPRESS)
2692 add('--badger', action='store_false', help=argparse.SUPPRESS)
2693 add('--bladder', help=argparse.SUPPRESS)
2694 return parser
2695
2696 failures = [
2697 '--spam --badger',
2698 '--badger --bladder B',
2699 '--bladder B --spam',
2700 ]
2701 successes = [
2702 ('--spam', NS(spam=True, badger=True, bladder=None)),
2703 ('--badger', NS(spam=False, badger=False, bladder=None)),
2704 ('--bladder B', NS(spam=False, badger=True, bladder='B')),
2705 ('--spam --spam', NS(spam=True, badger=True, bladder=None)),
2706 ]
2707 successes_when_not_required = [
2708 ('', NS(spam=False, badger=True, bladder=None)),
2709 ]
2710
2711 usage_when_required = usage_when_not_required = '''\
2712 usage: PROG [-h]
2713 '''
2714 help = '''\
2715
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002716 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002717 -h, --help show this help message and exit
2718 '''
2719
2720
2721class TestMutuallyExclusiveOptionalAndPositional(MEMixin, TestCase):
2722
2723 def get_parser(self, required):
2724 parser = ErrorRaisingArgumentParser(prog='PROG')
2725 group = parser.add_mutually_exclusive_group(required=required)
2726 group.add_argument('--foo', action='store_true', help='FOO')
2727 group.add_argument('--spam', help='SPAM')
2728 group.add_argument('badger', nargs='*', default='X', help='BADGER')
2729 return parser
2730
2731 failures = [
2732 '--foo --spam S',
2733 '--spam S X',
2734 'X --foo',
2735 'X Y Z --spam S',
2736 '--foo X Y',
2737 ]
2738 successes = [
2739 ('--foo', NS(foo=True, spam=None, badger='X')),
2740 ('--spam S', NS(foo=False, spam='S', badger='X')),
2741 ('X', NS(foo=False, spam=None, badger=['X'])),
2742 ('X Y Z', NS(foo=False, spam=None, badger=['X', 'Y', 'Z'])),
2743 ]
2744 successes_when_not_required = [
2745 ('', NS(foo=False, spam=None, badger='X')),
2746 ]
2747
2748 usage_when_not_required = '''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08002749 usage: PROG [-h] [--foo | --spam SPAM | badger ...]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002750 '''
2751 usage_when_required = '''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08002752 usage: PROG [-h] (--foo | --spam SPAM | badger ...)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002753 '''
2754 help = '''\
2755
2756 positional arguments:
2757 badger BADGER
2758
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002759 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002760 -h, --help show this help message and exit
2761 --foo FOO
2762 --spam SPAM SPAM
2763 '''
2764
2765
2766class TestMutuallyExclusiveOptionalsMixed(MEMixin, TestCase):
2767
2768 def get_parser(self, required):
2769 parser = ErrorRaisingArgumentParser(prog='PROG')
2770 parser.add_argument('-x', action='store_true', help='x help')
2771 group = parser.add_mutually_exclusive_group(required=required)
2772 group.add_argument('-a', action='store_true', help='a help')
2773 group.add_argument('-b', action='store_true', help='b help')
2774 parser.add_argument('-y', action='store_true', help='y help')
2775 group.add_argument('-c', action='store_true', help='c help')
2776 return parser
2777
2778 failures = ['-a -b', '-b -c', '-a -c', '-a -b -c']
2779 successes = [
2780 ('-a', NS(a=True, b=False, c=False, x=False, y=False)),
2781 ('-b', NS(a=False, b=True, c=False, x=False, y=False)),
2782 ('-c', NS(a=False, b=False, c=True, x=False, y=False)),
2783 ('-a -x', NS(a=True, b=False, c=False, x=True, y=False)),
2784 ('-y -b', NS(a=False, b=True, c=False, x=False, y=True)),
2785 ('-x -y -c', NS(a=False, b=False, c=True, x=True, y=True)),
2786 ]
2787 successes_when_not_required = [
2788 ('', NS(a=False, b=False, c=False, x=False, y=False)),
2789 ('-x', NS(a=False, b=False, c=False, x=True, y=False)),
2790 ('-y', NS(a=False, b=False, c=False, x=False, y=True)),
2791 ]
2792
2793 usage_when_required = usage_when_not_required = '''\
2794 usage: PROG [-h] [-x] [-a] [-b] [-y] [-c]
2795 '''
2796 help = '''\
2797
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002798 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002799 -h, --help show this help message and exit
2800 -x x help
2801 -a a help
2802 -b b help
2803 -y y help
2804 -c c help
2805 '''
2806
2807
Georg Brandl0f6b47a2011-01-30 12:19:35 +00002808class TestMutuallyExclusiveInGroup(MEMixin, TestCase):
2809
2810 def get_parser(self, required=None):
2811 parser = ErrorRaisingArgumentParser(prog='PROG')
2812 titled_group = parser.add_argument_group(
2813 title='Titled group', description='Group description')
2814 mutex_group = \
2815 titled_group.add_mutually_exclusive_group(required=required)
2816 mutex_group.add_argument('--bar', help='bar help')
2817 mutex_group.add_argument('--baz', help='baz help')
2818 return parser
2819
2820 failures = ['--bar X --baz Y', '--baz X --bar Y']
2821 successes = [
2822 ('--bar X', NS(bar='X', baz=None)),
2823 ('--baz Y', NS(bar=None, baz='Y')),
2824 ]
2825 successes_when_not_required = [
2826 ('', NS(bar=None, baz=None)),
2827 ]
2828
2829 usage_when_not_required = '''\
2830 usage: PROG [-h] [--bar BAR | --baz BAZ]
2831 '''
2832 usage_when_required = '''\
2833 usage: PROG [-h] (--bar BAR | --baz BAZ)
2834 '''
2835 help = '''\
2836
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002837 options:
Georg Brandl0f6b47a2011-01-30 12:19:35 +00002838 -h, --help show this help message and exit
2839
2840 Titled group:
2841 Group description
2842
2843 --bar BAR bar help
2844 --baz BAZ baz help
2845 '''
2846
2847
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002848class TestMutuallyExclusiveOptionalsAndPositionalsMixed(MEMixin, TestCase):
2849
2850 def get_parser(self, required):
2851 parser = ErrorRaisingArgumentParser(prog='PROG')
2852 parser.add_argument('x', help='x help')
2853 parser.add_argument('-y', action='store_true', help='y help')
2854 group = parser.add_mutually_exclusive_group(required=required)
2855 group.add_argument('a', nargs='?', help='a help')
2856 group.add_argument('-b', action='store_true', help='b help')
2857 group.add_argument('-c', action='store_true', help='c help')
2858 return parser
2859
2860 failures = ['X A -b', '-b -c', '-c X A']
2861 successes = [
2862 ('X A', NS(a='A', b=False, c=False, x='X', y=False)),
2863 ('X -b', NS(a=None, b=True, c=False, x='X', y=False)),
2864 ('X -c', NS(a=None, b=False, c=True, x='X', y=False)),
2865 ('X A -y', NS(a='A', b=False, c=False, x='X', y=True)),
2866 ('X -y -b', NS(a=None, b=True, c=False, x='X', y=True)),
2867 ]
2868 successes_when_not_required = [
2869 ('X', NS(a=None, b=False, c=False, x='X', y=False)),
2870 ('X -y', NS(a=None, b=False, c=False, x='X', y=True)),
2871 ]
2872
2873 usage_when_required = usage_when_not_required = '''\
2874 usage: PROG [-h] [-y] [-b] [-c] x [a]
2875 '''
2876 help = '''\
2877
2878 positional arguments:
2879 x x help
2880 a a help
2881
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002882 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002883 -h, --help show this help message and exit
2884 -y y help
2885 -b b help
2886 -c c help
2887 '''
2888
Flavian Hautboisda27d9b2019-08-25 21:06:45 +02002889class TestMutuallyExclusiveNested(MEMixin, TestCase):
2890
2891 def get_parser(self, required):
2892 parser = ErrorRaisingArgumentParser(prog='PROG')
2893 group = parser.add_mutually_exclusive_group(required=required)
2894 group.add_argument('-a')
2895 group.add_argument('-b')
2896 group2 = group.add_mutually_exclusive_group(required=required)
2897 group2.add_argument('-c')
2898 group2.add_argument('-d')
2899 group3 = group2.add_mutually_exclusive_group(required=required)
2900 group3.add_argument('-e')
2901 group3.add_argument('-f')
2902 return parser
2903
2904 usage_when_not_required = '''\
2905 usage: PROG [-h] [-a A | -b B | [-c C | -d D | [-e E | -f F]]]
2906 '''
2907 usage_when_required = '''\
2908 usage: PROG [-h] (-a A | -b B | (-c C | -d D | (-e E | -f F)))
2909 '''
2910
2911 help = '''\
2912
Raymond Hettinger41b223d2020-12-23 09:40:56 -08002913 options:
Flavian Hautboisda27d9b2019-08-25 21:06:45 +02002914 -h, --help show this help message and exit
2915 -a A
2916 -b B
2917 -c C
2918 -d D
2919 -e E
2920 -f F
2921 '''
2922
2923 # We are only interested in testing the behavior of format_usage().
2924 test_failures_when_not_required = None
2925 test_failures_when_required = None
2926 test_successes_when_not_required = None
2927 test_successes_when_required = None
2928
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002929# =================================================
2930# Mutually exclusive group in parent parser tests
2931# =================================================
2932
2933class MEPBase(object):
2934
2935 def get_parser(self, required=None):
2936 parent = super(MEPBase, self).get_parser(required=required)
2937 parser = ErrorRaisingArgumentParser(
2938 prog=parent.prog, add_help=False, parents=[parent])
2939 return parser
2940
2941
2942class TestMutuallyExclusiveGroupErrorsParent(
2943 MEPBase, TestMutuallyExclusiveGroupErrors):
2944 pass
2945
2946
2947class TestMutuallyExclusiveSimpleParent(
2948 MEPBase, TestMutuallyExclusiveSimple):
2949 pass
2950
2951
2952class TestMutuallyExclusiveLongParent(
2953 MEPBase, TestMutuallyExclusiveLong):
2954 pass
2955
2956
2957class TestMutuallyExclusiveFirstSuppressedParent(
2958 MEPBase, TestMutuallyExclusiveFirstSuppressed):
2959 pass
2960
2961
2962class TestMutuallyExclusiveManySuppressedParent(
2963 MEPBase, TestMutuallyExclusiveManySuppressed):
2964 pass
2965
2966
2967class TestMutuallyExclusiveOptionalAndPositionalParent(
2968 MEPBase, TestMutuallyExclusiveOptionalAndPositional):
2969 pass
2970
2971
2972class TestMutuallyExclusiveOptionalsMixedParent(
2973 MEPBase, TestMutuallyExclusiveOptionalsMixed):
2974 pass
2975
2976
2977class TestMutuallyExclusiveOptionalsAndPositionalsMixedParent(
2978 MEPBase, TestMutuallyExclusiveOptionalsAndPositionalsMixed):
2979 pass
2980
2981# =================
2982# Set default tests
2983# =================
2984
2985class TestSetDefaults(TestCase):
2986
2987 def test_set_defaults_no_args(self):
2988 parser = ErrorRaisingArgumentParser()
2989 parser.set_defaults(x='foo')
2990 parser.set_defaults(y='bar', z=1)
2991 self.assertEqual(NS(x='foo', y='bar', z=1),
2992 parser.parse_args([]))
2993 self.assertEqual(NS(x='foo', y='bar', z=1),
2994 parser.parse_args([], NS()))
2995 self.assertEqual(NS(x='baz', y='bar', z=1),
2996 parser.parse_args([], NS(x='baz')))
2997 self.assertEqual(NS(x='baz', y='bar', z=2),
2998 parser.parse_args([], NS(x='baz', z=2)))
2999
3000 def test_set_defaults_with_args(self):
3001 parser = ErrorRaisingArgumentParser()
3002 parser.set_defaults(x='foo', y='bar')
3003 parser.add_argument('-x', default='xfoox')
3004 self.assertEqual(NS(x='xfoox', y='bar'),
3005 parser.parse_args([]))
3006 self.assertEqual(NS(x='xfoox', y='bar'),
3007 parser.parse_args([], NS()))
3008 self.assertEqual(NS(x='baz', y='bar'),
3009 parser.parse_args([], NS(x='baz')))
3010 self.assertEqual(NS(x='1', y='bar'),
3011 parser.parse_args('-x 1'.split()))
3012 self.assertEqual(NS(x='1', y='bar'),
3013 parser.parse_args('-x 1'.split(), NS()))
3014 self.assertEqual(NS(x='1', y='bar'),
3015 parser.parse_args('-x 1'.split(), NS(x='baz')))
3016
3017 def test_set_defaults_subparsers(self):
3018 parser = ErrorRaisingArgumentParser()
3019 parser.set_defaults(x='foo')
3020 subparsers = parser.add_subparsers()
3021 parser_a = subparsers.add_parser('a')
3022 parser_a.set_defaults(y='bar')
3023 self.assertEqual(NS(x='foo', y='bar'),
3024 parser.parse_args('a'.split()))
3025
3026 def test_set_defaults_parents(self):
3027 parent = ErrorRaisingArgumentParser(add_help=False)
3028 parent.set_defaults(x='foo')
3029 parser = ErrorRaisingArgumentParser(parents=[parent])
3030 self.assertEqual(NS(x='foo'), parser.parse_args([]))
3031
R David Murray7570cbd2014-10-17 19:55:11 -04003032 def test_set_defaults_on_parent_and_subparser(self):
3033 parser = argparse.ArgumentParser()
3034 xparser = parser.add_subparsers().add_parser('X')
3035 parser.set_defaults(foo=1)
3036 xparser.set_defaults(foo=2)
3037 self.assertEqual(NS(foo=2), parser.parse_args(['X']))
3038
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003039 def test_set_defaults_same_as_add_argument(self):
3040 parser = ErrorRaisingArgumentParser()
3041 parser.set_defaults(w='W', x='X', y='Y', z='Z')
3042 parser.add_argument('-w')
3043 parser.add_argument('-x', default='XX')
3044 parser.add_argument('y', nargs='?')
3045 parser.add_argument('z', nargs='?', default='ZZ')
3046
3047 # defaults set previously
3048 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
3049 parser.parse_args([]))
3050
3051 # reset defaults
3052 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
3053 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
3054 parser.parse_args([]))
3055
3056 def test_set_defaults_same_as_add_argument_group(self):
3057 parser = ErrorRaisingArgumentParser()
3058 parser.set_defaults(w='W', x='X', y='Y', z='Z')
3059 group = parser.add_argument_group('foo')
3060 group.add_argument('-w')
3061 group.add_argument('-x', default='XX')
3062 group.add_argument('y', nargs='?')
3063 group.add_argument('z', nargs='?', default='ZZ')
3064
3065
3066 # defaults set previously
3067 self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'),
3068 parser.parse_args([]))
3069
3070 # reset defaults
3071 parser.set_defaults(w='WW', x='X', y='YY', z='Z')
3072 self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'),
3073 parser.parse_args([]))
3074
3075# =================
3076# Get default tests
3077# =================
3078
3079class TestGetDefault(TestCase):
3080
3081 def test_get_default(self):
3082 parser = ErrorRaisingArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003083 self.assertIsNone(parser.get_default("foo"))
3084 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003085
3086 parser.add_argument("--foo")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003087 self.assertIsNone(parser.get_default("foo"))
3088 self.assertIsNone(parser.get_default("bar"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003089
3090 parser.add_argument("--bar", type=int, default=42)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003091 self.assertIsNone(parser.get_default("foo"))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003092 self.assertEqual(42, parser.get_default("bar"))
3093
3094 parser.set_defaults(foo="badger")
3095 self.assertEqual("badger", parser.get_default("foo"))
3096 self.assertEqual(42, parser.get_default("bar"))
3097
3098# ==========================
3099# Namespace 'contains' tests
3100# ==========================
3101
3102class TestNamespaceContainsSimple(TestCase):
3103
3104 def test_empty(self):
3105 ns = argparse.Namespace()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003106 self.assertNotIn('', ns)
3107 self.assertNotIn('x', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003108
3109 def test_non_empty(self):
3110 ns = argparse.Namespace(x=1, y=2)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03003111 self.assertNotIn('', ns)
3112 self.assertIn('x', ns)
3113 self.assertIn('y', ns)
3114 self.assertNotIn('xx', ns)
3115 self.assertNotIn('z', ns)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003116
3117# =====================
3118# Help formatting tests
3119# =====================
3120
3121class TestHelpFormattingMetaclass(type):
3122
3123 def __init__(cls, name, bases, bodydict):
3124 if name == 'HelpTestCase':
3125 return
3126
3127 class AddTests(object):
3128
3129 def __init__(self, test_class, func_suffix, std_name):
3130 self.func_suffix = func_suffix
3131 self.std_name = std_name
3132
3133 for test_func in [self.test_format,
3134 self.test_print,
3135 self.test_print_file]:
3136 test_name = '%s_%s' % (test_func.__name__, func_suffix)
3137
3138 def test_wrapper(self, test_func=test_func):
3139 test_func(self)
3140 try:
3141 test_wrapper.__name__ = test_name
3142 except TypeError:
3143 pass
3144 setattr(test_class, test_name, test_wrapper)
3145
3146 def _get_parser(self, tester):
3147 parser = argparse.ArgumentParser(
3148 *tester.parser_signature.args,
3149 **tester.parser_signature.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003150 for argument_sig in getattr(tester, 'argument_signatures', []):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003151 parser.add_argument(*argument_sig.args,
3152 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003153 group_sigs = getattr(tester, 'argument_group_signatures', [])
3154 for group_sig, argument_sigs in group_sigs:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003155 group = parser.add_argument_group(*group_sig.args,
3156 **group_sig.kwargs)
3157 for argument_sig in argument_sigs:
3158 group.add_argument(*argument_sig.args,
3159 **argument_sig.kwargs)
Steven Bethard8a6a1982011-03-27 13:53:53 +02003160 subparsers_sigs = getattr(tester, 'subparsers_signatures', [])
3161 if subparsers_sigs:
3162 subparsers = parser.add_subparsers()
3163 for subparser_sig in subparsers_sigs:
3164 subparsers.add_parser(*subparser_sig.args,
3165 **subparser_sig.kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003166 return parser
3167
3168 def _test(self, tester, parser_text):
3169 expected_text = getattr(tester, self.func_suffix)
3170 expected_text = textwrap.dedent(expected_text)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003171 tester.assertEqual(expected_text, parser_text)
3172
3173 def test_format(self, tester):
3174 parser = self._get_parser(tester)
3175 format = getattr(parser, 'format_%s' % self.func_suffix)
3176 self._test(tester, format())
3177
3178 def test_print(self, tester):
3179 parser = self._get_parser(tester)
3180 print_ = getattr(parser, 'print_%s' % self.func_suffix)
3181 old_stream = getattr(sys, self.std_name)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003182 setattr(sys, self.std_name, StdIOBuffer())
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003183 try:
3184 print_()
3185 parser_text = getattr(sys, self.std_name).getvalue()
3186 finally:
3187 setattr(sys, self.std_name, old_stream)
3188 self._test(tester, parser_text)
3189
3190 def test_print_file(self, tester):
3191 parser = self._get_parser(tester)
3192 print_ = getattr(parser, 'print_%s' % self.func_suffix)
Benjamin Petersonb48af542010-04-11 20:43:16 +00003193 sfile = StdIOBuffer()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003194 print_(sfile)
3195 parser_text = sfile.getvalue()
3196 self._test(tester, parser_text)
3197
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003198 # add tests for {format,print}_{usage,help}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003199 for func_suffix, std_name in [('usage', 'stdout'),
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003200 ('help', 'stdout')]:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003201 AddTests(cls, func_suffix, std_name)
3202
3203bases = TestCase,
3204HelpTestCase = TestHelpFormattingMetaclass('HelpTestCase', bases, {})
3205
3206
3207class TestHelpBiggerOptionals(HelpTestCase):
3208 """Make sure that argument help aligns when options are longer"""
3209
3210 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003211 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003212 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003213 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003214 Sig('-x', action='store_true', help='X HELP'),
3215 Sig('--y', help='Y HELP'),
3216 Sig('foo', help='FOO HELP'),
3217 Sig('bar', help='BAR HELP'),
3218 ]
3219 argument_group_signatures = []
3220 usage = '''\
3221 usage: PROG [-h] [-v] [-x] [--y Y] foo bar
3222 '''
3223 help = usage + '''\
3224
3225 DESCRIPTION
3226
3227 positional arguments:
3228 foo FOO HELP
3229 bar BAR HELP
3230
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003231 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003232 -h, --help show this help message and exit
3233 -v, --version show program's version number and exit
3234 -x X HELP
3235 --y Y Y HELP
3236
3237 EPILOG
3238 '''
3239 version = '''\
3240 0.1
3241 '''
3242
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003243class TestShortColumns(HelpTestCase):
3244 '''Test extremely small number of columns.
3245
3246 TestCase prevents "COLUMNS" from being too small in the tests themselves,
Martin Panter2e4571a2015-11-14 01:07:43 +00003247 but we don't want any exceptions thrown in such cases. Only ugly representation.
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003248 '''
3249 def setUp(self):
Hai Shi46605972020-08-04 00:49:18 +08003250 env = os_helper.EnvironmentVarGuard()
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003251 env.set("COLUMNS", '15')
3252 self.addCleanup(env.__exit__)
3253
3254 parser_signature = TestHelpBiggerOptionals.parser_signature
3255 argument_signatures = TestHelpBiggerOptionals.argument_signatures
3256 argument_group_signatures = TestHelpBiggerOptionals.argument_group_signatures
3257 usage = '''\
3258 usage: PROG
3259 [-h]
3260 [-v]
3261 [-x]
3262 [--y Y]
3263 foo
3264 bar
3265 '''
3266 help = usage + '''\
3267
3268 DESCRIPTION
3269
3270 positional arguments:
3271 foo
3272 FOO HELP
3273 bar
3274 BAR HELP
3275
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003276 options:
Serhiy Storchakaf4511122014-01-09 23:14:27 +02003277 -h, --help
3278 show this
3279 help
3280 message and
3281 exit
3282 -v, --version
3283 show
3284 program's
3285 version
3286 number and
3287 exit
3288 -x
3289 X HELP
3290 --y Y
3291 Y HELP
3292
3293 EPILOG
3294 '''
3295 version = TestHelpBiggerOptionals.version
3296
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003297
3298class TestHelpBiggerOptionalGroups(HelpTestCase):
3299 """Make sure that argument help aligns when options are longer"""
3300
3301 parser_signature = Sig(prog='PROG', description='DESCRIPTION',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003302 epilog='EPILOG')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003303 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003304 Sig('-v', '--version', action='version', version='0.1'),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003305 Sig('-x', action='store_true', help='X HELP'),
3306 Sig('--y', help='Y HELP'),
3307 Sig('foo', help='FOO HELP'),
3308 Sig('bar', help='BAR HELP'),
3309 ]
3310 argument_group_signatures = [
3311 (Sig('GROUP TITLE', description='GROUP DESCRIPTION'), [
3312 Sig('baz', help='BAZ HELP'),
3313 Sig('-z', nargs='+', help='Z HELP')]),
3314 ]
3315 usage = '''\
3316 usage: PROG [-h] [-v] [-x] [--y Y] [-z Z [Z ...]] foo bar baz
3317 '''
3318 help = usage + '''\
3319
3320 DESCRIPTION
3321
3322 positional arguments:
3323 foo FOO HELP
3324 bar BAR HELP
3325
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003326 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003327 -h, --help show this help message and exit
3328 -v, --version show program's version number and exit
3329 -x X HELP
3330 --y Y Y HELP
3331
3332 GROUP TITLE:
3333 GROUP DESCRIPTION
3334
3335 baz BAZ HELP
3336 -z Z [Z ...] Z HELP
3337
3338 EPILOG
3339 '''
3340 version = '''\
3341 0.1
3342 '''
3343
3344
3345class TestHelpBiggerPositionals(HelpTestCase):
3346 """Make sure that help aligns when arguments are longer"""
3347
3348 parser_signature = Sig(usage='USAGE', description='DESCRIPTION')
3349 argument_signatures = [
3350 Sig('-x', action='store_true', help='X HELP'),
3351 Sig('--y', help='Y HELP'),
3352 Sig('ekiekiekifekang', help='EKI HELP'),
3353 Sig('bar', help='BAR HELP'),
3354 ]
3355 argument_group_signatures = []
3356 usage = '''\
3357 usage: USAGE
3358 '''
3359 help = usage + '''\
3360
3361 DESCRIPTION
3362
3363 positional arguments:
3364 ekiekiekifekang EKI HELP
3365 bar BAR HELP
3366
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003367 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003368 -h, --help show this help message and exit
3369 -x X HELP
3370 --y Y Y HELP
3371 '''
3372
3373 version = ''
3374
3375
3376class TestHelpReformatting(HelpTestCase):
3377 """Make sure that text after short names starts on the first line"""
3378
3379 parser_signature = Sig(
3380 prog='PROG',
3381 description=' oddly formatted\n'
3382 'description\n'
3383 '\n'
3384 'that is so long that it should go onto multiple '
3385 'lines when wrapped')
3386 argument_signatures = [
3387 Sig('-x', metavar='XX', help='oddly\n'
3388 ' formatted -x help'),
3389 Sig('y', metavar='yyy', help='normal y help'),
3390 ]
3391 argument_group_signatures = [
3392 (Sig('title', description='\n'
3393 ' oddly formatted group\n'
3394 '\n'
3395 'description'),
3396 [Sig('-a', action='store_true',
3397 help=' oddly \n'
3398 'formatted -a help \n'
3399 ' again, so long that it should be wrapped over '
3400 'multiple lines')]),
3401 ]
3402 usage = '''\
3403 usage: PROG [-h] [-x XX] [-a] yyy
3404 '''
3405 help = usage + '''\
3406
3407 oddly formatted description that is so long that it should go onto \
3408multiple
3409 lines when wrapped
3410
3411 positional arguments:
3412 yyy normal y help
3413
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003414 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003415 -h, --help show this help message and exit
3416 -x XX oddly formatted -x help
3417
3418 title:
3419 oddly formatted group description
3420
3421 -a oddly formatted -a help again, so long that it should \
3422be wrapped
3423 over multiple lines
3424 '''
3425 version = ''
3426
3427
3428class TestHelpWrappingShortNames(HelpTestCase):
3429 """Make sure that text after short names starts on the first line"""
3430
3431 parser_signature = Sig(prog='PROG', description= 'D\nD' * 30)
3432 argument_signatures = [
3433 Sig('-x', metavar='XX', help='XHH HX' * 20),
3434 Sig('y', metavar='yyy', help='YH YH' * 20),
3435 ]
3436 argument_group_signatures = [
3437 (Sig('ALPHAS'), [
3438 Sig('-a', action='store_true', help='AHHH HHA' * 10)]),
3439 ]
3440 usage = '''\
3441 usage: PROG [-h] [-x XX] [-a] yyy
3442 '''
3443 help = usage + '''\
3444
3445 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3446DD DD DD
3447 DD DD DD DD D
3448
3449 positional arguments:
3450 yyy YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3451YHYH YHYH
3452 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3453
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003454 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003455 -h, --help show this help message and exit
3456 -x XX XHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH \
3457HXXHH HXXHH
3458 HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HX
3459
3460 ALPHAS:
3461 -a AHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH \
3462HHAAHHH
3463 HHAAHHH HHAAHHH HHA
3464 '''
3465 version = ''
3466
3467
3468class TestHelpWrappingLongNames(HelpTestCase):
3469 """Make sure that text after long names starts on the next line"""
3470
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003471 parser_signature = Sig(usage='USAGE', description= 'D D' * 30)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003472 argument_signatures = [
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02003473 Sig('-v', '--version', action='version', version='V V' * 30),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003474 Sig('-x', metavar='X' * 25, help='XH XH' * 20),
3475 Sig('y', metavar='y' * 25, help='YH YH' * 20),
3476 ]
3477 argument_group_signatures = [
3478 (Sig('ALPHAS'), [
3479 Sig('-a', metavar='A' * 25, help='AH AH' * 20),
3480 Sig('z', metavar='z' * 25, help='ZH ZH' * 20)]),
3481 ]
3482 usage = '''\
3483 usage: USAGE
3484 '''
3485 help = usage + '''\
3486
3487 D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \
3488DD DD DD
3489 DD DD DD DD D
3490
3491 positional arguments:
3492 yyyyyyyyyyyyyyyyyyyyyyyyy
3493 YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \
3494YHYH YHYH
3495 YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH
3496
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003497 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003498 -h, --help show this help message and exit
3499 -v, --version show program's version number and exit
3500 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3501 XH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH \
3502XHXH XHXH
3503 XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XH
3504
3505 ALPHAS:
3506 -a AAAAAAAAAAAAAAAAAAAAAAAAA
3507 AH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH \
3508AHAH AHAH
3509 AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AH
3510 zzzzzzzzzzzzzzzzzzzzzzzzz
3511 ZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH \
3512ZHZH ZHZH
3513 ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZH
3514 '''
3515 version = '''\
3516 V VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV \
3517VV VV VV
3518 VV VV VV VV V
3519 '''
3520
3521
3522class TestHelpUsage(HelpTestCase):
3523 """Test basic usage messages"""
3524
3525 parser_signature = Sig(prog='PROG')
3526 argument_signatures = [
3527 Sig('-w', nargs='+', help='w'),
3528 Sig('-x', nargs='*', help='x'),
3529 Sig('a', help='a'),
3530 Sig('b', help='b', nargs=2),
3531 Sig('c', help='c', nargs='?'),
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003532 Sig('--foo', help='Whether to foo', action=argparse.BooleanOptionalAction),
3533 Sig('--bar', help='Whether to bar', default=True,
3534 action=argparse.BooleanOptionalAction),
3535 Sig('-f', '--foobar', '--barfoo', action=argparse.BooleanOptionalAction),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003536 ]
3537 argument_group_signatures = [
3538 (Sig('group'), [
3539 Sig('-y', nargs='?', help='y'),
3540 Sig('-z', nargs=3, help='z'),
3541 Sig('d', help='d', nargs='*'),
3542 Sig('e', help='e', nargs='+'),
3543 ])
3544 ]
3545 usage = '''\
Brandt Buchera0ed99b2019-11-11 12:47:48 -08003546 usage: PROG [-h] [-w W [W ...]] [-x [X ...]] [--foo | --no-foo]
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003547 [--bar | --no-bar]
3548 [-f | --foobar | --no-foobar | --barfoo | --no-barfoo] [-y [Y]]
3549 [-z Z Z Z]
Brandt Buchera0ed99b2019-11-11 12:47:48 -08003550 a b b [c] [d ...] e [e ...]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003551 '''
3552 help = usage + '''\
3553
3554 positional arguments:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003555 a a
3556 b b
3557 c c
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003558
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003559 options:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003560 -h, --help show this help message and exit
3561 -w W [W ...] w
Brandt Buchera0ed99b2019-11-11 12:47:48 -08003562 -x [X ...] x
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003563 --foo, --no-foo Whether to foo
3564 --bar, --no-bar Whether to bar (default: True)
3565 -f, --foobar, --no-foobar, --barfoo, --no-barfoo
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003566
3567 group:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02003568 -y [Y] y
3569 -z Z Z Z z
3570 d d
3571 e e
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003572 '''
3573 version = ''
3574
3575
3576class TestHelpOnlyUserGroups(HelpTestCase):
3577 """Test basic usage messages"""
3578
3579 parser_signature = Sig(prog='PROG', add_help=False)
3580 argument_signatures = []
3581 argument_group_signatures = [
3582 (Sig('xxxx'), [
3583 Sig('-x', help='x'),
3584 Sig('a', help='a'),
3585 ]),
3586 (Sig('yyyy'), [
3587 Sig('b', help='b'),
3588 Sig('-y', help='y'),
3589 ]),
3590 ]
3591 usage = '''\
3592 usage: PROG [-x X] [-y Y] a b
3593 '''
3594 help = usage + '''\
3595
3596 xxxx:
3597 -x X x
3598 a a
3599
3600 yyyy:
3601 b b
3602 -y Y y
3603 '''
3604 version = ''
3605
3606
3607class TestHelpUsageLongProg(HelpTestCase):
3608 """Test usage messages where the prog is long"""
3609
3610 parser_signature = Sig(prog='P' * 60)
3611 argument_signatures = [
3612 Sig('-w', metavar='W'),
3613 Sig('-x', metavar='X'),
3614 Sig('a'),
3615 Sig('b'),
3616 ]
3617 argument_group_signatures = []
3618 usage = '''\
3619 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3620 [-h] [-w W] [-x X] a b
3621 '''
3622 help = usage + '''\
3623
3624 positional arguments:
3625 a
3626 b
3627
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003628 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003629 -h, --help show this help message and exit
3630 -w W
3631 -x X
3632 '''
3633 version = ''
3634
3635
3636class TestHelpUsageLongProgOptionsWrap(HelpTestCase):
3637 """Test usage messages where the prog is long and the optionals wrap"""
3638
3639 parser_signature = Sig(prog='P' * 60)
3640 argument_signatures = [
3641 Sig('-w', metavar='W' * 25),
3642 Sig('-x', metavar='X' * 25),
3643 Sig('-y', metavar='Y' * 25),
3644 Sig('-z', metavar='Z' * 25),
3645 Sig('a'),
3646 Sig('b'),
3647 ]
3648 argument_group_signatures = []
3649 usage = '''\
3650 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3651 [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3652[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3653 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3654 a b
3655 '''
3656 help = usage + '''\
3657
3658 positional arguments:
3659 a
3660 b
3661
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003662 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003663 -h, --help show this help message and exit
3664 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3665 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3666 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3667 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3668 '''
3669 version = ''
3670
3671
3672class TestHelpUsageLongProgPositionalsWrap(HelpTestCase):
3673 """Test usage messages where the prog is long and the positionals wrap"""
3674
3675 parser_signature = Sig(prog='P' * 60, add_help=False)
3676 argument_signatures = [
3677 Sig('a' * 25),
3678 Sig('b' * 25),
3679 Sig('c' * 25),
3680 ]
3681 argument_group_signatures = []
3682 usage = '''\
3683 usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
3684 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3685 ccccccccccccccccccccccccc
3686 '''
3687 help = usage + '''\
3688
3689 positional arguments:
3690 aaaaaaaaaaaaaaaaaaaaaaaaa
3691 bbbbbbbbbbbbbbbbbbbbbbbbb
3692 ccccccccccccccccccccccccc
3693 '''
3694 version = ''
3695
3696
3697class TestHelpUsageOptionalsWrap(HelpTestCase):
3698 """Test usage messages where the optionals wrap"""
3699
3700 parser_signature = Sig(prog='PROG')
3701 argument_signatures = [
3702 Sig('-w', metavar='W' * 25),
3703 Sig('-x', metavar='X' * 25),
3704 Sig('-y', metavar='Y' * 25),
3705 Sig('-z', metavar='Z' * 25),
3706 Sig('a'),
3707 Sig('b'),
3708 Sig('c'),
3709 ]
3710 argument_group_signatures = []
3711 usage = '''\
3712 usage: PROG [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \
3713[-x XXXXXXXXXXXXXXXXXXXXXXXXX]
3714 [-y YYYYYYYYYYYYYYYYYYYYYYYYY] \
3715[-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3716 a b c
3717 '''
3718 help = usage + '''\
3719
3720 positional arguments:
3721 a
3722 b
3723 c
3724
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003725 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003726 -h, --help show this help message and exit
3727 -w WWWWWWWWWWWWWWWWWWWWWWWWW
3728 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3729 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3730 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3731 '''
3732 version = ''
3733
3734
3735class TestHelpUsagePositionalsWrap(HelpTestCase):
3736 """Test usage messages where the positionals wrap"""
3737
3738 parser_signature = Sig(prog='PROG')
3739 argument_signatures = [
3740 Sig('-x'),
3741 Sig('-y'),
3742 Sig('-z'),
3743 Sig('a' * 25),
3744 Sig('b' * 25),
3745 Sig('c' * 25),
3746 ]
3747 argument_group_signatures = []
3748 usage = '''\
3749 usage: PROG [-h] [-x X] [-y Y] [-z Z]
3750 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3751 ccccccccccccccccccccccccc
3752 '''
3753 help = usage + '''\
3754
3755 positional arguments:
3756 aaaaaaaaaaaaaaaaaaaaaaaaa
3757 bbbbbbbbbbbbbbbbbbbbbbbbb
3758 ccccccccccccccccccccccccc
3759
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003760 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003761 -h, --help show this help message and exit
3762 -x X
3763 -y Y
3764 -z Z
3765 '''
3766 version = ''
3767
3768
3769class TestHelpUsageOptionalsPositionalsWrap(HelpTestCase):
3770 """Test usage messages where the optionals and positionals wrap"""
3771
3772 parser_signature = Sig(prog='PROG')
3773 argument_signatures = [
3774 Sig('-x', metavar='X' * 25),
3775 Sig('-y', metavar='Y' * 25),
3776 Sig('-z', metavar='Z' * 25),
3777 Sig('a' * 25),
3778 Sig('b' * 25),
3779 Sig('c' * 25),
3780 ]
3781 argument_group_signatures = []
3782 usage = '''\
3783 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3784[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3785 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3786 aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3787 ccccccccccccccccccccccccc
3788 '''
3789 help = usage + '''\
3790
3791 positional arguments:
3792 aaaaaaaaaaaaaaaaaaaaaaaaa
3793 bbbbbbbbbbbbbbbbbbbbbbbbb
3794 ccccccccccccccccccccccccc
3795
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003796 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003797 -h, --help show this help message and exit
3798 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3799 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3800 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3801 '''
3802 version = ''
3803
3804
3805class TestHelpUsageOptionalsOnlyWrap(HelpTestCase):
3806 """Test usage messages where there are only optionals and they wrap"""
3807
3808 parser_signature = Sig(prog='PROG')
3809 argument_signatures = [
3810 Sig('-x', metavar='X' * 25),
3811 Sig('-y', metavar='Y' * 25),
3812 Sig('-z', metavar='Z' * 25),
3813 ]
3814 argument_group_signatures = []
3815 usage = '''\
3816 usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \
3817[-y YYYYYYYYYYYYYYYYYYYYYYYYY]
3818 [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ]
3819 '''
3820 help = usage + '''\
3821
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003822 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003823 -h, --help show this help message and exit
3824 -x XXXXXXXXXXXXXXXXXXXXXXXXX
3825 -y YYYYYYYYYYYYYYYYYYYYYYYYY
3826 -z ZZZZZZZZZZZZZZZZZZZZZZZZZ
3827 '''
3828 version = ''
3829
3830
3831class TestHelpUsagePositionalsOnlyWrap(HelpTestCase):
3832 """Test usage messages where there are only positionals and they wrap"""
3833
3834 parser_signature = Sig(prog='PROG', add_help=False)
3835 argument_signatures = [
3836 Sig('a' * 25),
3837 Sig('b' * 25),
3838 Sig('c' * 25),
3839 ]
3840 argument_group_signatures = []
3841 usage = '''\
3842 usage: PROG aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb
3843 ccccccccccccccccccccccccc
3844 '''
3845 help = usage + '''\
3846
3847 positional arguments:
3848 aaaaaaaaaaaaaaaaaaaaaaaaa
3849 bbbbbbbbbbbbbbbbbbbbbbbbb
3850 ccccccccccccccccccccccccc
3851 '''
3852 version = ''
3853
3854
3855class TestHelpVariableExpansion(HelpTestCase):
3856 """Test that variables are expanded properly in help messages"""
3857
3858 parser_signature = Sig(prog='PROG')
3859 argument_signatures = [
3860 Sig('-x', type=int,
3861 help='x %(prog)s %(default)s %(type)s %%'),
3862 Sig('-y', action='store_const', default=42, const='XXX',
3863 help='y %(prog)s %(default)s %(const)s'),
3864 Sig('--foo', choices='abc',
3865 help='foo %(prog)s %(default)s %(choices)s'),
3866 Sig('--bar', default='baz', choices=[1, 2], metavar='BBB',
3867 help='bar %(prog)s %(default)s %(dest)s'),
3868 Sig('spam', help='spam %(prog)s %(default)s'),
3869 Sig('badger', default=0.5, help='badger %(prog)s %(default)s'),
3870 ]
3871 argument_group_signatures = [
3872 (Sig('group'), [
3873 Sig('-a', help='a %(prog)s %(default)s'),
3874 Sig('-b', default=-1, help='b %(prog)s %(default)s'),
3875 ])
3876 ]
3877 usage = ('''\
3878 usage: PROG [-h] [-x X] [-y] [--foo {a,b,c}] [--bar BBB] [-a A] [-b B]
3879 spam badger
3880 ''')
3881 help = usage + '''\
3882
3883 positional arguments:
3884 spam spam PROG None
3885 badger badger PROG 0.5
3886
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003887 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003888 -h, --help show this help message and exit
3889 -x X x PROG None int %
3890 -y y PROG 42 XXX
3891 --foo {a,b,c} foo PROG None a, b, c
3892 --bar BBB bar PROG baz bar
3893
3894 group:
3895 -a A a PROG None
3896 -b B b PROG -1
3897 '''
3898 version = ''
3899
3900
3901class TestHelpVariableExpansionUsageSupplied(HelpTestCase):
3902 """Test that variables are expanded properly when usage= is present"""
3903
3904 parser_signature = Sig(prog='PROG', usage='%(prog)s FOO')
3905 argument_signatures = []
3906 argument_group_signatures = []
3907 usage = ('''\
3908 usage: PROG FOO
3909 ''')
3910 help = usage + '''\
3911
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003912 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003913 -h, --help show this help message and exit
3914 '''
3915 version = ''
3916
3917
3918class TestHelpVariableExpansionNoArguments(HelpTestCase):
3919 """Test that variables are expanded properly with no arguments"""
3920
3921 parser_signature = Sig(prog='PROG', add_help=False)
3922 argument_signatures = []
3923 argument_group_signatures = []
3924 usage = ('''\
3925 usage: PROG
3926 ''')
3927 help = usage
3928 version = ''
3929
3930
3931class TestHelpSuppressUsage(HelpTestCase):
3932 """Test that items can be suppressed in usage messages"""
3933
3934 parser_signature = Sig(prog='PROG', usage=argparse.SUPPRESS)
3935 argument_signatures = [
3936 Sig('--foo', help='foo help'),
3937 Sig('spam', help='spam help'),
3938 ]
3939 argument_group_signatures = []
3940 help = '''\
3941 positional arguments:
3942 spam spam help
3943
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003944 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003945 -h, --help show this help message and exit
3946 --foo FOO foo help
3947 '''
3948 usage = ''
3949 version = ''
3950
3951
3952class TestHelpSuppressOptional(HelpTestCase):
3953 """Test that optional arguments can be suppressed in help messages"""
3954
3955 parser_signature = Sig(prog='PROG', add_help=False)
3956 argument_signatures = [
3957 Sig('--foo', help=argparse.SUPPRESS),
3958 Sig('spam', help='spam help'),
3959 ]
3960 argument_group_signatures = []
3961 usage = '''\
3962 usage: PROG spam
3963 '''
3964 help = usage + '''\
3965
3966 positional arguments:
3967 spam spam help
3968 '''
3969 version = ''
3970
3971
3972class TestHelpSuppressOptionalGroup(HelpTestCase):
3973 """Test that optional groups can be suppressed in help messages"""
3974
3975 parser_signature = Sig(prog='PROG')
3976 argument_signatures = [
3977 Sig('--foo', help='foo help'),
3978 Sig('spam', help='spam help'),
3979 ]
3980 argument_group_signatures = [
3981 (Sig('group'), [Sig('--bar', help=argparse.SUPPRESS)]),
3982 ]
3983 usage = '''\
3984 usage: PROG [-h] [--foo FOO] spam
3985 '''
3986 help = usage + '''\
3987
3988 positional arguments:
3989 spam spam help
3990
Raymond Hettinger41b223d2020-12-23 09:40:56 -08003991 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003992 -h, --help show this help message and exit
3993 --foo FOO foo help
3994 '''
3995 version = ''
3996
3997
3998class TestHelpSuppressPositional(HelpTestCase):
3999 """Test that positional arguments can be suppressed in help messages"""
4000
4001 parser_signature = Sig(prog='PROG')
4002 argument_signatures = [
4003 Sig('--foo', help='foo help'),
4004 Sig('spam', help=argparse.SUPPRESS),
4005 ]
4006 argument_group_signatures = []
4007 usage = '''\
4008 usage: PROG [-h] [--foo FOO]
4009 '''
4010 help = usage + '''\
4011
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004012 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004013 -h, --help show this help message and exit
4014 --foo FOO foo help
4015 '''
4016 version = ''
4017
4018
4019class TestHelpRequiredOptional(HelpTestCase):
4020 """Test that required options don't look optional"""
4021
4022 parser_signature = Sig(prog='PROG')
4023 argument_signatures = [
4024 Sig('--foo', required=True, help='foo help'),
4025 ]
4026 argument_group_signatures = []
4027 usage = '''\
4028 usage: PROG [-h] --foo FOO
4029 '''
4030 help = usage + '''\
4031
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004032 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004033 -h, --help show this help message and exit
4034 --foo FOO foo help
4035 '''
4036 version = ''
4037
4038
4039class TestHelpAlternatePrefixChars(HelpTestCase):
4040 """Test that options display with different prefix characters"""
4041
4042 parser_signature = Sig(prog='PROG', prefix_chars='^;', add_help=False)
4043 argument_signatures = [
4044 Sig('^^foo', action='store_true', help='foo help'),
4045 Sig(';b', ';;bar', help='bar help'),
4046 ]
4047 argument_group_signatures = []
4048 usage = '''\
4049 usage: PROG [^^foo] [;b BAR]
4050 '''
4051 help = usage + '''\
4052
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004053 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004054 ^^foo foo help
4055 ;b BAR, ;;bar BAR bar help
4056 '''
4057 version = ''
4058
4059
4060class TestHelpNoHelpOptional(HelpTestCase):
4061 """Test that the --help argument can be suppressed help messages"""
4062
4063 parser_signature = Sig(prog='PROG', add_help=False)
4064 argument_signatures = [
4065 Sig('--foo', help='foo help'),
4066 Sig('spam', help='spam help'),
4067 ]
4068 argument_group_signatures = []
4069 usage = '''\
4070 usage: PROG [--foo FOO] spam
4071 '''
4072 help = usage + '''\
4073
4074 positional arguments:
4075 spam spam help
4076
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004077 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004078 --foo FOO foo help
4079 '''
4080 version = ''
4081
4082
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004083class TestHelpNone(HelpTestCase):
4084 """Test that no errors occur if no help is specified"""
4085
4086 parser_signature = Sig(prog='PROG')
4087 argument_signatures = [
4088 Sig('--foo'),
4089 Sig('spam'),
4090 ]
4091 argument_group_signatures = []
4092 usage = '''\
4093 usage: PROG [-h] [--foo FOO] spam
4094 '''
4095 help = usage + '''\
4096
4097 positional arguments:
4098 spam
4099
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004100 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004101 -h, --help show this help message and exit
4102 --foo FOO
4103 '''
4104 version = ''
4105
4106
4107class TestHelpTupleMetavar(HelpTestCase):
4108 """Test specifying metavar as a tuple"""
4109
4110 parser_signature = Sig(prog='PROG')
4111 argument_signatures = [
4112 Sig('-w', help='w', nargs='+', metavar=('W1', 'W2')),
4113 Sig('-x', help='x', nargs='*', metavar=('X1', 'X2')),
4114 Sig('-y', help='y', nargs=3, metavar=('Y1', 'Y2', 'Y3')),
4115 Sig('-z', help='z', nargs='?', metavar=('Z1', )),
4116 ]
4117 argument_group_signatures = []
4118 usage = '''\
4119 usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] \
4120[-z [Z1]]
4121 '''
4122 help = usage + '''\
4123
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004124 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004125 -h, --help show this help message and exit
4126 -w W1 [W2 ...] w
4127 -x [X1 [X2 ...]] x
4128 -y Y1 Y2 Y3 y
4129 -z [Z1] z
4130 '''
4131 version = ''
4132
4133
4134class TestHelpRawText(HelpTestCase):
4135 """Test the RawTextHelpFormatter"""
4136
4137 parser_signature = Sig(
4138 prog='PROG', formatter_class=argparse.RawTextHelpFormatter,
4139 description='Keep the formatting\n'
4140 ' exactly as it is written\n'
4141 '\n'
4142 'here\n')
4143
4144 argument_signatures = [
4145 Sig('--foo', help=' foo help should also\n'
4146 'appear as given here'),
4147 Sig('spam', help='spam help'),
4148 ]
4149 argument_group_signatures = [
4150 (Sig('title', description=' This text\n'
4151 ' should be indented\n'
4152 ' exactly like it is here\n'),
4153 [Sig('--bar', help='bar help')]),
4154 ]
4155 usage = '''\
4156 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
4157 '''
4158 help = usage + '''\
4159
4160 Keep the formatting
4161 exactly as it is written
4162
4163 here
4164
4165 positional arguments:
4166 spam spam help
4167
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004168 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004169 -h, --help show this help message and exit
4170 --foo FOO foo help should also
4171 appear as given here
4172
4173 title:
4174 This text
4175 should be indented
4176 exactly like it is here
4177
4178 --bar BAR bar help
4179 '''
4180 version = ''
4181
4182
4183class TestHelpRawDescription(HelpTestCase):
4184 """Test the RawTextHelpFormatter"""
4185
4186 parser_signature = Sig(
4187 prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter,
4188 description='Keep the formatting\n'
4189 ' exactly as it is written\n'
4190 '\n'
4191 'here\n')
4192
4193 argument_signatures = [
4194 Sig('--foo', help=' foo help should not\n'
4195 ' retain this odd formatting'),
4196 Sig('spam', help='spam help'),
4197 ]
4198 argument_group_signatures = [
4199 (Sig('title', description=' This text\n'
4200 ' should be indented\n'
4201 ' exactly like it is here\n'),
4202 [Sig('--bar', help='bar help')]),
4203 ]
4204 usage = '''\
4205 usage: PROG [-h] [--foo FOO] [--bar BAR] spam
4206 '''
4207 help = usage + '''\
4208
4209 Keep the formatting
4210 exactly as it is written
4211
4212 here
4213
4214 positional arguments:
4215 spam spam help
4216
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004217 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004218 -h, --help show this help message and exit
4219 --foo FOO foo help should not retain this odd formatting
4220
4221 title:
4222 This text
4223 should be indented
4224 exactly like it is here
4225
4226 --bar BAR bar help
4227 '''
4228 version = ''
4229
4230
4231class TestHelpArgumentDefaults(HelpTestCase):
4232 """Test the ArgumentDefaultsHelpFormatter"""
4233
4234 parser_signature = Sig(
4235 prog='PROG', formatter_class=argparse.ArgumentDefaultsHelpFormatter,
4236 description='description')
4237
4238 argument_signatures = [
4239 Sig('--foo', help='foo help - oh and by the way, %(default)s'),
4240 Sig('--bar', action='store_true', help='bar help'),
4241 Sig('spam', help='spam help'),
4242 Sig('badger', nargs='?', default='wooden', help='badger help'),
4243 ]
4244 argument_group_signatures = [
4245 (Sig('title', description='description'),
4246 [Sig('--baz', type=int, default=42, help='baz help')]),
4247 ]
4248 usage = '''\
4249 usage: PROG [-h] [--foo FOO] [--bar] [--baz BAZ] spam [badger]
4250 '''
4251 help = usage + '''\
4252
4253 description
4254
4255 positional arguments:
4256 spam spam help
4257 badger badger help (default: wooden)
4258
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004259 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004260 -h, --help show this help message and exit
4261 --foo FOO foo help - oh and by the way, None
4262 --bar bar help (default: False)
4263
4264 title:
4265 description
4266
4267 --baz BAZ baz help (default: 42)
4268 '''
4269 version = ''
4270
Steven Bethard50fe5932010-05-24 03:47:38 +00004271class TestHelpVersionAction(HelpTestCase):
4272 """Test the default help for the version action"""
4273
4274 parser_signature = Sig(prog='PROG', description='description')
4275 argument_signatures = [Sig('-V', '--version', action='version', version='3.6')]
4276 argument_group_signatures = []
4277 usage = '''\
4278 usage: PROG [-h] [-V]
4279 '''
4280 help = usage + '''\
4281
4282 description
4283
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004284 options:
Steven Bethard50fe5932010-05-24 03:47:38 +00004285 -h, --help show this help message and exit
4286 -V, --version show program's version number and exit
4287 '''
4288 version = ''
4289
Berker Peksagecb75e22015-04-10 16:11:12 +03004290
4291class TestHelpVersionActionSuppress(HelpTestCase):
4292 """Test that the --version argument can be suppressed in help messages"""
4293
4294 parser_signature = Sig(prog='PROG')
4295 argument_signatures = [
4296 Sig('-v', '--version', action='version', version='1.0',
4297 help=argparse.SUPPRESS),
4298 Sig('--foo', help='foo help'),
4299 Sig('spam', help='spam help'),
4300 ]
4301 argument_group_signatures = []
4302 usage = '''\
4303 usage: PROG [-h] [--foo FOO] spam
4304 '''
4305 help = usage + '''\
4306
4307 positional arguments:
4308 spam spam help
4309
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004310 options:
Berker Peksagecb75e22015-04-10 16:11:12 +03004311 -h, --help show this help message and exit
4312 --foo FOO foo help
4313 '''
4314
4315
Steven Bethard8a6a1982011-03-27 13:53:53 +02004316class TestHelpSubparsersOrdering(HelpTestCase):
4317 """Test ordering of subcommands in help matches the code"""
4318 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004319 description='display some subcommands')
4320 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004321
4322 subparsers_signatures = [Sig(name=name)
4323 for name in ('a', 'b', 'c', 'd', 'e')]
4324
4325 usage = '''\
4326 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4327 '''
4328
4329 help = usage + '''\
4330
4331 display some subcommands
4332
4333 positional arguments:
4334 {a,b,c,d,e}
4335
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004336 options:
Steven Bethard8a6a1982011-03-27 13:53:53 +02004337 -h, --help show this help message and exit
4338 -v, --version show program's version number and exit
4339 '''
4340
4341 version = '''\
4342 0.1
4343 '''
4344
4345class TestHelpSubparsersWithHelpOrdering(HelpTestCase):
4346 """Test ordering of subcommands in help matches the code"""
4347 parser_signature = Sig(prog='PROG',
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004348 description='display some subcommands')
4349 argument_signatures = [Sig('-v', '--version', action='version', version='0.1')]
Steven Bethard8a6a1982011-03-27 13:53:53 +02004350
4351 subcommand_data = (('a', 'a subcommand help'),
4352 ('b', 'b subcommand help'),
4353 ('c', 'c subcommand help'),
4354 ('d', 'd subcommand help'),
4355 ('e', 'e subcommand help'),
4356 )
4357
4358 subparsers_signatures = [Sig(name=name, help=help)
4359 for name, help in subcommand_data]
4360
4361 usage = '''\
4362 usage: PROG [-h] [-v] {a,b,c,d,e} ...
4363 '''
4364
4365 help = usage + '''\
4366
4367 display some subcommands
4368
4369 positional arguments:
4370 {a,b,c,d,e}
4371 a a subcommand help
4372 b b subcommand help
4373 c c subcommand help
4374 d d subcommand help
4375 e e subcommand help
4376
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004377 options:
Steven Bethard8a6a1982011-03-27 13:53:53 +02004378 -h, --help show this help message and exit
4379 -v, --version show program's version number and exit
4380 '''
4381
4382 version = '''\
4383 0.1
4384 '''
4385
4386
Steven Bethard0331e902011-03-26 14:48:04 +01004387
4388class TestHelpMetavarTypeFormatter(HelpTestCase):
Steven Bethard0331e902011-03-26 14:48:04 +01004389
4390 def custom_type(string):
4391 return string
4392
4393 parser_signature = Sig(prog='PROG', description='description',
4394 formatter_class=argparse.MetavarTypeHelpFormatter)
4395 argument_signatures = [Sig('a', type=int),
4396 Sig('-b', type=custom_type),
4397 Sig('-c', type=float, metavar='SOME FLOAT')]
4398 argument_group_signatures = []
4399 usage = '''\
4400 usage: PROG [-h] [-b custom_type] [-c SOME FLOAT] int
4401 '''
4402 help = usage + '''\
4403
4404 description
4405
4406 positional arguments:
4407 int
4408
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004409 options:
Steven Bethard0331e902011-03-26 14:48:04 +01004410 -h, --help show this help message and exit
4411 -b custom_type
4412 -c SOME FLOAT
4413 '''
4414 version = ''
4415
4416
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004417# =====================================
4418# Optional/Positional constructor tests
4419# =====================================
4420
4421class TestInvalidArgumentConstructors(TestCase):
4422 """Test a bunch of invalid Argument constructors"""
4423
4424 def assertTypeError(self, *args, **kwargs):
4425 parser = argparse.ArgumentParser()
4426 self.assertRaises(TypeError, parser.add_argument,
4427 *args, **kwargs)
4428
4429 def assertValueError(self, *args, **kwargs):
4430 parser = argparse.ArgumentParser()
4431 self.assertRaises(ValueError, parser.add_argument,
4432 *args, **kwargs)
4433
4434 def test_invalid_keyword_arguments(self):
4435 self.assertTypeError('-x', bar=None)
4436 self.assertTypeError('-y', callback='foo')
4437 self.assertTypeError('-y', callback_args=())
4438 self.assertTypeError('-y', callback_kwargs={})
4439
4440 def test_missing_destination(self):
4441 self.assertTypeError()
4442 for action in ['append', 'store']:
4443 self.assertTypeError(action=action)
4444
4445 def test_invalid_option_strings(self):
4446 self.assertValueError('--')
4447 self.assertValueError('---')
4448
4449 def test_invalid_type(self):
4450 self.assertValueError('--foo', type='int')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004451 self.assertValueError('--foo', type=(int, float))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004452
4453 def test_invalid_action(self):
4454 self.assertValueError('-x', action='foo')
4455 self.assertValueError('foo', action='baz')
Steven Bethard7cb20a82011-04-04 01:53:02 +02004456 self.assertValueError('--foo', action=('store', 'append'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004457 parser = argparse.ArgumentParser()
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004458 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004459 parser.add_argument("--foo", action="store-true")
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004460 self.assertIn('unknown action', str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004461
4462 def test_multiple_dest(self):
4463 parser = argparse.ArgumentParser()
4464 parser.add_argument(dest='foo')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004465 with self.assertRaises(ValueError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004466 parser.add_argument('bar', dest='baz')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004467 self.assertIn('dest supplied twice for positional argument',
4468 str(cm.exception))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004469
4470 def test_no_argument_actions(self):
4471 for action in ['store_const', 'store_true', 'store_false',
4472 'append_const', 'count']:
4473 for attrs in [dict(type=int), dict(nargs='+'),
4474 dict(choices='ab')]:
4475 self.assertTypeError('-x', action=action, **attrs)
4476
4477 def test_no_argument_no_const_actions(self):
4478 # options with zero arguments
4479 for action in ['store_true', 'store_false', 'count']:
4480
4481 # const is always disallowed
4482 self.assertTypeError('-x', const='foo', action=action)
4483
4484 # nargs is always disallowed
4485 self.assertTypeError('-x', nargs='*', action=action)
4486
4487 def test_more_than_one_argument_actions(self):
4488 for action in ['store', 'append']:
4489
4490 # nargs=0 is disallowed
4491 self.assertValueError('-x', nargs=0, action=action)
4492 self.assertValueError('spam', nargs=0, action=action)
4493
4494 # const is disallowed with non-optional arguments
4495 for nargs in [1, '*', '+']:
4496 self.assertValueError('-x', const='foo',
4497 nargs=nargs, action=action)
4498 self.assertValueError('spam', const='foo',
4499 nargs=nargs, action=action)
4500
4501 def test_required_const_actions(self):
4502 for action in ['store_const', 'append_const']:
4503
4504 # nargs is always disallowed
4505 self.assertTypeError('-x', nargs='+', action=action)
4506
4507 def test_parsers_action_missing_params(self):
4508 self.assertTypeError('command', action='parsers')
4509 self.assertTypeError('command', action='parsers', prog='PROG')
4510 self.assertTypeError('command', action='parsers',
4511 parser_class=argparse.ArgumentParser)
4512
4513 def test_required_positional(self):
4514 self.assertTypeError('foo', required=True)
4515
4516 def test_user_defined_action(self):
4517
4518 class Success(Exception):
4519 pass
4520
4521 class Action(object):
4522
4523 def __init__(self,
4524 option_strings,
4525 dest,
4526 const,
4527 default,
4528 required=False):
4529 if dest == 'spam':
4530 if const is Success:
4531 if default is Success:
4532 raise Success()
4533
4534 def __call__(self, *args, **kwargs):
4535 pass
4536
4537 parser = argparse.ArgumentParser()
4538 self.assertRaises(Success, parser.add_argument, '--spam',
4539 action=Action, default=Success, const=Success)
4540 self.assertRaises(Success, parser.add_argument, 'spam',
4541 action=Action, default=Success, const=Success)
4542
4543# ================================
4544# Actions returned by add_argument
4545# ================================
4546
4547class TestActionsReturned(TestCase):
4548
4549 def test_dest(self):
4550 parser = argparse.ArgumentParser()
4551 action = parser.add_argument('--foo')
4552 self.assertEqual(action.dest, 'foo')
4553 action = parser.add_argument('-b', '--bar')
4554 self.assertEqual(action.dest, 'bar')
4555 action = parser.add_argument('-x', '-y')
4556 self.assertEqual(action.dest, 'x')
4557
4558 def test_misc(self):
4559 parser = argparse.ArgumentParser()
4560 action = parser.add_argument('--foo', nargs='?', const=42,
4561 default=84, type=int, choices=[1, 2],
4562 help='FOO', metavar='BAR', dest='baz')
4563 self.assertEqual(action.nargs, '?')
4564 self.assertEqual(action.const, 42)
4565 self.assertEqual(action.default, 84)
4566 self.assertEqual(action.type, int)
4567 self.assertEqual(action.choices, [1, 2])
4568 self.assertEqual(action.help, 'FOO')
4569 self.assertEqual(action.metavar, 'BAR')
4570 self.assertEqual(action.dest, 'baz')
4571
4572
4573# ================================
4574# Argument conflict handling tests
4575# ================================
4576
4577class TestConflictHandling(TestCase):
4578
4579 def test_bad_type(self):
4580 self.assertRaises(ValueError, argparse.ArgumentParser,
4581 conflict_handler='foo')
4582
4583 def test_conflict_error(self):
4584 parser = argparse.ArgumentParser()
4585 parser.add_argument('-x')
4586 self.assertRaises(argparse.ArgumentError,
4587 parser.add_argument, '-x')
4588 parser.add_argument('--spam')
4589 self.assertRaises(argparse.ArgumentError,
4590 parser.add_argument, '--spam')
4591
4592 def test_resolve_error(self):
4593 get_parser = argparse.ArgumentParser
4594 parser = get_parser(prog='PROG', conflict_handler='resolve')
4595
4596 parser.add_argument('-x', help='OLD X')
4597 parser.add_argument('-x', help='NEW X')
4598 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4599 usage: PROG [-h] [-x X]
4600
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004601 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004602 -h, --help show this help message and exit
4603 -x X NEW X
4604 '''))
4605
4606 parser.add_argument('--spam', metavar='OLD_SPAM')
4607 parser.add_argument('--spam', metavar='NEW_SPAM')
4608 self.assertEqual(parser.format_help(), textwrap.dedent('''\
4609 usage: PROG [-h] [-x X] [--spam NEW_SPAM]
4610
Raymond Hettinger41b223d2020-12-23 09:40:56 -08004611 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004612 -h, --help show this help message and exit
4613 -x X NEW X
4614 --spam NEW_SPAM
4615 '''))
4616
4617
4618# =============================
4619# Help and Version option tests
4620# =============================
4621
4622class TestOptionalsHelpVersionActions(TestCase):
4623 """Test the help and version actions"""
4624
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004625 def assertPrintHelpExit(self, parser, args_str):
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004626 with self.assertRaises(ArgumentParserError) as cm:
4627 parser.parse_args(args_str.split())
4628 self.assertEqual(parser.format_help(), cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004629
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004630 def assertArgumentParserError(self, parser, *args):
4631 self.assertRaises(ArgumentParserError, parser.parse_args, args)
4632
4633 def test_version(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004634 parser = ErrorRaisingArgumentParser()
4635 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004636 self.assertPrintHelpExit(parser, '-h')
4637 self.assertPrintHelpExit(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004638 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004639
4640 def test_version_format(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004641 parser = ErrorRaisingArgumentParser(prog='PPP')
4642 parser.add_argument('-v', '--version', action='version', version='%(prog)s 3.5')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004643 with self.assertRaises(ArgumentParserError) as cm:
4644 parser.parse_args(['-v'])
4645 self.assertEqual('PPP 3.5\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004646
4647 def test_version_no_help(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004648 parser = ErrorRaisingArgumentParser(add_help=False)
4649 parser.add_argument('-v', '--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004650 self.assertArgumentParserError(parser, '-h')
4651 self.assertArgumentParserError(parser, '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004652 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004653
4654 def test_version_action(self):
4655 parser = ErrorRaisingArgumentParser(prog='XXX')
4656 parser.add_argument('-V', action='version', version='%(prog)s 3.7')
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004657 with self.assertRaises(ArgumentParserError) as cm:
4658 parser.parse_args(['-V'])
4659 self.assertEqual('XXX 3.7\n', cm.exception.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004660
4661 def test_no_help(self):
4662 parser = ErrorRaisingArgumentParser(add_help=False)
4663 self.assertArgumentParserError(parser, '-h')
4664 self.assertArgumentParserError(parser, '--help')
4665 self.assertArgumentParserError(parser, '-v')
4666 self.assertArgumentParserError(parser, '--version')
4667
4668 def test_alternate_help_version(self):
4669 parser = ErrorRaisingArgumentParser()
4670 parser.add_argument('-x', action='help')
4671 parser.add_argument('-y', action='version')
4672 self.assertPrintHelpExit(parser, '-x')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004673 self.assertArgumentParserError(parser, '-v')
4674 self.assertArgumentParserError(parser, '--version')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004675 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004676
4677 def test_help_version_extra_arguments(self):
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004678 parser = ErrorRaisingArgumentParser()
4679 parser.add_argument('--version', action='version', version='1.0')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004680 parser.add_argument('-x', action='store_true')
4681 parser.add_argument('y')
4682
4683 # try all combinations of valid prefixes and suffixes
4684 valid_prefixes = ['', '-x', 'foo', '-x bar', 'baz -x']
4685 valid_suffixes = valid_prefixes + ['--bad-option', 'foo bar baz']
4686 for prefix in valid_prefixes:
4687 for suffix in valid_suffixes:
4688 format = '%s %%s %s' % (prefix, suffix)
4689 self.assertPrintHelpExit(parser, format % '-h')
4690 self.assertPrintHelpExit(parser, format % '--help')
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004691 self.assertRaises(AttributeError, getattr, parser, 'format_version')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004692
4693
4694# ======================
4695# str() and repr() tests
4696# ======================
4697
4698class TestStrings(TestCase):
4699 """Test str() and repr() on Optionals and Positionals"""
4700
4701 def assertStringEqual(self, obj, result_string):
4702 for func in [str, repr]:
4703 self.assertEqual(func(obj), result_string)
4704
4705 def test_optional(self):
4706 option = argparse.Action(
4707 option_strings=['--foo', '-a', '-b'],
4708 dest='b',
4709 type='int',
4710 nargs='+',
4711 default=42,
4712 choices=[1, 2, 3],
4713 help='HELP',
4714 metavar='METAVAR')
4715 string = (
4716 "Action(option_strings=['--foo', '-a', '-b'], dest='b', "
4717 "nargs='+', const=None, default=42, type='int', "
4718 "choices=[1, 2, 3], help='HELP', metavar='METAVAR')")
4719 self.assertStringEqual(option, string)
4720
4721 def test_argument(self):
4722 argument = argparse.Action(
4723 option_strings=[],
4724 dest='x',
4725 type=float,
4726 nargs='?',
4727 default=2.5,
4728 choices=[0.5, 1.5, 2.5],
4729 help='H HH H',
4730 metavar='MV MV MV')
4731 string = (
4732 "Action(option_strings=[], dest='x', nargs='?', "
4733 "const=None, default=2.5, type=%r, choices=[0.5, 1.5, 2.5], "
4734 "help='H HH H', metavar='MV MV MV')" % float)
4735 self.assertStringEqual(argument, string)
4736
4737 def test_namespace(self):
4738 ns = argparse.Namespace(foo=42, bar='spam')
Raymond Hettinger96819532020-05-17 18:53:01 -07004739 string = "Namespace(foo=42, bar='spam')"
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004740 self.assertStringEqual(ns, string)
4741
Berker Peksag76b17142015-07-29 23:51:47 +03004742 def test_namespace_starkwargs_notidentifier(self):
4743 ns = argparse.Namespace(**{'"': 'quote'})
4744 string = """Namespace(**{'"': 'quote'})"""
4745 self.assertStringEqual(ns, string)
4746
4747 def test_namespace_kwargs_and_starkwargs_notidentifier(self):
4748 ns = argparse.Namespace(a=1, **{'"': 'quote'})
4749 string = """Namespace(a=1, **{'"': 'quote'})"""
4750 self.assertStringEqual(ns, string)
4751
4752 def test_namespace_starkwargs_identifier(self):
4753 ns = argparse.Namespace(**{'valid': True})
4754 string = "Namespace(valid=True)"
4755 self.assertStringEqual(ns, string)
4756
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004757 def test_parser(self):
4758 parser = argparse.ArgumentParser(prog='PROG')
4759 string = (
4760 "ArgumentParser(prog='PROG', usage=None, description=None, "
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02004761 "formatter_class=%r, conflict_handler='error', "
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004762 "add_help=True)" % argparse.HelpFormatter)
4763 self.assertStringEqual(parser, string)
4764
4765# ===============
4766# Namespace tests
4767# ===============
4768
4769class TestNamespace(TestCase):
4770
4771 def test_constructor(self):
4772 ns = argparse.Namespace()
4773 self.assertRaises(AttributeError, getattr, ns, 'x')
4774
4775 ns = argparse.Namespace(a=42, b='spam')
4776 self.assertEqual(ns.a, 42)
4777 self.assertEqual(ns.b, 'spam')
4778
4779 def test_equality(self):
4780 ns1 = argparse.Namespace(a=1, b=2)
4781 ns2 = argparse.Namespace(b=2, a=1)
4782 ns3 = argparse.Namespace(a=1)
4783 ns4 = argparse.Namespace(b=2)
4784
4785 self.assertEqual(ns1, ns2)
4786 self.assertNotEqual(ns1, ns3)
4787 self.assertNotEqual(ns1, ns4)
4788 self.assertNotEqual(ns2, ns3)
4789 self.assertNotEqual(ns2, ns4)
4790 self.assertTrue(ns1 != ns3)
4791 self.assertTrue(ns1 != ns4)
4792 self.assertTrue(ns2 != ns3)
4793 self.assertTrue(ns2 != ns4)
4794
Berker Peksagc16387b2016-09-28 17:21:52 +03004795 def test_equality_returns_notimplemented(self):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07004796 # See issue 21481
4797 ns = argparse.Namespace(a=1, b=2)
4798 self.assertIs(ns.__eq__(None), NotImplemented)
4799 self.assertIs(ns.__ne__(None), NotImplemented)
4800
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004801
4802# ===================
4803# File encoding tests
4804# ===================
4805
4806class TestEncoding(TestCase):
4807
4808 def _test_module_encoding(self, path):
4809 path, _ = os.path.splitext(path)
4810 path += ".py"
Victor Stinner272d8882017-06-16 08:59:01 +02004811 with open(path, 'r', encoding='utf-8') as f:
Antoine Pitroub86680e2010-10-14 21:15:17 +00004812 f.read()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004813
4814 def test_argparse_module_encoding(self):
4815 self._test_module_encoding(argparse.__file__)
4816
4817 def test_test_argparse_module_encoding(self):
4818 self._test_module_encoding(__file__)
4819
4820# ===================
4821# ArgumentError tests
4822# ===================
4823
4824class TestArgumentError(TestCase):
4825
4826 def test_argument_error(self):
4827 msg = "my error here"
4828 error = argparse.ArgumentError(None, msg)
4829 self.assertEqual(str(error), msg)
4830
4831# =======================
4832# ArgumentTypeError tests
4833# =======================
4834
R. David Murray722b5fd2010-11-20 03:48:58 +00004835class TestArgumentTypeError(TestCase):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004836
4837 def test_argument_type_error(self):
4838
4839 def spam(string):
4840 raise argparse.ArgumentTypeError('spam!')
4841
4842 parser = ErrorRaisingArgumentParser(prog='PROG', add_help=False)
4843 parser.add_argument('x', type=spam)
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004844 with self.assertRaises(ArgumentParserError) as cm:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004845 parser.parse_args(['XXX'])
Berker Peksag1c5f56a2014-07-06 09:33:20 +03004846 self.assertEqual('usage: PROG x\nPROG: error: argument x: spam!\n',
4847 cm.exception.stderr)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004848
R David Murrayf97c59a2011-06-09 12:34:07 -04004849# =========================
4850# MessageContentError tests
4851# =========================
4852
4853class TestMessageContentError(TestCase):
4854
4855 def test_missing_argument_name_in_message(self):
4856 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4857 parser.add_argument('req_pos', type=str)
4858 parser.add_argument('-req_opt', type=int, required=True)
4859 parser.add_argument('need_one', type=str, nargs='+')
4860
4861 with self.assertRaises(ArgumentParserError) as cm:
4862 parser.parse_args([])
4863 msg = str(cm.exception)
4864 self.assertRegex(msg, 'req_pos')
4865 self.assertRegex(msg, 'req_opt')
4866 self.assertRegex(msg, 'need_one')
4867 with self.assertRaises(ArgumentParserError) as cm:
4868 parser.parse_args(['myXargument'])
4869 msg = str(cm.exception)
4870 self.assertNotIn(msg, 'req_pos')
4871 self.assertRegex(msg, 'req_opt')
4872 self.assertRegex(msg, 'need_one')
4873 with self.assertRaises(ArgumentParserError) as cm:
4874 parser.parse_args(['myXargument', '-req_opt=1'])
4875 msg = str(cm.exception)
4876 self.assertNotIn(msg, 'req_pos')
4877 self.assertNotIn(msg, 'req_opt')
4878 self.assertRegex(msg, 'need_one')
4879
4880 def test_optional_optional_not_in_message(self):
4881 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4882 parser.add_argument('req_pos', type=str)
4883 parser.add_argument('--req_opt', type=int, required=True)
4884 parser.add_argument('--opt_opt', type=bool, nargs='?',
4885 default=True)
4886 with self.assertRaises(ArgumentParserError) as cm:
4887 parser.parse_args([])
4888 msg = str(cm.exception)
4889 self.assertRegex(msg, 'req_pos')
4890 self.assertRegex(msg, 'req_opt')
4891 self.assertNotIn(msg, 'opt_opt')
4892 with self.assertRaises(ArgumentParserError) as cm:
4893 parser.parse_args(['--req_opt=1'])
4894 msg = str(cm.exception)
4895 self.assertRegex(msg, 'req_pos')
4896 self.assertNotIn(msg, 'req_opt')
4897 self.assertNotIn(msg, 'opt_opt')
4898
4899 def test_optional_positional_not_in_message(self):
4900 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
4901 parser.add_argument('req_pos')
4902 parser.add_argument('optional_positional', nargs='?', default='eggs')
4903 with self.assertRaises(ArgumentParserError) as cm:
4904 parser.parse_args([])
4905 msg = str(cm.exception)
4906 self.assertRegex(msg, 'req_pos')
4907 self.assertNotIn(msg, 'optional_positional')
4908
4909
R David Murray6fb8fb12012-08-31 22:45:20 -04004910# ================================================
4911# Check that the type function is called only once
4912# ================================================
4913
4914class TestTypeFunctionCallOnlyOnce(TestCase):
4915
4916 def test_type_function_call_only_once(self):
4917 def spam(string_to_convert):
4918 self.assertEqual(string_to_convert, 'spam!')
4919 return 'foo_converted'
4920
4921 parser = argparse.ArgumentParser()
4922 parser.add_argument('--foo', type=spam, default='bar')
4923 args = parser.parse_args('--foo spam!'.split())
4924 self.assertEqual(NS(foo='foo_converted'), args)
4925
Barry Warsaweaae1b72012-09-12 14:34:50 -04004926# ==================================================================
4927# Check semantics regarding the default argument and type conversion
4928# ==================================================================
R David Murray6fb8fb12012-08-31 22:45:20 -04004929
Barry Warsaweaae1b72012-09-12 14:34:50 -04004930class TestTypeFunctionCalledOnDefault(TestCase):
R David Murray6fb8fb12012-08-31 22:45:20 -04004931
4932 def test_type_function_call_with_non_string_default(self):
4933 def spam(int_to_convert):
4934 self.assertEqual(int_to_convert, 0)
4935 return 'foo_converted'
4936
4937 parser = argparse.ArgumentParser()
4938 parser.add_argument('--foo', type=spam, default=0)
4939 args = parser.parse_args([])
Barry Warsaweaae1b72012-09-12 14:34:50 -04004940 # foo should *not* be converted because its default is not a string.
4941 self.assertEqual(NS(foo=0), args)
4942
4943 def test_type_function_call_with_string_default(self):
4944 def spam(int_to_convert):
4945 return 'foo_converted'
4946
4947 parser = argparse.ArgumentParser()
4948 parser.add_argument('--foo', type=spam, default='0')
4949 args = parser.parse_args([])
4950 # foo is converted because its default is a string.
R David Murray6fb8fb12012-08-31 22:45:20 -04004951 self.assertEqual(NS(foo='foo_converted'), args)
4952
Barry Warsaweaae1b72012-09-12 14:34:50 -04004953 def test_no_double_type_conversion_of_default(self):
4954 def extend(str_to_convert):
4955 return str_to_convert + '*'
4956
4957 parser = argparse.ArgumentParser()
4958 parser.add_argument('--test', type=extend, default='*')
4959 args = parser.parse_args([])
4960 # The test argument will be two stars, one coming from the default
4961 # value and one coming from the type conversion being called exactly
4962 # once.
4963 self.assertEqual(NS(test='**'), args)
4964
Barry Warsaw4b2f9e92012-09-11 22:38:47 -04004965 def test_issue_15906(self):
4966 # Issue #15906: When action='append', type=str, default=[] are
4967 # providing, the dest value was the string representation "[]" when it
4968 # should have been an empty list.
4969 parser = argparse.ArgumentParser()
4970 parser.add_argument('--test', dest='test', type=str,
4971 default=[], action='append')
4972 args = parser.parse_args([])
4973 self.assertEqual(args.test, [])
4974
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004975# ======================
4976# parse_known_args tests
4977# ======================
4978
4979class TestParseKnownArgs(TestCase):
4980
R David Murrayb5228282012-09-08 12:08:01 -04004981 def test_arguments_tuple(self):
4982 parser = argparse.ArgumentParser()
4983 parser.parse_args(())
4984
4985 def test_arguments_list(self):
4986 parser = argparse.ArgumentParser()
4987 parser.parse_args([])
4988
4989 def test_arguments_tuple_positional(self):
4990 parser = argparse.ArgumentParser()
4991 parser.add_argument('x')
4992 parser.parse_args(('x',))
4993
4994 def test_arguments_list_positional(self):
4995 parser = argparse.ArgumentParser()
4996 parser.add_argument('x')
4997 parser.parse_args(['x'])
4998
Benjamin Peterson698a18a2010-03-02 22:34:37 +00004999 def test_optionals(self):
5000 parser = argparse.ArgumentParser()
5001 parser.add_argument('--foo')
5002 args, extras = parser.parse_known_args('--foo F --bar --baz'.split())
5003 self.assertEqual(NS(foo='F'), args)
5004 self.assertEqual(['--bar', '--baz'], extras)
5005
5006 def test_mixed(self):
5007 parser = argparse.ArgumentParser()
5008 parser.add_argument('-v', nargs='?', const=1, type=int)
5009 parser.add_argument('--spam', action='store_false')
5010 parser.add_argument('badger')
5011
5012 argv = ["B", "C", "--foo", "-v", "3", "4"]
5013 args, extras = parser.parse_known_args(argv)
5014 self.assertEqual(NS(v=3, spam=True, badger="B"), args)
5015 self.assertEqual(["C", "--foo", "4"], extras)
5016
R. David Murray0f6b9d22017-09-06 20:25:40 -04005017# ===========================
5018# parse_intermixed_args tests
5019# ===========================
5020
5021class TestIntermixedArgs(TestCase):
5022 def test_basic(self):
5023 # test parsing intermixed optionals and positionals
5024 parser = argparse.ArgumentParser(prog='PROG')
5025 parser.add_argument('--foo', dest='foo')
5026 bar = parser.add_argument('--bar', dest='bar', required=True)
5027 parser.add_argument('cmd')
5028 parser.add_argument('rest', nargs='*', type=int)
5029 argv = 'cmd --foo x 1 --bar y 2 3'.split()
5030 args = parser.parse_intermixed_args(argv)
5031 # rest gets [1,2,3] despite the foo and bar strings
5032 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args)
5033
5034 args, extras = parser.parse_known_args(argv)
5035 # cannot parse the '1,2,3'
5036 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[]), args)
5037 self.assertEqual(["1", "2", "3"], extras)
5038
5039 argv = 'cmd --foo x 1 --error 2 --bar y 3'.split()
5040 args, extras = parser.parse_known_intermixed_args(argv)
5041 # unknown optionals go into extras
5042 self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1]), args)
5043 self.assertEqual(['--error', '2', '3'], extras)
5044
5045 # restores attributes that were temporarily changed
5046 self.assertIsNone(parser.usage)
5047 self.assertEqual(bar.required, True)
5048
5049 def test_remainder(self):
5050 # Intermixed and remainder are incompatible
5051 parser = ErrorRaisingArgumentParser(prog='PROG')
5052 parser.add_argument('-z')
5053 parser.add_argument('x')
5054 parser.add_argument('y', nargs='...')
5055 argv = 'X A B -z Z'.split()
5056 # intermixed fails with '...' (also 'A...')
5057 # self.assertRaises(TypeError, parser.parse_intermixed_args, argv)
5058 with self.assertRaises(TypeError) as cm:
5059 parser.parse_intermixed_args(argv)
5060 self.assertRegex(str(cm.exception), r'\.\.\.')
5061
5062 def test_exclusive(self):
5063 # mutually exclusive group; intermixed works fine
5064 parser = ErrorRaisingArgumentParser(prog='PROG')
5065 group = parser.add_mutually_exclusive_group(required=True)
5066 group.add_argument('--foo', action='store_true', help='FOO')
5067 group.add_argument('--spam', help='SPAM')
5068 parser.add_argument('badger', nargs='*', default='X', help='BADGER')
5069 args = parser.parse_intermixed_args('1 --foo 2'.split())
5070 self.assertEqual(NS(badger=['1', '2'], foo=True, spam=None), args)
5071 self.assertRaises(ArgumentParserError, parser.parse_intermixed_args, '1 2'.split())
5072 self.assertEqual(group.required, True)
5073
5074 def test_exclusive_incompatible(self):
5075 # mutually exclusive group including positional - fail
5076 parser = ErrorRaisingArgumentParser(prog='PROG')
5077 group = parser.add_mutually_exclusive_group(required=True)
5078 group.add_argument('--foo', action='store_true', help='FOO')
5079 group.add_argument('--spam', help='SPAM')
5080 group.add_argument('badger', nargs='*', default='X', help='BADGER')
5081 self.assertRaises(TypeError, parser.parse_intermixed_args, [])
5082 self.assertEqual(group.required, True)
5083
5084class TestIntermixedMessageContentError(TestCase):
5085 # case where Intermixed gives different error message
5086 # error is raised by 1st parsing step
5087 def test_missing_argument_name_in_message(self):
5088 parser = ErrorRaisingArgumentParser(prog='PROG', usage='')
5089 parser.add_argument('req_pos', type=str)
5090 parser.add_argument('-req_opt', type=int, required=True)
5091
5092 with self.assertRaises(ArgumentParserError) as cm:
5093 parser.parse_args([])
5094 msg = str(cm.exception)
5095 self.assertRegex(msg, 'req_pos')
5096 self.assertRegex(msg, 'req_opt')
5097
5098 with self.assertRaises(ArgumentParserError) as cm:
5099 parser.parse_intermixed_args([])
5100 msg = str(cm.exception)
5101 self.assertNotRegex(msg, 'req_pos')
5102 self.assertRegex(msg, 'req_opt')
5103
Steven Bethard8d9a4622011-03-26 17:33:56 +01005104# ==========================
5105# add_argument metavar tests
5106# ==========================
5107
5108class TestAddArgumentMetavar(TestCase):
5109
5110 EXPECTED_MESSAGE = "length of metavar tuple does not match nargs"
5111
5112 def do_test_no_exception(self, nargs, metavar):
5113 parser = argparse.ArgumentParser()
5114 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
5115
5116 def do_test_exception(self, nargs, metavar):
5117 parser = argparse.ArgumentParser()
5118 with self.assertRaises(ValueError) as cm:
5119 parser.add_argument("--foo", nargs=nargs, metavar=metavar)
5120 self.assertEqual(cm.exception.args[0], self.EXPECTED_MESSAGE)
5121
5122 # Unit tests for different values of metavar when nargs=None
5123
5124 def test_nargs_None_metavar_string(self):
5125 self.do_test_no_exception(nargs=None, metavar="1")
5126
5127 def test_nargs_None_metavar_length0(self):
5128 self.do_test_exception(nargs=None, metavar=tuple())
5129
5130 def test_nargs_None_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005131 self.do_test_no_exception(nargs=None, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005132
5133 def test_nargs_None_metavar_length2(self):
5134 self.do_test_exception(nargs=None, metavar=("1", "2"))
5135
5136 def test_nargs_None_metavar_length3(self):
5137 self.do_test_exception(nargs=None, metavar=("1", "2", "3"))
5138
5139 # Unit tests for different values of metavar when nargs=?
5140
5141 def test_nargs_optional_metavar_string(self):
5142 self.do_test_no_exception(nargs="?", metavar="1")
5143
5144 def test_nargs_optional_metavar_length0(self):
5145 self.do_test_exception(nargs="?", metavar=tuple())
5146
5147 def test_nargs_optional_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005148 self.do_test_no_exception(nargs="?", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005149
5150 def test_nargs_optional_metavar_length2(self):
5151 self.do_test_exception(nargs="?", metavar=("1", "2"))
5152
5153 def test_nargs_optional_metavar_length3(self):
5154 self.do_test_exception(nargs="?", metavar=("1", "2", "3"))
5155
5156 # Unit tests for different values of metavar when nargs=*
5157
5158 def test_nargs_zeroormore_metavar_string(self):
5159 self.do_test_no_exception(nargs="*", metavar="1")
5160
5161 def test_nargs_zeroormore_metavar_length0(self):
5162 self.do_test_exception(nargs="*", metavar=tuple())
5163
5164 def test_nargs_zeroormore_metavar_length1(self):
Brandt Buchera0ed99b2019-11-11 12:47:48 -08005165 self.do_test_no_exception(nargs="*", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005166
5167 def test_nargs_zeroormore_metavar_length2(self):
5168 self.do_test_no_exception(nargs="*", metavar=("1", "2"))
5169
5170 def test_nargs_zeroormore_metavar_length3(self):
5171 self.do_test_exception(nargs="*", metavar=("1", "2", "3"))
5172
5173 # Unit tests for different values of metavar when nargs=+
5174
5175 def test_nargs_oneormore_metavar_string(self):
5176 self.do_test_no_exception(nargs="+", metavar="1")
5177
5178 def test_nargs_oneormore_metavar_length0(self):
5179 self.do_test_exception(nargs="+", metavar=tuple())
5180
5181 def test_nargs_oneormore_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005182 self.do_test_exception(nargs="+", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005183
5184 def test_nargs_oneormore_metavar_length2(self):
5185 self.do_test_no_exception(nargs="+", metavar=("1", "2"))
5186
5187 def test_nargs_oneormore_metavar_length3(self):
5188 self.do_test_exception(nargs="+", metavar=("1", "2", "3"))
5189
5190 # Unit tests for different values of metavar when nargs=...
5191
5192 def test_nargs_remainder_metavar_string(self):
5193 self.do_test_no_exception(nargs="...", metavar="1")
5194
5195 def test_nargs_remainder_metavar_length0(self):
5196 self.do_test_no_exception(nargs="...", metavar=tuple())
5197
5198 def test_nargs_remainder_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005199 self.do_test_no_exception(nargs="...", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005200
5201 def test_nargs_remainder_metavar_length2(self):
5202 self.do_test_no_exception(nargs="...", metavar=("1", "2"))
5203
5204 def test_nargs_remainder_metavar_length3(self):
5205 self.do_test_no_exception(nargs="...", metavar=("1", "2", "3"))
5206
5207 # Unit tests for different values of metavar when nargs=A...
5208
5209 def test_nargs_parser_metavar_string(self):
5210 self.do_test_no_exception(nargs="A...", metavar="1")
5211
5212 def test_nargs_parser_metavar_length0(self):
5213 self.do_test_exception(nargs="A...", metavar=tuple())
5214
5215 def test_nargs_parser_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005216 self.do_test_no_exception(nargs="A...", metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005217
5218 def test_nargs_parser_metavar_length2(self):
5219 self.do_test_exception(nargs="A...", metavar=("1", "2"))
5220
5221 def test_nargs_parser_metavar_length3(self):
5222 self.do_test_exception(nargs="A...", metavar=("1", "2", "3"))
5223
5224 # Unit tests for different values of metavar when nargs=1
5225
5226 def test_nargs_1_metavar_string(self):
5227 self.do_test_no_exception(nargs=1, metavar="1")
5228
5229 def test_nargs_1_metavar_length0(self):
5230 self.do_test_exception(nargs=1, metavar=tuple())
5231
5232 def test_nargs_1_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005233 self.do_test_no_exception(nargs=1, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005234
5235 def test_nargs_1_metavar_length2(self):
5236 self.do_test_exception(nargs=1, metavar=("1", "2"))
5237
5238 def test_nargs_1_metavar_length3(self):
5239 self.do_test_exception(nargs=1, metavar=("1", "2", "3"))
5240
5241 # Unit tests for different values of metavar when nargs=2
5242
5243 def test_nargs_2_metavar_string(self):
5244 self.do_test_no_exception(nargs=2, metavar="1")
5245
5246 def test_nargs_2_metavar_length0(self):
5247 self.do_test_exception(nargs=2, metavar=tuple())
5248
5249 def test_nargs_2_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005250 self.do_test_exception(nargs=2, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005251
5252 def test_nargs_2_metavar_length2(self):
5253 self.do_test_no_exception(nargs=2, metavar=("1", "2"))
5254
5255 def test_nargs_2_metavar_length3(self):
5256 self.do_test_exception(nargs=2, metavar=("1", "2", "3"))
5257
5258 # Unit tests for different values of metavar when nargs=3
5259
5260 def test_nargs_3_metavar_string(self):
5261 self.do_test_no_exception(nargs=3, metavar="1")
5262
5263 def test_nargs_3_metavar_length0(self):
5264 self.do_test_exception(nargs=3, metavar=tuple())
5265
5266 def test_nargs_3_metavar_length1(self):
wim glenn66f02aa2018-06-08 05:12:49 -05005267 self.do_test_exception(nargs=3, metavar=("1",))
Steven Bethard8d9a4622011-03-26 17:33:56 +01005268
5269 def test_nargs_3_metavar_length2(self):
5270 self.do_test_exception(nargs=3, metavar=("1", "2"))
5271
5272 def test_nargs_3_metavar_length3(self):
5273 self.do_test_no_exception(nargs=3, metavar=("1", "2", "3"))
5274
tmblweed4b3e9752019-08-01 21:57:13 -07005275
5276class TestInvalidNargs(TestCase):
5277
5278 EXPECTED_INVALID_MESSAGE = "invalid nargs value"
5279 EXPECTED_RANGE_MESSAGE = ("nargs for store actions must be != 0; if you "
5280 "have nothing to store, actions such as store "
5281 "true or store const may be more appropriate")
5282
5283 def do_test_range_exception(self, nargs):
5284 parser = argparse.ArgumentParser()
5285 with self.assertRaises(ValueError) as cm:
5286 parser.add_argument("--foo", nargs=nargs)
5287 self.assertEqual(cm.exception.args[0], self.EXPECTED_RANGE_MESSAGE)
5288
5289 def do_test_invalid_exception(self, nargs):
5290 parser = argparse.ArgumentParser()
5291 with self.assertRaises(ValueError) as cm:
5292 parser.add_argument("--foo", nargs=nargs)
5293 self.assertEqual(cm.exception.args[0], self.EXPECTED_INVALID_MESSAGE)
5294
5295 # Unit tests for different values of nargs
5296
5297 def test_nargs_alphabetic(self):
5298 self.do_test_invalid_exception(nargs='a')
5299 self.do_test_invalid_exception(nargs="abcd")
5300
5301 def test_nargs_zero(self):
5302 self.do_test_range_exception(nargs=0)
5303
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005304# ============================
5305# from argparse import * tests
5306# ============================
5307
5308class TestImportStar(TestCase):
5309
5310 def test(self):
5311 for name in argparse.__all__:
5312 self.assertTrue(hasattr(argparse, name))
5313
Steven Bethard72c55382010-11-01 15:23:12 +00005314 def test_all_exports_everything_but_modules(self):
5315 items = [
5316 name
5317 for name, value in vars(argparse).items()
Éric Araujo12159152010-12-04 17:31:49 +00005318 if not (name.startswith("_") or name == 'ngettext')
Steven Bethard72c55382010-11-01 15:23:12 +00005319 if not inspect.ismodule(value)
5320 ]
5321 self.assertEqual(sorted(items), sorted(argparse.__all__))
5322
wim glenn66f02aa2018-06-08 05:12:49 -05005323
5324class TestWrappingMetavar(TestCase):
5325
5326 def setUp(self):
Berker Peksag74102c92018-07-25 18:23:44 +03005327 super().setUp()
wim glenn66f02aa2018-06-08 05:12:49 -05005328 self.parser = ErrorRaisingArgumentParser(
5329 'this_is_spammy_prog_with_a_long_name_sorry_about_the_name'
5330 )
5331 # this metavar was triggering library assertion errors due to usage
5332 # message formatting incorrectly splitting on the ] chars within
5333 metavar = '<http[s]://example:1234>'
5334 self.parser.add_argument('--proxy', metavar=metavar)
5335
5336 def test_help_with_metavar(self):
5337 help_text = self.parser.format_help()
5338 self.assertEqual(help_text, textwrap.dedent('''\
5339 usage: this_is_spammy_prog_with_a_long_name_sorry_about_the_name
5340 [-h] [--proxy <http[s]://example:1234>]
5341
Raymond Hettinger41b223d2020-12-23 09:40:56 -08005342 options:
wim glenn66f02aa2018-06-08 05:12:49 -05005343 -h, --help show this help message and exit
5344 --proxy <http[s]://example:1234>
5345 '''))
5346
5347
Hai Shif5456382019-09-12 05:56:05 -05005348class TestExitOnError(TestCase):
5349
5350 def setUp(self):
5351 self.parser = argparse.ArgumentParser(exit_on_error=False)
5352 self.parser.add_argument('--integers', metavar='N', type=int)
5353
5354 def test_exit_on_error_with_good_args(self):
5355 ns = self.parser.parse_args('--integers 4'.split())
5356 self.assertEqual(ns, argparse.Namespace(integers=4))
5357
5358 def test_exit_on_error_with_bad_args(self):
5359 with self.assertRaises(argparse.ArgumentError):
5360 self.parser.parse_args('--integers a'.split())
5361
5362
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005363def test_main():
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02005364 support.run_unittest(__name__)
Benjamin Peterson4fd181c2010-03-02 23:46:42 +00005365 # Remove global references to avoid looking like we have refleaks.
5366 RFile.seen = {}
5367 WFile.seen = set()
5368
Benjamin Peterson698a18a2010-03-02 22:34:37 +00005369
5370
5371if __name__ == '__main__':
5372 test_main()