Steven Bethard | cd4ec0e | 2010-03-24 23:07:31 +0000 | [diff] [blame] | 1 | # Author: Steven J. Bethard <steven.bethard@gmail.com>. |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2 | |
Steven Bethard | 72c5538 | 2010-11-01 15:23:12 +0000 | [diff] [blame] | 3 | import inspect |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4 | import os |
| 5 | import shutil |
Steven Bethard | b027011 | 2011-01-24 21:02:50 +0000 | [diff] [blame] | 6 | import stat |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 7 | import sys |
| 8 | import textwrap |
| 9 | import tempfile |
| 10 | import unittest |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 11 | import argparse |
| 12 | |
Benjamin Peterson | 16f2fd0 | 2010-03-02 23:09:38 +0000 | [diff] [blame] | 13 | from io import StringIO |
| 14 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 15 | from test import support |
Hai Shi | 4660597 | 2020-08-04 00:49:18 +0800 | [diff] [blame] | 16 | from test.support import os_helper |
Petri Lehtinen | 74d6c25 | 2012-12-15 22:39:32 +0200 | [diff] [blame] | 17 | from unittest import mock |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 18 | class StdIOBuffer(StringIO): |
| 19 | pass |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 20 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 21 | class TestCase(unittest.TestCase): |
| 22 | |
Steven Bethard | 1f1c247 | 2010-11-01 13:56:09 +0000 | [diff] [blame] | 23 | 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 Peksag | 74102c9 | 2018-07-25 18:23:44 +0300 | [diff] [blame] | 26 | # variable. To ensure that this width is used, set COLUMNS to 80. |
Hai Shi | 4660597 | 2020-08-04 00:49:18 +0800 | [diff] [blame] | 27 | env = os_helper.EnvironmentVarGuard() |
Berker Peksag | 74102c9 | 2018-07-25 18:23:44 +0300 | [diff] [blame] | 28 | env['COLUMNS'] = '80' |
Steven Bethard | 1f1c247 | 2010-11-01 13:56:09 +0000 | [diff] [blame] | 29 | self.addCleanup(env.__exit__) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 30 | |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 31 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 32 | class 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 Peterson | 511e222 | 2014-04-04 13:55:56 -0400 | [diff] [blame] | 41 | 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 Bethard | b027011 | 2011-01-24 21:02:50 +0000 | [diff] [blame] | 44 | shutil.rmtree(self.temp_dir, True) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 45 | |
Steven Bethard | b027011 | 2011-01-24 21:02:50 +0000 | [diff] [blame] | 46 | def create_readonly_file(self, filename): |
| 47 | file_path = os.path.join(self.temp_dir, filename) |
| 48 | with open(file_path, 'w') as file: |
| 49 | file.write(filename) |
| 50 | os.chmod(file_path, stat.S_IREAD) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 51 | |
| 52 | class Sig(object): |
| 53 | |
| 54 | def __init__(self, *args, **kwargs): |
| 55 | self.args = args |
| 56 | self.kwargs = kwargs |
| 57 | |
| 58 | |
| 59 | class 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 Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 72 | |
| 73 | class 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 | |
| 83 | def 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 Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 87 | if isinstance(sys.stderr, StdIOBuffer) or isinstance(sys.stdout, StdIOBuffer): |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 88 | 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 Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 94 | sys.stdout = StdIOBuffer() |
| 95 | sys.stderr = StdIOBuffer() |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 96 | 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() |
alclarks | d4331c5 | 2020-02-21 08:48:36 +0000 | [diff] [blame] | 109 | raise ArgumentParserError( |
| 110 | "SystemExit", stdout, stderr, code) from None |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 111 | finally: |
| 112 | sys.stdout = old_stdout |
| 113 | sys.stderr = old_stderr |
| 114 | |
| 115 | |
| 116 | class 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 | |
| 131 | class 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 Melotti | 12b7f48 | 2014-08-05 02:24:03 +0300 | [diff] [blame] | 227 | with tester.assertRaises(ArgumentParserError, msg=args): |
| 228 | parser.parse_args(args) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 229 | |
| 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 | |
| 244 | bases = TestCase, |
| 245 | ParserTestCase = ParserTesterMetaclass('ParserTestCase', bases, {}) |
| 246 | |
| 247 | # =============== |
| 248 | # Optionals tests |
| 249 | # =============== |
| 250 | |
| 251 | class 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 | |
| 265 | class 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 | |
| 291 | class 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 | |
| 305 | class 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 | |
| 321 | class 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 | |
| 337 | class 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 | |
| 350 | class 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 | |
| 364 | class 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 | |
| 382 | class 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 | |
| 401 | class 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 | |
| 420 | class TestOptionalsAlternatePrefixChars(ParserTestCase): |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 421 | """Test an Optional with option strings with custom prefixes""" |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 422 | |
| 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 Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 429 | 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 | |
| 440 | class 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 Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 451 | 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 Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 458 | ('/ba +f', NS(f=True, bar=None, baz=42)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 459 | ] |
| 460 | |
Steven Bethard | 1ca45a5 | 2010-11-01 15:57:36 +0000 | [diff] [blame] | 461 | |
| 462 | class 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 Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 485 | class 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 | |
| 501 | class 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 | |
| 514 | class 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 | |
| 526 | class 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 | |
| 537 | class TestOptionalsNargs1(ParserTestCase): |
Martin Panter | cc71a79 | 2016-04-05 06:19:42 +0000 | [diff] [blame] | 538 | """Tests specifying 1 arg for an Optional""" |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 539 | |
| 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 | |
| 548 | class TestOptionalsNargs3(ParserTestCase): |
Martin Panter | cc71a79 | 2016-04-05 06:19:42 +0000 | [diff] [blame] | 549 | """Tests specifying 3 args for an Optional""" |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 550 | |
| 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 | |
| 559 | class 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 | |
| 582 | class TestOptionalsNargsZeroOrMore(ParserTestCase): |
Martin Panter | cc71a79 | 2016-04-05 06:19:42 +0000 | [diff] [blame] | 583 | """Tests specifying args for an Optional that accepts zero or more""" |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 584 | |
| 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 | |
| 601 | class TestOptionalsNargsOneOrMore(ParserTestCase): |
Martin Panter | cc71a79 | 2016-04-05 06:19:42 +0000 | [diff] [blame] | 602 | """Tests specifying args for an Optional that accepts one or more""" |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 603 | |
| 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 | |
| 618 | class 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 | |
| 635 | class TestOptionalsRequired(ParserTestCase): |
Benjamin Peterson | 82f34ad | 2015-01-13 09:17:24 -0500 | [diff] [blame] | 636 | """Tests an optional action that is required""" |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 637 | |
| 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 | |
| 648 | class 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 | |
| 659 | class 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 | |
| 670 | class 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 | |
| 681 | class 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 Lapeyre | 6a517c6 | 2019-09-13 12:17:43 +0200 | [diff] [blame] | 691 | class 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 Lapeyre | b084d1b | 2020-06-06 00:00:42 +0200 | [diff] [blame] | 704 | 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 Lapeyre | 6a517c6 | 2019-09-13 12:17:43 +0200 | [diff] [blame] | 712 | class 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 Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 723 | |
| 724 | class 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 | |
| 736 | class 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 | |
| 748 | class 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 | |
| 763 | class 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 | |
| 778 | class 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 Peksag | 8089cd6 | 2015-02-14 01:39:17 +0200 | [diff] [blame] | 789 | class 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 | |
| 806 | class 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-Dodds | dffca9e | 2019-07-14 00:35:58 -0500 | [diff] [blame] | 822 | |
Kyle Meyer | 8edfc47 | 2020-02-18 04:48:57 -0500 | [diff] [blame] | 823 | class 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-Dodds | dffca9e | 2019-07-14 00:35:58 -0500 | [diff] [blame] | 840 | class 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 Meyer | 8edfc47 | 2020-02-18 04:48:57 -0500 | [diff] [blame] | 858 | |
| 859 | class 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 Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 878 | # ================ |
| 879 | # Positional tests |
| 880 | # ================ |
| 881 | |
| 882 | class 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 | |
| 892 | class 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 | |
| 902 | class 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 | |
| 912 | class 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 | |
| 924 | class 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 | |
| 936 | class 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 | |
| 947 | class 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 | |
| 958 | class 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 | |
| 969 | class 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 | |
| 984 | class 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 | |
| 994 | class 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 | |
| 1004 | class 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 | |
| 1014 | class 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 | |
| 1026 | class 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 | |
| 1037 | class 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 | |
| 1048 | class 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 | |
| 1060 | class 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 | |
| 1071 | class 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 | |
| 1082 | class 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 | |
| 1093 | class 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 | |
| 1103 | class 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 | |
| 1114 | class 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 | |
| 1126 | class 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 | |
| 1137 | class 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 | |
| 1148 | class 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 | |
| 1163 | class 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 | |
| 1178 | class 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 | |
| 1193 | class 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 | |
| 1208 | class 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 | |
| 1221 | class 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 | |
| 1233 | class 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 | |
| 1244 | class 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 | |
| 1255 | class 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 | |
| 1271 | class 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 | |
| 1287 | class 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 | |
| 1304 | class 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 | |
| 1323 | class 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 | |
| 1342 | class TestNargsZeroOrMore(ParserTestCase): |
Martin Panter | cc71a79 | 2016-04-05 06:19:42 +0000 | [diff] [blame] | 1343 | """Tests specifying args for an Optional that accepts zero or more""" |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1344 | |
| 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 | |
| 1358 | class 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 | |
| 1371 | class 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 | |
| 1398 | class 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 | |
| 1417 | class 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 | |
| 1437 | class TestParserDefault42(ParserTestCase): |
| 1438 | """Test actions with a parser-level default of 42""" |
| 1439 | |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 1440 | parser_signature = Sig(argument_default=42) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1441 | argument_signatures = [ |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 1442 | Sig('--version', action='version', version='1.0'), |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1443 | Sig('foo', nargs='?'), |
| 1444 | Sig('bar', nargs='*'), |
| 1445 | Sig('--baz', action='store_true'), |
| 1446 | ] |
| 1447 | failures = ['-x'] |
| 1448 | successes = [ |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 1449 | ('', 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 Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1455 | ] |
| 1456 | |
| 1457 | |
| 1458 | class 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: |
Serhiy Storchaka | 5b10b98 | 2019-03-05 10:06:26 +0200 | [diff] [blame] | 1471 | with open(path, 'w') as file: |
| 1472 | file.write(text) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1473 | |
| 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 Murray | b94082a | 2012-07-21 22:20:11 -0400 | [diff] [blame] | 1488 | (["-a", "", "X", "Y"], NS(a='', x='X', y=['Y'])), |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1489 | ] |
| 1490 | |
| 1491 | |
| 1492 | class 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: |
Serhiy Storchaka | 5b10b98 | 2019-03-05 10:06:26 +0200 | [diff] [blame] | 1501 | with open(path, 'w') as file: |
| 1502 | file.write(text) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1503 | |
| 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 | |
| 1526 | class 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 Lehtinen | 74d6c25 | 2012-12-15 22:39:32 +0200 | [diff] [blame] | 1536 | 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 Dower | d0f49d2 | 2018-09-18 09:10:26 -0700 | [diff] [blame] | 1549 | class StdStreamComparer: |
| 1550 | def __init__(self, attr): |
| 1551 | self.attr = attr |
| 1552 | |
| 1553 | def __eq__(self, other): |
| 1554 | return other == getattr(sys, self.attr) |
| 1555 | |
| 1556 | eq_stdin = StdStreamComparer('stdin') |
| 1557 | eq_stdout = StdStreamComparer('stdout') |
| 1558 | eq_stderr = StdStreamComparer('stderr') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1559 | |
| 1560 | class 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 | |
| 1577 | class 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']: |
Serhiy Storchaka | 5b10b98 | 2019-03-05 10:06:26 +0200 | [diff] [blame] | 1583 | with open(os.path.join(self.temp_dir, file_name), 'w') as file: |
| 1584 | file.write(file_name) |
Steven Bethard | b027011 | 2011-01-24 21:02:50 +0000 | [diff] [blame] | 1585 | self.create_readonly_file('readonly') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1586 | |
| 1587 | argument_signatures = [ |
| 1588 | Sig('-x', type=argparse.FileType()), |
| 1589 | Sig('spam', type=argparse.FileType('r')), |
| 1590 | ] |
Steven Bethard | b027011 | 2011-01-24 21:02:50 +0000 | [diff] [blame] | 1591 | failures = ['-x', '', 'non-existent-file.txt'] |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1592 | successes = [ |
| 1593 | ('foo', NS(x=None, spam=RFile('foo'))), |
| 1594 | ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))), |
| 1595 | ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))), |
Steve Dower | d0f49d2 | 2018-09-18 09:10:26 -0700 | [diff] [blame] | 1596 | ('-x - -', NS(x=eq_stdin, spam=eq_stdin)), |
Steven Bethard | b027011 | 2011-01-24 21:02:50 +0000 | [diff] [blame] | 1597 | ('readonly', NS(x=None, spam=RFile('readonly'))), |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1598 | ] |
| 1599 | |
R David Murray | 6fb8fb1 | 2012-08-31 22:45:20 -0400 | [diff] [blame] | 1600 | class TestFileTypeDefaults(TempDirMixin, ParserTestCase): |
| 1601 | """Test that a file is not created unless the default is needed""" |
| 1602 | def setUp(self): |
| 1603 | super(TestFileTypeDefaults, self).setUp() |
| 1604 | file = open(os.path.join(self.temp_dir, 'good'), 'w') |
| 1605 | file.write('good') |
| 1606 | file.close() |
| 1607 | |
| 1608 | argument_signatures = [ |
| 1609 | Sig('-c', type=argparse.FileType('r'), default='no-file.txt'), |
| 1610 | ] |
| 1611 | # should provoke no such file error |
| 1612 | failures = [''] |
| 1613 | # should not provoke error because default file is created |
| 1614 | successes = [('-c good', NS(c=RFile('good')))] |
| 1615 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1616 | |
| 1617 | class TestFileTypeRB(TempDirMixin, ParserTestCase): |
| 1618 | """Test the FileType option/argument type for reading files""" |
| 1619 | |
| 1620 | def setUp(self): |
| 1621 | super(TestFileTypeRB, self).setUp() |
| 1622 | for file_name in ['foo', 'bar']: |
Serhiy Storchaka | 5b10b98 | 2019-03-05 10:06:26 +0200 | [diff] [blame] | 1623 | with open(os.path.join(self.temp_dir, file_name), 'w') as file: |
| 1624 | file.write(file_name) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1625 | |
| 1626 | argument_signatures = [ |
| 1627 | Sig('-x', type=argparse.FileType('rb')), |
| 1628 | Sig('spam', type=argparse.FileType('rb')), |
| 1629 | ] |
| 1630 | failures = ['-x', ''] |
| 1631 | successes = [ |
| 1632 | ('foo', NS(x=None, spam=RFile('foo'))), |
| 1633 | ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))), |
| 1634 | ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))), |
Steve Dower | d0f49d2 | 2018-09-18 09:10:26 -0700 | [diff] [blame] | 1635 | ('-x - -', NS(x=eq_stdin, spam=eq_stdin)), |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1636 | ] |
| 1637 | |
| 1638 | |
| 1639 | class WFile(object): |
| 1640 | seen = set() |
| 1641 | |
| 1642 | def __init__(self, name): |
| 1643 | self.name = name |
| 1644 | |
| 1645 | def __eq__(self, other): |
| 1646 | if other not in self.seen: |
| 1647 | text = 'Check that file is writable.' |
| 1648 | if 'b' in other.mode: |
| 1649 | text = text.encode('ascii') |
| 1650 | other.write(text) |
| 1651 | other.close() |
| 1652 | self.seen.add(other) |
| 1653 | return self.name == other.name |
| 1654 | |
| 1655 | |
Victor Stinner | a04b39b | 2011-11-20 23:09:09 +0100 | [diff] [blame] | 1656 | @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0, |
| 1657 | "non-root user required") |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1658 | class TestFileTypeW(TempDirMixin, ParserTestCase): |
| 1659 | """Test the FileType option/argument type for writing files""" |
| 1660 | |
Steven Bethard | b027011 | 2011-01-24 21:02:50 +0000 | [diff] [blame] | 1661 | def setUp(self): |
| 1662 | super(TestFileTypeW, self).setUp() |
| 1663 | self.create_readonly_file('readonly') |
| 1664 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1665 | argument_signatures = [ |
| 1666 | Sig('-x', type=argparse.FileType('w')), |
| 1667 | Sig('spam', type=argparse.FileType('w')), |
| 1668 | ] |
Steven Bethard | b027011 | 2011-01-24 21:02:50 +0000 | [diff] [blame] | 1669 | failures = ['-x', '', 'readonly'] |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1670 | successes = [ |
| 1671 | ('foo', NS(x=None, spam=WFile('foo'))), |
| 1672 | ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))), |
| 1673 | ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))), |
Steve Dower | d0f49d2 | 2018-09-18 09:10:26 -0700 | [diff] [blame] | 1674 | ('-x - -', NS(x=eq_stdout, spam=eq_stdout)), |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1675 | ] |
| 1676 | |
| 1677 | |
| 1678 | class TestFileTypeWB(TempDirMixin, ParserTestCase): |
| 1679 | |
| 1680 | argument_signatures = [ |
| 1681 | Sig('-x', type=argparse.FileType('wb')), |
| 1682 | Sig('spam', type=argparse.FileType('wb')), |
| 1683 | ] |
| 1684 | failures = ['-x', ''] |
| 1685 | successes = [ |
| 1686 | ('foo', NS(x=None, spam=WFile('foo'))), |
| 1687 | ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))), |
| 1688 | ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))), |
Steve Dower | d0f49d2 | 2018-09-18 09:10:26 -0700 | [diff] [blame] | 1689 | ('-x - -', NS(x=eq_stdout, spam=eq_stdout)), |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1690 | ] |
| 1691 | |
| 1692 | |
Petri Lehtinen | 74d6c25 | 2012-12-15 22:39:32 +0200 | [diff] [blame] | 1693 | class TestFileTypeOpenArgs(TestCase): |
| 1694 | """Test that open (the builtin) is correctly called""" |
| 1695 | |
| 1696 | def test_open_args(self): |
| 1697 | FT = argparse.FileType |
| 1698 | cases = [ |
| 1699 | (FT('rb'), ('rb', -1, None, None)), |
| 1700 | (FT('w', 1), ('w', 1, None, None)), |
| 1701 | (FT('w', errors='replace'), ('w', -1, None, 'replace')), |
| 1702 | (FT('wb', encoding='big5'), ('wb', -1, 'big5', None)), |
| 1703 | (FT('w', 0, 'l1', 'strict'), ('w', 0, 'l1', 'strict')), |
| 1704 | ] |
| 1705 | with mock.patch('builtins.open') as m: |
| 1706 | for type, args in cases: |
| 1707 | type('foo') |
| 1708 | m.assert_called_with('foo', *args) |
| 1709 | |
| 1710 | |
zygocephalus | 03d5831 | 2019-06-07 23:08:36 +0300 | [diff] [blame] | 1711 | class TestFileTypeMissingInitialization(TestCase): |
| 1712 | """ |
| 1713 | Test that add_argument throws an error if FileType class |
| 1714 | object was passed instead of instance of FileType |
| 1715 | """ |
| 1716 | |
| 1717 | def test(self): |
| 1718 | parser = argparse.ArgumentParser() |
| 1719 | with self.assertRaises(ValueError) as cm: |
| 1720 | parser.add_argument('-x', type=argparse.FileType) |
| 1721 | |
| 1722 | self.assertEqual( |
| 1723 | '%r is a FileType class object, instance of it must be passed' |
| 1724 | % (argparse.FileType,), |
| 1725 | str(cm.exception) |
| 1726 | ) |
| 1727 | |
| 1728 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1729 | class TestTypeCallable(ParserTestCase): |
| 1730 | """Test some callables as option/argument types""" |
| 1731 | |
| 1732 | argument_signatures = [ |
| 1733 | Sig('--eggs', type=complex), |
| 1734 | Sig('spam', type=float), |
| 1735 | ] |
| 1736 | failures = ['a', '42j', '--eggs a', '--eggs 2i'] |
| 1737 | successes = [ |
| 1738 | ('--eggs=42 42', NS(eggs=42, spam=42.0)), |
| 1739 | ('--eggs 2j -- -1.5', NS(eggs=2j, spam=-1.5)), |
| 1740 | ('1024.675', NS(eggs=None, spam=1024.675)), |
| 1741 | ] |
| 1742 | |
| 1743 | |
| 1744 | class TestTypeUserDefined(ParserTestCase): |
| 1745 | """Test a user-defined option/argument type""" |
| 1746 | |
| 1747 | class MyType(TestCase): |
| 1748 | |
| 1749 | def __init__(self, value): |
| 1750 | self.value = value |
| 1751 | |
| 1752 | def __eq__(self, other): |
| 1753 | return (type(self), self.value) == (type(other), other.value) |
| 1754 | |
| 1755 | argument_signatures = [ |
| 1756 | Sig('-x', type=MyType), |
| 1757 | Sig('spam', type=MyType), |
| 1758 | ] |
| 1759 | failures = [] |
| 1760 | successes = [ |
| 1761 | ('a -x b', NS(x=MyType('b'), spam=MyType('a'))), |
| 1762 | ('-xf g', NS(x=MyType('f'), spam=MyType('g'))), |
| 1763 | ] |
| 1764 | |
| 1765 | |
| 1766 | class TestTypeClassicClass(ParserTestCase): |
| 1767 | """Test a classic class type""" |
| 1768 | |
| 1769 | class C: |
| 1770 | |
| 1771 | def __init__(self, value): |
| 1772 | self.value = value |
| 1773 | |
| 1774 | def __eq__(self, other): |
| 1775 | return (type(self), self.value) == (type(other), other.value) |
| 1776 | |
| 1777 | argument_signatures = [ |
| 1778 | Sig('-x', type=C), |
| 1779 | Sig('spam', type=C), |
| 1780 | ] |
| 1781 | failures = [] |
| 1782 | successes = [ |
| 1783 | ('a -x b', NS(x=C('b'), spam=C('a'))), |
| 1784 | ('-xf g', NS(x=C('f'), spam=C('g'))), |
| 1785 | ] |
| 1786 | |
| 1787 | |
| 1788 | class TestTypeRegistration(TestCase): |
| 1789 | """Test a user-defined type by registering it""" |
| 1790 | |
| 1791 | def test(self): |
| 1792 | |
| 1793 | def get_my_type(string): |
| 1794 | return 'my_type{%s}' % string |
| 1795 | |
| 1796 | parser = argparse.ArgumentParser() |
| 1797 | parser.register('type', 'my_type', get_my_type) |
| 1798 | parser.add_argument('-x', type='my_type') |
| 1799 | parser.add_argument('y', type='my_type') |
| 1800 | |
| 1801 | self.assertEqual(parser.parse_args('1'.split()), |
| 1802 | NS(x=None, y='my_type{1}')) |
| 1803 | self.assertEqual(parser.parse_args('-x 1 42'.split()), |
| 1804 | NS(x='my_type{1}', y='my_type{42}')) |
| 1805 | |
| 1806 | |
| 1807 | # ============ |
| 1808 | # Action tests |
| 1809 | # ============ |
| 1810 | |
| 1811 | class TestActionUserDefined(ParserTestCase): |
| 1812 | """Test a user-defined option/argument action""" |
| 1813 | |
| 1814 | class OptionalAction(argparse.Action): |
| 1815 | |
| 1816 | def __call__(self, parser, namespace, value, option_string=None): |
| 1817 | try: |
| 1818 | # check destination and option string |
| 1819 | assert self.dest == 'spam', 'dest: %s' % self.dest |
| 1820 | assert option_string == '-s', 'flag: %s' % option_string |
| 1821 | # when option is before argument, badger=2, and when |
| 1822 | # option is after argument, badger=<whatever was set> |
| 1823 | expected_ns = NS(spam=0.25) |
| 1824 | if value in [0.125, 0.625]: |
| 1825 | expected_ns.badger = 2 |
| 1826 | elif value in [2.0]: |
| 1827 | expected_ns.badger = 84 |
| 1828 | else: |
| 1829 | raise AssertionError('value: %s' % value) |
| 1830 | assert expected_ns == namespace, ('expected %s, got %s' % |
| 1831 | (expected_ns, namespace)) |
| 1832 | except AssertionError: |
| 1833 | e = sys.exc_info()[1] |
| 1834 | raise ArgumentParserError('opt_action failed: %s' % e) |
| 1835 | setattr(namespace, 'spam', value) |
| 1836 | |
| 1837 | class PositionalAction(argparse.Action): |
| 1838 | |
| 1839 | def __call__(self, parser, namespace, value, option_string=None): |
| 1840 | try: |
| 1841 | assert option_string is None, ('option_string: %s' % |
| 1842 | option_string) |
| 1843 | # check destination |
| 1844 | assert self.dest == 'badger', 'dest: %s' % self.dest |
| 1845 | # when argument is before option, spam=0.25, and when |
| 1846 | # option is after argument, spam=<whatever was set> |
| 1847 | expected_ns = NS(badger=2) |
| 1848 | if value in [42, 84]: |
| 1849 | expected_ns.spam = 0.25 |
| 1850 | elif value in [1]: |
| 1851 | expected_ns.spam = 0.625 |
| 1852 | elif value in [2]: |
| 1853 | expected_ns.spam = 0.125 |
| 1854 | else: |
| 1855 | raise AssertionError('value: %s' % value) |
| 1856 | assert expected_ns == namespace, ('expected %s, got %s' % |
| 1857 | (expected_ns, namespace)) |
| 1858 | except AssertionError: |
| 1859 | e = sys.exc_info()[1] |
| 1860 | raise ArgumentParserError('arg_action failed: %s' % e) |
| 1861 | setattr(namespace, 'badger', value) |
| 1862 | |
| 1863 | argument_signatures = [ |
| 1864 | Sig('-s', dest='spam', action=OptionalAction, |
| 1865 | type=float, default=0.25), |
| 1866 | Sig('badger', action=PositionalAction, |
| 1867 | type=int, nargs='?', default=2), |
| 1868 | ] |
| 1869 | failures = [] |
| 1870 | successes = [ |
| 1871 | ('-s0.125', NS(spam=0.125, badger=2)), |
| 1872 | ('42', NS(spam=0.25, badger=42)), |
| 1873 | ('-s 0.625 1', NS(spam=0.625, badger=1)), |
| 1874 | ('84 -s2', NS(spam=2.0, badger=84)), |
| 1875 | ] |
| 1876 | |
| 1877 | |
| 1878 | class TestActionRegistration(TestCase): |
| 1879 | """Test a user-defined action supplied by registering it""" |
| 1880 | |
| 1881 | class MyAction(argparse.Action): |
| 1882 | |
| 1883 | def __call__(self, parser, namespace, values, option_string=None): |
| 1884 | setattr(namespace, self.dest, 'foo[%s]' % values) |
| 1885 | |
| 1886 | def test(self): |
| 1887 | |
| 1888 | parser = argparse.ArgumentParser() |
| 1889 | parser.register('action', 'my_action', self.MyAction) |
| 1890 | parser.add_argument('badger', action='my_action') |
| 1891 | |
| 1892 | self.assertEqual(parser.parse_args(['1']), NS(badger='foo[1]')) |
| 1893 | self.assertEqual(parser.parse_args(['42']), NS(badger='foo[42]')) |
| 1894 | |
| 1895 | |
Batuhan Taşkaya | aa32a7e | 2019-05-21 20:47:42 +0300 | [diff] [blame] | 1896 | class TestActionExtend(ParserTestCase): |
| 1897 | argument_signatures = [ |
| 1898 | Sig('--foo', action="extend", nargs="+", type=str), |
| 1899 | ] |
| 1900 | failures = () |
| 1901 | successes = [ |
| 1902 | ('--foo f1 --foo f2 f3 f4', NS(foo=['f1', 'f2', 'f3', 'f4'])), |
| 1903 | ] |
| 1904 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1905 | # ================ |
| 1906 | # Subparsers tests |
| 1907 | # ================ |
| 1908 | |
| 1909 | class TestAddSubparsers(TestCase): |
| 1910 | """Test the add_subparsers method""" |
| 1911 | |
| 1912 | def assertArgumentParserError(self, *args, **kwargs): |
| 1913 | self.assertRaises(ArgumentParserError, *args, **kwargs) |
| 1914 | |
Steven Bethard | fd311a7 | 2010-12-18 11:19:23 +0000 | [diff] [blame] | 1915 | def _get_parser(self, subparser_help=False, prefix_chars=None, |
| 1916 | aliases=False): |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1917 | # create a parser with a subparsers argument |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 1918 | if prefix_chars: |
| 1919 | parser = ErrorRaisingArgumentParser( |
| 1920 | prog='PROG', description='main description', prefix_chars=prefix_chars) |
| 1921 | parser.add_argument( |
| 1922 | prefix_chars[0] * 2 + 'foo', action='store_true', help='foo help') |
| 1923 | else: |
| 1924 | parser = ErrorRaisingArgumentParser( |
| 1925 | prog='PROG', description='main description') |
| 1926 | parser.add_argument( |
| 1927 | '--foo', action='store_true', help='foo help') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1928 | parser.add_argument( |
| 1929 | 'bar', type=float, help='bar help') |
| 1930 | |
| 1931 | # check that only one subparsers argument can be added |
Anthony Sottile | aaf6fc0 | 2017-09-20 14:35:27 -0700 | [diff] [blame] | 1932 | subparsers_kwargs = {'required': False} |
Steven Bethard | fd311a7 | 2010-12-18 11:19:23 +0000 | [diff] [blame] | 1933 | if aliases: |
| 1934 | subparsers_kwargs['metavar'] = 'COMMAND' |
| 1935 | subparsers_kwargs['title'] = 'commands' |
| 1936 | else: |
| 1937 | subparsers_kwargs['help'] = 'command help' |
| 1938 | subparsers = parser.add_subparsers(**subparsers_kwargs) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1939 | self.assertArgumentParserError(parser.add_subparsers) |
| 1940 | |
| 1941 | # add first sub-parser |
| 1942 | parser1_kwargs = dict(description='1 description') |
| 1943 | if subparser_help: |
| 1944 | parser1_kwargs['help'] = '1 help' |
Steven Bethard | fd311a7 | 2010-12-18 11:19:23 +0000 | [diff] [blame] | 1945 | if aliases: |
| 1946 | parser1_kwargs['aliases'] = ['1alias1', '1alias2'] |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1947 | parser1 = subparsers.add_parser('1', **parser1_kwargs) |
| 1948 | parser1.add_argument('-w', type=int, help='w help') |
| 1949 | parser1.add_argument('x', choices='abc', help='x help') |
| 1950 | |
| 1951 | # add second sub-parser |
| 1952 | parser2_kwargs = dict(description='2 description') |
| 1953 | if subparser_help: |
| 1954 | parser2_kwargs['help'] = '2 help' |
| 1955 | parser2 = subparsers.add_parser('2', **parser2_kwargs) |
| 1956 | parser2.add_argument('-y', choices='123', help='y help') |
| 1957 | parser2.add_argument('z', type=complex, nargs='*', help='z help') |
| 1958 | |
R David Murray | 00528e8 | 2012-07-21 22:48:35 -0400 | [diff] [blame] | 1959 | # add third sub-parser |
| 1960 | parser3_kwargs = dict(description='3 description') |
| 1961 | if subparser_help: |
| 1962 | parser3_kwargs['help'] = '3 help' |
| 1963 | parser3 = subparsers.add_parser('3', **parser3_kwargs) |
| 1964 | parser3.add_argument('t', type=int, help='t help') |
| 1965 | parser3.add_argument('u', nargs='...', help='u help') |
| 1966 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1967 | # return the main parser |
| 1968 | return parser |
| 1969 | |
| 1970 | def setUp(self): |
Steven Bethard | 1f1c247 | 2010-11-01 13:56:09 +0000 | [diff] [blame] | 1971 | super().setUp() |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1972 | self.parser = self._get_parser() |
| 1973 | self.command_help_parser = self._get_parser(subparser_help=True) |
| 1974 | |
| 1975 | def test_parse_args_failures(self): |
| 1976 | # check some failure cases: |
| 1977 | for args_str in ['', 'a', 'a a', '0.5 a', '0.5 1', |
| 1978 | '0.5 1 -y', '0.5 2 -w']: |
| 1979 | args = args_str.split() |
| 1980 | self.assertArgumentParserError(self.parser.parse_args, args) |
| 1981 | |
| 1982 | def test_parse_args(self): |
| 1983 | # check some non-failure cases: |
| 1984 | self.assertEqual( |
| 1985 | self.parser.parse_args('0.5 1 b -w 7'.split()), |
| 1986 | NS(foo=False, bar=0.5, w=7, x='b'), |
| 1987 | ) |
| 1988 | self.assertEqual( |
| 1989 | self.parser.parse_args('0.25 --foo 2 -y 2 3j -- -1j'.split()), |
| 1990 | NS(foo=True, bar=0.25, y='2', z=[3j, -1j]), |
| 1991 | ) |
| 1992 | self.assertEqual( |
| 1993 | self.parser.parse_args('--foo 0.125 1 c'.split()), |
| 1994 | NS(foo=True, bar=0.125, w=None, x='c'), |
| 1995 | ) |
R David Murray | 00528e8 | 2012-07-21 22:48:35 -0400 | [diff] [blame] | 1996 | self.assertEqual( |
| 1997 | self.parser.parse_args('-1.5 3 11 -- a --foo 7 -- b'.split()), |
| 1998 | NS(foo=False, bar=-1.5, t=11, u=['a', '--foo', '7', '--', 'b']), |
| 1999 | ) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2000 | |
Steven Bethard | fca2e8a | 2010-11-02 12:47:22 +0000 | [diff] [blame] | 2001 | def test_parse_known_args(self): |
| 2002 | self.assertEqual( |
| 2003 | self.parser.parse_known_args('0.5 1 b -w 7'.split()), |
| 2004 | (NS(foo=False, bar=0.5, w=7, x='b'), []), |
| 2005 | ) |
| 2006 | self.assertEqual( |
| 2007 | self.parser.parse_known_args('0.5 -p 1 b -w 7'.split()), |
| 2008 | (NS(foo=False, bar=0.5, w=7, x='b'), ['-p']), |
| 2009 | ) |
| 2010 | self.assertEqual( |
| 2011 | self.parser.parse_known_args('0.5 1 b -w 7 -p'.split()), |
| 2012 | (NS(foo=False, bar=0.5, w=7, x='b'), ['-p']), |
| 2013 | ) |
| 2014 | self.assertEqual( |
| 2015 | self.parser.parse_known_args('0.5 1 b -q -rs -w 7'.split()), |
| 2016 | (NS(foo=False, bar=0.5, w=7, x='b'), ['-q', '-rs']), |
| 2017 | ) |
| 2018 | self.assertEqual( |
| 2019 | self.parser.parse_known_args('0.5 -W 1 b -X Y -w 7 Z'.split()), |
| 2020 | (NS(foo=False, bar=0.5, w=7, x='b'), ['-W', '-X', 'Y', 'Z']), |
| 2021 | ) |
| 2022 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2023 | def test_dest(self): |
| 2024 | parser = ErrorRaisingArgumentParser() |
| 2025 | parser.add_argument('--foo', action='store_true') |
| 2026 | subparsers = parser.add_subparsers(dest='bar') |
| 2027 | parser1 = subparsers.add_parser('1') |
| 2028 | parser1.add_argument('baz') |
| 2029 | self.assertEqual(NS(foo=False, bar='1', baz='2'), |
| 2030 | parser.parse_args('1 2'.split())) |
| 2031 | |
Anthony Sottile | aaf6fc0 | 2017-09-20 14:35:27 -0700 | [diff] [blame] | 2032 | def _test_required_subparsers(self, parser): |
| 2033 | # Should parse the sub command |
| 2034 | ret = parser.parse_args(['run']) |
| 2035 | self.assertEqual(ret.command, 'run') |
| 2036 | |
| 2037 | # Error when the command is missing |
| 2038 | self.assertArgumentParserError(parser.parse_args, ()) |
| 2039 | |
| 2040 | def test_required_subparsers_via_attribute(self): |
| 2041 | parser = ErrorRaisingArgumentParser() |
| 2042 | subparsers = parser.add_subparsers(dest='command') |
| 2043 | subparsers.required = True |
| 2044 | subparsers.add_parser('run') |
| 2045 | self._test_required_subparsers(parser) |
| 2046 | |
| 2047 | def test_required_subparsers_via_kwarg(self): |
| 2048 | parser = ErrorRaisingArgumentParser() |
| 2049 | subparsers = parser.add_subparsers(dest='command', required=True) |
| 2050 | subparsers.add_parser('run') |
| 2051 | self._test_required_subparsers(parser) |
| 2052 | |
| 2053 | def test_required_subparsers_default(self): |
| 2054 | parser = ErrorRaisingArgumentParser() |
| 2055 | subparsers = parser.add_subparsers(dest='command') |
| 2056 | subparsers.add_parser('run') |
Ned Deily | 8ebf5ce | 2018-05-23 21:55:15 -0400 | [diff] [blame] | 2057 | # No error here |
| 2058 | ret = parser.parse_args(()) |
| 2059 | self.assertIsNone(ret.command) |
Anthony Sottile | aaf6fc0 | 2017-09-20 14:35:27 -0700 | [diff] [blame] | 2060 | |
| 2061 | def test_optional_subparsers(self): |
| 2062 | parser = ErrorRaisingArgumentParser() |
| 2063 | subparsers = parser.add_subparsers(dest='command', required=False) |
| 2064 | subparsers.add_parser('run') |
| 2065 | # No error here |
| 2066 | ret = parser.parse_args(()) |
| 2067 | self.assertIsNone(ret.command) |
| 2068 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2069 | def test_help(self): |
| 2070 | self.assertEqual(self.parser.format_usage(), |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2071 | 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2072 | self.assertEqual(self.parser.format_help(), textwrap.dedent('''\ |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2073 | usage: PROG [-h] [--foo] bar {1,2,3} ... |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2074 | |
| 2075 | main description |
| 2076 | |
| 2077 | positional arguments: |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2078 | bar bar help |
| 2079 | {1,2,3} command help |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2080 | |
| 2081 | optional arguments: |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2082 | -h, --help show this help message and exit |
| 2083 | --foo foo help |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2084 | ''')) |
| 2085 | |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 2086 | def test_help_extra_prefix_chars(self): |
| 2087 | # Make sure - is still used for help if it is a non-first prefix char |
| 2088 | parser = self._get_parser(prefix_chars='+:-') |
| 2089 | self.assertEqual(parser.format_usage(), |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2090 | 'usage: PROG [-h] [++foo] bar {1,2,3} ...\n') |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 2091 | self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2092 | usage: PROG [-h] [++foo] bar {1,2,3} ... |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 2093 | |
| 2094 | main description |
| 2095 | |
| 2096 | positional arguments: |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2097 | bar bar help |
| 2098 | {1,2,3} command help |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 2099 | |
| 2100 | optional arguments: |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2101 | -h, --help show this help message and exit |
| 2102 | ++foo foo help |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 2103 | ''')) |
| 2104 | |
Xiang Zhang | 7fe28ad | 2017-01-22 14:37:22 +0800 | [diff] [blame] | 2105 | def test_help_non_breaking_spaces(self): |
| 2106 | parser = ErrorRaisingArgumentParser( |
| 2107 | prog='PROG', description='main description') |
| 2108 | parser.add_argument( |
| 2109 | "--non-breaking", action='store_false', |
| 2110 | help='help message containing non-breaking spaces shall not ' |
| 2111 | 'wrap\N{NO-BREAK SPACE}at non-breaking spaces') |
| 2112 | self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
| 2113 | usage: PROG [-h] [--non-breaking] |
| 2114 | |
| 2115 | main description |
| 2116 | |
| 2117 | optional arguments: |
| 2118 | -h, --help show this help message and exit |
| 2119 | --non-breaking help message containing non-breaking spaces shall not |
| 2120 | wrap\N{NO-BREAK SPACE}at non-breaking spaces |
| 2121 | ''')) |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 2122 | |
| 2123 | def test_help_alternate_prefix_chars(self): |
| 2124 | parser = self._get_parser(prefix_chars='+:/') |
| 2125 | self.assertEqual(parser.format_usage(), |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2126 | 'usage: PROG [+h] [++foo] bar {1,2,3} ...\n') |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 2127 | self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2128 | usage: PROG [+h] [++foo] bar {1,2,3} ... |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 2129 | |
| 2130 | main description |
| 2131 | |
| 2132 | positional arguments: |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2133 | bar bar help |
| 2134 | {1,2,3} command help |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 2135 | |
| 2136 | optional arguments: |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2137 | +h, ++help show this help message and exit |
| 2138 | ++foo foo help |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 2139 | ''')) |
| 2140 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2141 | def test_parser_command_help(self): |
| 2142 | self.assertEqual(self.command_help_parser.format_usage(), |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2143 | 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2144 | self.assertEqual(self.command_help_parser.format_help(), |
| 2145 | textwrap.dedent('''\ |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2146 | usage: PROG [-h] [--foo] bar {1,2,3} ... |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2147 | |
| 2148 | main description |
| 2149 | |
| 2150 | positional arguments: |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2151 | bar bar help |
| 2152 | {1,2,3} command help |
| 2153 | 1 1 help |
| 2154 | 2 2 help |
| 2155 | 3 3 help |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2156 | |
| 2157 | optional arguments: |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2158 | -h, --help show this help message and exit |
| 2159 | --foo foo help |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2160 | ''')) |
| 2161 | |
| 2162 | def test_subparser_title_help(self): |
| 2163 | parser = ErrorRaisingArgumentParser(prog='PROG', |
| 2164 | description='main description') |
| 2165 | parser.add_argument('--foo', action='store_true', help='foo help') |
| 2166 | parser.add_argument('bar', help='bar help') |
| 2167 | subparsers = parser.add_subparsers(title='subcommands', |
| 2168 | description='command help', |
| 2169 | help='additional text') |
| 2170 | parser1 = subparsers.add_parser('1') |
| 2171 | parser2 = subparsers.add_parser('2') |
| 2172 | self.assertEqual(parser.format_usage(), |
| 2173 | 'usage: PROG [-h] [--foo] bar {1,2} ...\n') |
| 2174 | self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
| 2175 | usage: PROG [-h] [--foo] bar {1,2} ... |
| 2176 | |
| 2177 | main description |
| 2178 | |
| 2179 | positional arguments: |
| 2180 | bar bar help |
| 2181 | |
| 2182 | optional arguments: |
| 2183 | -h, --help show this help message and exit |
| 2184 | --foo foo help |
| 2185 | |
| 2186 | subcommands: |
| 2187 | command help |
| 2188 | |
| 2189 | {1,2} additional text |
| 2190 | ''')) |
| 2191 | |
| 2192 | def _test_subparser_help(self, args_str, expected_help): |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 2193 | with self.assertRaises(ArgumentParserError) as cm: |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2194 | self.parser.parse_args(args_str.split()) |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 2195 | self.assertEqual(expected_help, cm.exception.stdout) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2196 | |
| 2197 | def test_subparser1_help(self): |
| 2198 | self._test_subparser_help('5.0 1 -h', textwrap.dedent('''\ |
| 2199 | usage: PROG bar 1 [-h] [-w W] {a,b,c} |
| 2200 | |
| 2201 | 1 description |
| 2202 | |
| 2203 | positional arguments: |
| 2204 | {a,b,c} x help |
| 2205 | |
| 2206 | optional arguments: |
| 2207 | -h, --help show this help message and exit |
| 2208 | -w W w help |
| 2209 | ''')) |
| 2210 | |
| 2211 | def test_subparser2_help(self): |
| 2212 | self._test_subparser_help('5.0 2 -h', textwrap.dedent('''\ |
Brandt Bucher | a0ed99b | 2019-11-11 12:47:48 -0800 | [diff] [blame] | 2213 | usage: PROG bar 2 [-h] [-y {1,2,3}] [z ...] |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2214 | |
| 2215 | 2 description |
| 2216 | |
| 2217 | positional arguments: |
| 2218 | z z help |
| 2219 | |
| 2220 | optional arguments: |
| 2221 | -h, --help show this help message and exit |
| 2222 | -y {1,2,3} y help |
| 2223 | ''')) |
| 2224 | |
Steven Bethard | fd311a7 | 2010-12-18 11:19:23 +0000 | [diff] [blame] | 2225 | def test_alias_invocation(self): |
| 2226 | parser = self._get_parser(aliases=True) |
| 2227 | self.assertEqual( |
| 2228 | parser.parse_known_args('0.5 1alias1 b'.split()), |
| 2229 | (NS(foo=False, bar=0.5, w=None, x='b'), []), |
| 2230 | ) |
| 2231 | self.assertEqual( |
| 2232 | parser.parse_known_args('0.5 1alias2 b'.split()), |
| 2233 | (NS(foo=False, bar=0.5, w=None, x='b'), []), |
| 2234 | ) |
| 2235 | |
| 2236 | def test_error_alias_invocation(self): |
| 2237 | parser = self._get_parser(aliases=True) |
| 2238 | self.assertArgumentParserError(parser.parse_args, |
| 2239 | '0.5 1alias3 b'.split()) |
| 2240 | |
| 2241 | def test_alias_help(self): |
| 2242 | parser = self._get_parser(aliases=True, subparser_help=True) |
| 2243 | self.maxDiff = None |
| 2244 | self.assertEqual(parser.format_help(), textwrap.dedent("""\ |
| 2245 | usage: PROG [-h] [--foo] bar COMMAND ... |
| 2246 | |
| 2247 | main description |
| 2248 | |
| 2249 | positional arguments: |
| 2250 | bar bar help |
| 2251 | |
| 2252 | optional arguments: |
| 2253 | -h, --help show this help message and exit |
| 2254 | --foo foo help |
| 2255 | |
| 2256 | commands: |
| 2257 | COMMAND |
| 2258 | 1 (1alias1, 1alias2) |
| 2259 | 1 help |
| 2260 | 2 2 help |
R David Murray | 00528e8 | 2012-07-21 22:48:35 -0400 | [diff] [blame] | 2261 | 3 3 help |
Steven Bethard | fd311a7 | 2010-12-18 11:19:23 +0000 | [diff] [blame] | 2262 | """)) |
| 2263 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2264 | # ============ |
| 2265 | # Groups tests |
| 2266 | # ============ |
| 2267 | |
| 2268 | class TestPositionalsGroups(TestCase): |
| 2269 | """Tests that order of group positionals matches construction order""" |
| 2270 | |
| 2271 | def test_nongroup_first(self): |
| 2272 | parser = ErrorRaisingArgumentParser() |
| 2273 | parser.add_argument('foo') |
| 2274 | group = parser.add_argument_group('g') |
| 2275 | group.add_argument('bar') |
| 2276 | parser.add_argument('baz') |
| 2277 | expected = NS(foo='1', bar='2', baz='3') |
| 2278 | result = parser.parse_args('1 2 3'.split()) |
| 2279 | self.assertEqual(expected, result) |
| 2280 | |
| 2281 | def test_group_first(self): |
| 2282 | parser = ErrorRaisingArgumentParser() |
| 2283 | group = parser.add_argument_group('xxx') |
| 2284 | group.add_argument('foo') |
| 2285 | parser.add_argument('bar') |
| 2286 | parser.add_argument('baz') |
| 2287 | expected = NS(foo='1', bar='2', baz='3') |
| 2288 | result = parser.parse_args('1 2 3'.split()) |
| 2289 | self.assertEqual(expected, result) |
| 2290 | |
| 2291 | def test_interleaved_groups(self): |
| 2292 | parser = ErrorRaisingArgumentParser() |
| 2293 | group = parser.add_argument_group('xxx') |
| 2294 | parser.add_argument('foo') |
| 2295 | group.add_argument('bar') |
| 2296 | parser.add_argument('baz') |
| 2297 | group = parser.add_argument_group('yyy') |
| 2298 | group.add_argument('frell') |
| 2299 | expected = NS(foo='1', bar='2', baz='3', frell='4') |
| 2300 | result = parser.parse_args('1 2 3 4'.split()) |
| 2301 | self.assertEqual(expected, result) |
| 2302 | |
| 2303 | # =================== |
| 2304 | # Parent parser tests |
| 2305 | # =================== |
| 2306 | |
| 2307 | class TestParentParsers(TestCase): |
| 2308 | """Tests that parsers can be created with parent parsers""" |
| 2309 | |
| 2310 | def assertArgumentParserError(self, *args, **kwargs): |
| 2311 | self.assertRaises(ArgumentParserError, *args, **kwargs) |
| 2312 | |
| 2313 | def setUp(self): |
Steven Bethard | 1f1c247 | 2010-11-01 13:56:09 +0000 | [diff] [blame] | 2314 | super().setUp() |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2315 | self.wxyz_parent = ErrorRaisingArgumentParser(add_help=False) |
| 2316 | self.wxyz_parent.add_argument('--w') |
| 2317 | x_group = self.wxyz_parent.add_argument_group('x') |
| 2318 | x_group.add_argument('-y') |
| 2319 | self.wxyz_parent.add_argument('z') |
| 2320 | |
| 2321 | self.abcd_parent = ErrorRaisingArgumentParser(add_help=False) |
| 2322 | self.abcd_parent.add_argument('a') |
| 2323 | self.abcd_parent.add_argument('-b') |
| 2324 | c_group = self.abcd_parent.add_argument_group('c') |
| 2325 | c_group.add_argument('--d') |
| 2326 | |
| 2327 | self.w_parent = ErrorRaisingArgumentParser(add_help=False) |
| 2328 | self.w_parent.add_argument('--w') |
| 2329 | |
| 2330 | self.z_parent = ErrorRaisingArgumentParser(add_help=False) |
| 2331 | self.z_parent.add_argument('z') |
| 2332 | |
| 2333 | # parents with mutually exclusive groups |
| 2334 | self.ab_mutex_parent = ErrorRaisingArgumentParser(add_help=False) |
| 2335 | group = self.ab_mutex_parent.add_mutually_exclusive_group() |
| 2336 | group.add_argument('-a', action='store_true') |
| 2337 | group.add_argument('-b', action='store_true') |
| 2338 | |
| 2339 | self.main_program = os.path.basename(sys.argv[0]) |
| 2340 | |
| 2341 | def test_single_parent(self): |
| 2342 | parser = ErrorRaisingArgumentParser(parents=[self.wxyz_parent]) |
| 2343 | self.assertEqual(parser.parse_args('-y 1 2 --w 3'.split()), |
| 2344 | NS(w='3', y='1', z='2')) |
| 2345 | |
| 2346 | def test_single_parent_mutex(self): |
| 2347 | self._test_mutex_ab(self.ab_mutex_parent.parse_args) |
| 2348 | parser = ErrorRaisingArgumentParser(parents=[self.ab_mutex_parent]) |
| 2349 | self._test_mutex_ab(parser.parse_args) |
| 2350 | |
| 2351 | def test_single_granparent_mutex(self): |
| 2352 | parents = [self.ab_mutex_parent] |
| 2353 | parser = ErrorRaisingArgumentParser(add_help=False, parents=parents) |
| 2354 | parser = ErrorRaisingArgumentParser(parents=[parser]) |
| 2355 | self._test_mutex_ab(parser.parse_args) |
| 2356 | |
| 2357 | def _test_mutex_ab(self, parse_args): |
| 2358 | self.assertEqual(parse_args([]), NS(a=False, b=False)) |
| 2359 | self.assertEqual(parse_args(['-a']), NS(a=True, b=False)) |
| 2360 | self.assertEqual(parse_args(['-b']), NS(a=False, b=True)) |
| 2361 | self.assertArgumentParserError(parse_args, ['-a', '-b']) |
| 2362 | self.assertArgumentParserError(parse_args, ['-b', '-a']) |
| 2363 | self.assertArgumentParserError(parse_args, ['-c']) |
| 2364 | self.assertArgumentParserError(parse_args, ['-a', '-c']) |
| 2365 | self.assertArgumentParserError(parse_args, ['-b', '-c']) |
| 2366 | |
| 2367 | def test_multiple_parents(self): |
| 2368 | parents = [self.abcd_parent, self.wxyz_parent] |
| 2369 | parser = ErrorRaisingArgumentParser(parents=parents) |
| 2370 | self.assertEqual(parser.parse_args('--d 1 --w 2 3 4'.split()), |
| 2371 | NS(a='3', b=None, d='1', w='2', y=None, z='4')) |
| 2372 | |
| 2373 | def test_multiple_parents_mutex(self): |
| 2374 | parents = [self.ab_mutex_parent, self.wxyz_parent] |
| 2375 | parser = ErrorRaisingArgumentParser(parents=parents) |
| 2376 | self.assertEqual(parser.parse_args('-a --w 2 3'.split()), |
| 2377 | NS(a=True, b=False, w='2', y=None, z='3')) |
| 2378 | self.assertArgumentParserError( |
| 2379 | parser.parse_args, '-a --w 2 3 -b'.split()) |
| 2380 | self.assertArgumentParserError( |
| 2381 | parser.parse_args, '-a -b --w 2 3'.split()) |
| 2382 | |
| 2383 | def test_conflicting_parents(self): |
| 2384 | self.assertRaises( |
| 2385 | argparse.ArgumentError, |
| 2386 | argparse.ArgumentParser, |
| 2387 | parents=[self.w_parent, self.wxyz_parent]) |
| 2388 | |
| 2389 | def test_conflicting_parents_mutex(self): |
| 2390 | self.assertRaises( |
| 2391 | argparse.ArgumentError, |
| 2392 | argparse.ArgumentParser, |
| 2393 | parents=[self.abcd_parent, self.ab_mutex_parent]) |
| 2394 | |
| 2395 | def test_same_argument_name_parents(self): |
| 2396 | parents = [self.wxyz_parent, self.z_parent] |
| 2397 | parser = ErrorRaisingArgumentParser(parents=parents) |
| 2398 | self.assertEqual(parser.parse_args('1 2'.split()), |
| 2399 | NS(w=None, y=None, z='2')) |
| 2400 | |
| 2401 | def test_subparser_parents(self): |
| 2402 | parser = ErrorRaisingArgumentParser() |
| 2403 | subparsers = parser.add_subparsers() |
| 2404 | abcde_parser = subparsers.add_parser('bar', parents=[self.abcd_parent]) |
| 2405 | abcde_parser.add_argument('e') |
| 2406 | self.assertEqual(parser.parse_args('bar -b 1 --d 2 3 4'.split()), |
| 2407 | NS(a='3', b='1', d='2', e='4')) |
| 2408 | |
| 2409 | def test_subparser_parents_mutex(self): |
| 2410 | parser = ErrorRaisingArgumentParser() |
| 2411 | subparsers = parser.add_subparsers() |
| 2412 | parents = [self.ab_mutex_parent] |
| 2413 | abc_parser = subparsers.add_parser('foo', parents=parents) |
| 2414 | c_group = abc_parser.add_argument_group('c_group') |
| 2415 | c_group.add_argument('c') |
| 2416 | parents = [self.wxyz_parent, self.ab_mutex_parent] |
| 2417 | wxyzabe_parser = subparsers.add_parser('bar', parents=parents) |
| 2418 | wxyzabe_parser.add_argument('e') |
| 2419 | self.assertEqual(parser.parse_args('foo -a 4'.split()), |
| 2420 | NS(a=True, b=False, c='4')) |
| 2421 | self.assertEqual(parser.parse_args('bar -b --w 2 3 4'.split()), |
| 2422 | NS(a=False, b=True, w='2', y=None, z='3', e='4')) |
| 2423 | self.assertArgumentParserError( |
| 2424 | parser.parse_args, 'foo -a -b 4'.split()) |
| 2425 | self.assertArgumentParserError( |
| 2426 | parser.parse_args, 'bar -b -a 4'.split()) |
| 2427 | |
| 2428 | def test_parent_help(self): |
| 2429 | parents = [self.abcd_parent, self.wxyz_parent] |
| 2430 | parser = ErrorRaisingArgumentParser(parents=parents) |
| 2431 | parser_help = parser.format_help() |
Terry Jan Reedy | ee91e09 | 2012-01-09 18:20:09 -0500 | [diff] [blame] | 2432 | progname = self.main_program |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2433 | self.assertEqual(parser_help, textwrap.dedent('''\ |
Terry Jan Reedy | ee91e09 | 2012-01-09 18:20:09 -0500 | [diff] [blame] | 2434 | usage: {}{}[-h] [-b B] [--d D] [--w W] [-y Y] a z |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2435 | |
| 2436 | positional arguments: |
| 2437 | a |
| 2438 | z |
| 2439 | |
| 2440 | optional arguments: |
| 2441 | -h, --help show this help message and exit |
| 2442 | -b B |
| 2443 | --w W |
| 2444 | |
| 2445 | c: |
| 2446 | --d D |
| 2447 | |
| 2448 | x: |
| 2449 | -y Y |
Terry Jan Reedy | ee91e09 | 2012-01-09 18:20:09 -0500 | [diff] [blame] | 2450 | '''.format(progname, ' ' if progname else '' ))) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2451 | |
| 2452 | def test_groups_parents(self): |
| 2453 | parent = ErrorRaisingArgumentParser(add_help=False) |
| 2454 | g = parent.add_argument_group(title='g', description='gd') |
| 2455 | g.add_argument('-w') |
| 2456 | g.add_argument('-x') |
| 2457 | m = parent.add_mutually_exclusive_group() |
| 2458 | m.add_argument('-y') |
| 2459 | m.add_argument('-z') |
| 2460 | parser = ErrorRaisingArgumentParser(parents=[parent]) |
| 2461 | |
| 2462 | self.assertRaises(ArgumentParserError, parser.parse_args, |
| 2463 | ['-y', 'Y', '-z', 'Z']) |
| 2464 | |
| 2465 | parser_help = parser.format_help() |
Terry Jan Reedy | ee91e09 | 2012-01-09 18:20:09 -0500 | [diff] [blame] | 2466 | progname = self.main_program |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2467 | self.assertEqual(parser_help, textwrap.dedent('''\ |
Terry Jan Reedy | ee91e09 | 2012-01-09 18:20:09 -0500 | [diff] [blame] | 2468 | usage: {}{}[-h] [-w W] [-x X] [-y Y | -z Z] |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2469 | |
| 2470 | optional arguments: |
| 2471 | -h, --help show this help message and exit |
| 2472 | -y Y |
| 2473 | -z Z |
| 2474 | |
| 2475 | g: |
| 2476 | gd |
| 2477 | |
| 2478 | -w W |
| 2479 | -x X |
Terry Jan Reedy | ee91e09 | 2012-01-09 18:20:09 -0500 | [diff] [blame] | 2480 | '''.format(progname, ' ' if progname else '' ))) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2481 | |
| 2482 | # ============================== |
| 2483 | # Mutually exclusive group tests |
| 2484 | # ============================== |
| 2485 | |
| 2486 | class TestMutuallyExclusiveGroupErrors(TestCase): |
| 2487 | |
| 2488 | def test_invalid_add_argument_group(self): |
| 2489 | parser = ErrorRaisingArgumentParser() |
| 2490 | raises = self.assertRaises |
| 2491 | raises(TypeError, parser.add_mutually_exclusive_group, title='foo') |
| 2492 | |
| 2493 | def test_invalid_add_argument(self): |
| 2494 | parser = ErrorRaisingArgumentParser() |
| 2495 | group = parser.add_mutually_exclusive_group() |
| 2496 | add_argument = group.add_argument |
| 2497 | raises = self.assertRaises |
| 2498 | raises(ValueError, add_argument, '--foo', required=True) |
| 2499 | raises(ValueError, add_argument, 'bar') |
| 2500 | raises(ValueError, add_argument, 'bar', nargs='+') |
| 2501 | raises(ValueError, add_argument, 'bar', nargs=1) |
| 2502 | raises(ValueError, add_argument, 'bar', nargs=argparse.PARSER) |
| 2503 | |
Steven Bethard | 49998ee | 2010-11-01 16:29:26 +0000 | [diff] [blame] | 2504 | def test_help(self): |
| 2505 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2506 | group1 = parser.add_mutually_exclusive_group() |
| 2507 | group1.add_argument('--foo', action='store_true') |
| 2508 | group1.add_argument('--bar', action='store_false') |
| 2509 | group2 = parser.add_mutually_exclusive_group() |
| 2510 | group2.add_argument('--soup', action='store_true') |
| 2511 | group2.add_argument('--nuts', action='store_false') |
| 2512 | expected = '''\ |
| 2513 | usage: PROG [-h] [--foo | --bar] [--soup | --nuts] |
| 2514 | |
| 2515 | optional arguments: |
| 2516 | -h, --help show this help message and exit |
| 2517 | --foo |
| 2518 | --bar |
| 2519 | --soup |
| 2520 | --nuts |
| 2521 | ''' |
| 2522 | self.assertEqual(parser.format_help(), textwrap.dedent(expected)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2523 | |
| 2524 | class MEMixin(object): |
| 2525 | |
| 2526 | def test_failures_when_not_required(self): |
| 2527 | parse_args = self.get_parser(required=False).parse_args |
| 2528 | error = ArgumentParserError |
| 2529 | for args_string in self.failures: |
| 2530 | self.assertRaises(error, parse_args, args_string.split()) |
| 2531 | |
| 2532 | def test_failures_when_required(self): |
| 2533 | parse_args = self.get_parser(required=True).parse_args |
| 2534 | error = ArgumentParserError |
| 2535 | for args_string in self.failures + ['']: |
| 2536 | self.assertRaises(error, parse_args, args_string.split()) |
| 2537 | |
| 2538 | def test_successes_when_not_required(self): |
| 2539 | parse_args = self.get_parser(required=False).parse_args |
| 2540 | successes = self.successes + self.successes_when_not_required |
| 2541 | for args_string, expected_ns in successes: |
| 2542 | actual_ns = parse_args(args_string.split()) |
| 2543 | self.assertEqual(actual_ns, expected_ns) |
| 2544 | |
| 2545 | def test_successes_when_required(self): |
| 2546 | parse_args = self.get_parser(required=True).parse_args |
| 2547 | for args_string, expected_ns in self.successes: |
| 2548 | actual_ns = parse_args(args_string.split()) |
| 2549 | self.assertEqual(actual_ns, expected_ns) |
| 2550 | |
| 2551 | def test_usage_when_not_required(self): |
| 2552 | format_usage = self.get_parser(required=False).format_usage |
| 2553 | expected_usage = self.usage_when_not_required |
| 2554 | self.assertEqual(format_usage(), textwrap.dedent(expected_usage)) |
| 2555 | |
| 2556 | def test_usage_when_required(self): |
| 2557 | format_usage = self.get_parser(required=True).format_usage |
| 2558 | expected_usage = self.usage_when_required |
| 2559 | self.assertEqual(format_usage(), textwrap.dedent(expected_usage)) |
| 2560 | |
| 2561 | def test_help_when_not_required(self): |
| 2562 | format_help = self.get_parser(required=False).format_help |
| 2563 | help = self.usage_when_not_required + self.help |
| 2564 | self.assertEqual(format_help(), textwrap.dedent(help)) |
| 2565 | |
| 2566 | def test_help_when_required(self): |
| 2567 | format_help = self.get_parser(required=True).format_help |
| 2568 | help = self.usage_when_required + self.help |
| 2569 | self.assertEqual(format_help(), textwrap.dedent(help)) |
| 2570 | |
| 2571 | |
| 2572 | class TestMutuallyExclusiveSimple(MEMixin, TestCase): |
| 2573 | |
| 2574 | def get_parser(self, required=None): |
| 2575 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2576 | group = parser.add_mutually_exclusive_group(required=required) |
| 2577 | group.add_argument('--bar', help='bar help') |
| 2578 | group.add_argument('--baz', nargs='?', const='Z', help='baz help') |
| 2579 | return parser |
| 2580 | |
| 2581 | failures = ['--bar X --baz Y', '--bar X --baz'] |
| 2582 | successes = [ |
| 2583 | ('--bar X', NS(bar='X', baz=None)), |
| 2584 | ('--bar X --bar Z', NS(bar='Z', baz=None)), |
| 2585 | ('--baz Y', NS(bar=None, baz='Y')), |
| 2586 | ('--baz', NS(bar=None, baz='Z')), |
| 2587 | ] |
| 2588 | successes_when_not_required = [ |
| 2589 | ('', NS(bar=None, baz=None)), |
| 2590 | ] |
| 2591 | |
| 2592 | usage_when_not_required = '''\ |
| 2593 | usage: PROG [-h] [--bar BAR | --baz [BAZ]] |
| 2594 | ''' |
| 2595 | usage_when_required = '''\ |
| 2596 | usage: PROG [-h] (--bar BAR | --baz [BAZ]) |
| 2597 | ''' |
| 2598 | help = '''\ |
| 2599 | |
| 2600 | optional arguments: |
| 2601 | -h, --help show this help message and exit |
| 2602 | --bar BAR bar help |
| 2603 | --baz [BAZ] baz help |
| 2604 | ''' |
| 2605 | |
| 2606 | |
| 2607 | class TestMutuallyExclusiveLong(MEMixin, TestCase): |
| 2608 | |
| 2609 | def get_parser(self, required=None): |
| 2610 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2611 | parser.add_argument('--abcde', help='abcde help') |
| 2612 | parser.add_argument('--fghij', help='fghij help') |
| 2613 | group = parser.add_mutually_exclusive_group(required=required) |
| 2614 | group.add_argument('--klmno', help='klmno help') |
| 2615 | group.add_argument('--pqrst', help='pqrst help') |
| 2616 | return parser |
| 2617 | |
| 2618 | failures = ['--klmno X --pqrst Y'] |
| 2619 | successes = [ |
| 2620 | ('--klmno X', NS(abcde=None, fghij=None, klmno='X', pqrst=None)), |
| 2621 | ('--abcde Y --klmno X', |
| 2622 | NS(abcde='Y', fghij=None, klmno='X', pqrst=None)), |
| 2623 | ('--pqrst X', NS(abcde=None, fghij=None, klmno=None, pqrst='X')), |
| 2624 | ('--pqrst X --fghij Y', |
| 2625 | NS(abcde=None, fghij='Y', klmno=None, pqrst='X')), |
| 2626 | ] |
| 2627 | successes_when_not_required = [ |
| 2628 | ('', NS(abcde=None, fghij=None, klmno=None, pqrst=None)), |
| 2629 | ] |
| 2630 | |
| 2631 | usage_when_not_required = '''\ |
| 2632 | usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ] |
| 2633 | [--klmno KLMNO | --pqrst PQRST] |
| 2634 | ''' |
| 2635 | usage_when_required = '''\ |
| 2636 | usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ] |
| 2637 | (--klmno KLMNO | --pqrst PQRST) |
| 2638 | ''' |
| 2639 | help = '''\ |
| 2640 | |
| 2641 | optional arguments: |
| 2642 | -h, --help show this help message and exit |
| 2643 | --abcde ABCDE abcde help |
| 2644 | --fghij FGHIJ fghij help |
| 2645 | --klmno KLMNO klmno help |
| 2646 | --pqrst PQRST pqrst help |
| 2647 | ''' |
| 2648 | |
| 2649 | |
| 2650 | class TestMutuallyExclusiveFirstSuppressed(MEMixin, TestCase): |
| 2651 | |
| 2652 | def get_parser(self, required): |
| 2653 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2654 | group = parser.add_mutually_exclusive_group(required=required) |
| 2655 | group.add_argument('-x', help=argparse.SUPPRESS) |
| 2656 | group.add_argument('-y', action='store_false', help='y help') |
| 2657 | return parser |
| 2658 | |
| 2659 | failures = ['-x X -y'] |
| 2660 | successes = [ |
| 2661 | ('-x X', NS(x='X', y=True)), |
| 2662 | ('-x X -x Y', NS(x='Y', y=True)), |
| 2663 | ('-y', NS(x=None, y=False)), |
| 2664 | ] |
| 2665 | successes_when_not_required = [ |
| 2666 | ('', NS(x=None, y=True)), |
| 2667 | ] |
| 2668 | |
| 2669 | usage_when_not_required = '''\ |
| 2670 | usage: PROG [-h] [-y] |
| 2671 | ''' |
| 2672 | usage_when_required = '''\ |
| 2673 | usage: PROG [-h] -y |
| 2674 | ''' |
| 2675 | help = '''\ |
| 2676 | |
| 2677 | optional arguments: |
| 2678 | -h, --help show this help message and exit |
| 2679 | -y y help |
| 2680 | ''' |
| 2681 | |
| 2682 | |
| 2683 | class TestMutuallyExclusiveManySuppressed(MEMixin, TestCase): |
| 2684 | |
| 2685 | def get_parser(self, required): |
| 2686 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2687 | group = parser.add_mutually_exclusive_group(required=required) |
| 2688 | add = group.add_argument |
| 2689 | add('--spam', action='store_true', help=argparse.SUPPRESS) |
| 2690 | add('--badger', action='store_false', help=argparse.SUPPRESS) |
| 2691 | add('--bladder', help=argparse.SUPPRESS) |
| 2692 | return parser |
| 2693 | |
| 2694 | failures = [ |
| 2695 | '--spam --badger', |
| 2696 | '--badger --bladder B', |
| 2697 | '--bladder B --spam', |
| 2698 | ] |
| 2699 | successes = [ |
| 2700 | ('--spam', NS(spam=True, badger=True, bladder=None)), |
| 2701 | ('--badger', NS(spam=False, badger=False, bladder=None)), |
| 2702 | ('--bladder B', NS(spam=False, badger=True, bladder='B')), |
| 2703 | ('--spam --spam', NS(spam=True, badger=True, bladder=None)), |
| 2704 | ] |
| 2705 | successes_when_not_required = [ |
| 2706 | ('', NS(spam=False, badger=True, bladder=None)), |
| 2707 | ] |
| 2708 | |
| 2709 | usage_when_required = usage_when_not_required = '''\ |
| 2710 | usage: PROG [-h] |
| 2711 | ''' |
| 2712 | help = '''\ |
| 2713 | |
| 2714 | optional arguments: |
| 2715 | -h, --help show this help message and exit |
| 2716 | ''' |
| 2717 | |
| 2718 | |
| 2719 | class TestMutuallyExclusiveOptionalAndPositional(MEMixin, TestCase): |
| 2720 | |
| 2721 | def get_parser(self, required): |
| 2722 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2723 | group = parser.add_mutually_exclusive_group(required=required) |
| 2724 | group.add_argument('--foo', action='store_true', help='FOO') |
| 2725 | group.add_argument('--spam', help='SPAM') |
| 2726 | group.add_argument('badger', nargs='*', default='X', help='BADGER') |
| 2727 | return parser |
| 2728 | |
| 2729 | failures = [ |
| 2730 | '--foo --spam S', |
| 2731 | '--spam S X', |
| 2732 | 'X --foo', |
| 2733 | 'X Y Z --spam S', |
| 2734 | '--foo X Y', |
| 2735 | ] |
| 2736 | successes = [ |
| 2737 | ('--foo', NS(foo=True, spam=None, badger='X')), |
| 2738 | ('--spam S', NS(foo=False, spam='S', badger='X')), |
| 2739 | ('X', NS(foo=False, spam=None, badger=['X'])), |
| 2740 | ('X Y Z', NS(foo=False, spam=None, badger=['X', 'Y', 'Z'])), |
| 2741 | ] |
| 2742 | successes_when_not_required = [ |
| 2743 | ('', NS(foo=False, spam=None, badger='X')), |
| 2744 | ] |
| 2745 | |
| 2746 | usage_when_not_required = '''\ |
Brandt Bucher | a0ed99b | 2019-11-11 12:47:48 -0800 | [diff] [blame] | 2747 | usage: PROG [-h] [--foo | --spam SPAM | badger ...] |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2748 | ''' |
| 2749 | usage_when_required = '''\ |
Brandt Bucher | a0ed99b | 2019-11-11 12:47:48 -0800 | [diff] [blame] | 2750 | usage: PROG [-h] (--foo | --spam SPAM | badger ...) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2751 | ''' |
| 2752 | help = '''\ |
| 2753 | |
| 2754 | positional arguments: |
| 2755 | badger BADGER |
| 2756 | |
| 2757 | optional arguments: |
| 2758 | -h, --help show this help message and exit |
| 2759 | --foo FOO |
| 2760 | --spam SPAM SPAM |
| 2761 | ''' |
| 2762 | |
| 2763 | |
| 2764 | class TestMutuallyExclusiveOptionalsMixed(MEMixin, TestCase): |
| 2765 | |
| 2766 | def get_parser(self, required): |
| 2767 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2768 | parser.add_argument('-x', action='store_true', help='x help') |
| 2769 | group = parser.add_mutually_exclusive_group(required=required) |
| 2770 | group.add_argument('-a', action='store_true', help='a help') |
| 2771 | group.add_argument('-b', action='store_true', help='b help') |
| 2772 | parser.add_argument('-y', action='store_true', help='y help') |
| 2773 | group.add_argument('-c', action='store_true', help='c help') |
| 2774 | return parser |
| 2775 | |
| 2776 | failures = ['-a -b', '-b -c', '-a -c', '-a -b -c'] |
| 2777 | successes = [ |
| 2778 | ('-a', NS(a=True, b=False, c=False, x=False, y=False)), |
| 2779 | ('-b', NS(a=False, b=True, c=False, x=False, y=False)), |
| 2780 | ('-c', NS(a=False, b=False, c=True, x=False, y=False)), |
| 2781 | ('-a -x', NS(a=True, b=False, c=False, x=True, y=False)), |
| 2782 | ('-y -b', NS(a=False, b=True, c=False, x=False, y=True)), |
| 2783 | ('-x -y -c', NS(a=False, b=False, c=True, x=True, y=True)), |
| 2784 | ] |
| 2785 | successes_when_not_required = [ |
| 2786 | ('', NS(a=False, b=False, c=False, x=False, y=False)), |
| 2787 | ('-x', NS(a=False, b=False, c=False, x=True, y=False)), |
| 2788 | ('-y', NS(a=False, b=False, c=False, x=False, y=True)), |
| 2789 | ] |
| 2790 | |
| 2791 | usage_when_required = usage_when_not_required = '''\ |
| 2792 | usage: PROG [-h] [-x] [-a] [-b] [-y] [-c] |
| 2793 | ''' |
| 2794 | help = '''\ |
| 2795 | |
| 2796 | optional arguments: |
| 2797 | -h, --help show this help message and exit |
| 2798 | -x x help |
| 2799 | -a a help |
| 2800 | -b b help |
| 2801 | -y y help |
| 2802 | -c c help |
| 2803 | ''' |
| 2804 | |
| 2805 | |
Georg Brandl | 0f6b47a | 2011-01-30 12:19:35 +0000 | [diff] [blame] | 2806 | class TestMutuallyExclusiveInGroup(MEMixin, TestCase): |
| 2807 | |
| 2808 | def get_parser(self, required=None): |
| 2809 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2810 | titled_group = parser.add_argument_group( |
| 2811 | title='Titled group', description='Group description') |
| 2812 | mutex_group = \ |
| 2813 | titled_group.add_mutually_exclusive_group(required=required) |
| 2814 | mutex_group.add_argument('--bar', help='bar help') |
| 2815 | mutex_group.add_argument('--baz', help='baz help') |
| 2816 | return parser |
| 2817 | |
| 2818 | failures = ['--bar X --baz Y', '--baz X --bar Y'] |
| 2819 | successes = [ |
| 2820 | ('--bar X', NS(bar='X', baz=None)), |
| 2821 | ('--baz Y', NS(bar=None, baz='Y')), |
| 2822 | ] |
| 2823 | successes_when_not_required = [ |
| 2824 | ('', NS(bar=None, baz=None)), |
| 2825 | ] |
| 2826 | |
| 2827 | usage_when_not_required = '''\ |
| 2828 | usage: PROG [-h] [--bar BAR | --baz BAZ] |
| 2829 | ''' |
| 2830 | usage_when_required = '''\ |
| 2831 | usage: PROG [-h] (--bar BAR | --baz BAZ) |
| 2832 | ''' |
| 2833 | help = '''\ |
| 2834 | |
| 2835 | optional arguments: |
| 2836 | -h, --help show this help message and exit |
| 2837 | |
| 2838 | Titled group: |
| 2839 | Group description |
| 2840 | |
| 2841 | --bar BAR bar help |
| 2842 | --baz BAZ baz help |
| 2843 | ''' |
| 2844 | |
| 2845 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2846 | class TestMutuallyExclusiveOptionalsAndPositionalsMixed(MEMixin, TestCase): |
| 2847 | |
| 2848 | def get_parser(self, required): |
| 2849 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2850 | parser.add_argument('x', help='x help') |
| 2851 | parser.add_argument('-y', action='store_true', help='y help') |
| 2852 | group = parser.add_mutually_exclusive_group(required=required) |
| 2853 | group.add_argument('a', nargs='?', help='a help') |
| 2854 | group.add_argument('-b', action='store_true', help='b help') |
| 2855 | group.add_argument('-c', action='store_true', help='c help') |
| 2856 | return parser |
| 2857 | |
| 2858 | failures = ['X A -b', '-b -c', '-c X A'] |
| 2859 | successes = [ |
| 2860 | ('X A', NS(a='A', b=False, c=False, x='X', y=False)), |
| 2861 | ('X -b', NS(a=None, b=True, c=False, x='X', y=False)), |
| 2862 | ('X -c', NS(a=None, b=False, c=True, x='X', y=False)), |
| 2863 | ('X A -y', NS(a='A', b=False, c=False, x='X', y=True)), |
| 2864 | ('X -y -b', NS(a=None, b=True, c=False, x='X', y=True)), |
| 2865 | ] |
| 2866 | successes_when_not_required = [ |
| 2867 | ('X', NS(a=None, b=False, c=False, x='X', y=False)), |
| 2868 | ('X -y', NS(a=None, b=False, c=False, x='X', y=True)), |
| 2869 | ] |
| 2870 | |
| 2871 | usage_when_required = usage_when_not_required = '''\ |
| 2872 | usage: PROG [-h] [-y] [-b] [-c] x [a] |
| 2873 | ''' |
| 2874 | help = '''\ |
| 2875 | |
| 2876 | positional arguments: |
| 2877 | x x help |
| 2878 | a a help |
| 2879 | |
| 2880 | optional arguments: |
| 2881 | -h, --help show this help message and exit |
| 2882 | -y y help |
| 2883 | -b b help |
| 2884 | -c c help |
| 2885 | ''' |
| 2886 | |
Flavian Hautbois | da27d9b | 2019-08-25 21:06:45 +0200 | [diff] [blame] | 2887 | class TestMutuallyExclusiveNested(MEMixin, TestCase): |
| 2888 | |
| 2889 | def get_parser(self, required): |
| 2890 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2891 | group = parser.add_mutually_exclusive_group(required=required) |
| 2892 | group.add_argument('-a') |
| 2893 | group.add_argument('-b') |
| 2894 | group2 = group.add_mutually_exclusive_group(required=required) |
| 2895 | group2.add_argument('-c') |
| 2896 | group2.add_argument('-d') |
| 2897 | group3 = group2.add_mutually_exclusive_group(required=required) |
| 2898 | group3.add_argument('-e') |
| 2899 | group3.add_argument('-f') |
| 2900 | return parser |
| 2901 | |
| 2902 | usage_when_not_required = '''\ |
| 2903 | usage: PROG [-h] [-a A | -b B | [-c C | -d D | [-e E | -f F]]] |
| 2904 | ''' |
| 2905 | usage_when_required = '''\ |
| 2906 | usage: PROG [-h] (-a A | -b B | (-c C | -d D | (-e E | -f F))) |
| 2907 | ''' |
| 2908 | |
| 2909 | help = '''\ |
| 2910 | |
| 2911 | optional arguments: |
| 2912 | -h, --help show this help message and exit |
| 2913 | -a A |
| 2914 | -b B |
| 2915 | -c C |
| 2916 | -d D |
| 2917 | -e E |
| 2918 | -f F |
| 2919 | ''' |
| 2920 | |
| 2921 | # We are only interested in testing the behavior of format_usage(). |
| 2922 | test_failures_when_not_required = None |
| 2923 | test_failures_when_required = None |
| 2924 | test_successes_when_not_required = None |
| 2925 | test_successes_when_required = None |
| 2926 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2927 | # ================================================= |
| 2928 | # Mutually exclusive group in parent parser tests |
| 2929 | # ================================================= |
| 2930 | |
| 2931 | class MEPBase(object): |
| 2932 | |
| 2933 | def get_parser(self, required=None): |
| 2934 | parent = super(MEPBase, self).get_parser(required=required) |
| 2935 | parser = ErrorRaisingArgumentParser( |
| 2936 | prog=parent.prog, add_help=False, parents=[parent]) |
| 2937 | return parser |
| 2938 | |
| 2939 | |
| 2940 | class TestMutuallyExclusiveGroupErrorsParent( |
| 2941 | MEPBase, TestMutuallyExclusiveGroupErrors): |
| 2942 | pass |
| 2943 | |
| 2944 | |
| 2945 | class TestMutuallyExclusiveSimpleParent( |
| 2946 | MEPBase, TestMutuallyExclusiveSimple): |
| 2947 | pass |
| 2948 | |
| 2949 | |
| 2950 | class TestMutuallyExclusiveLongParent( |
| 2951 | MEPBase, TestMutuallyExclusiveLong): |
| 2952 | pass |
| 2953 | |
| 2954 | |
| 2955 | class TestMutuallyExclusiveFirstSuppressedParent( |
| 2956 | MEPBase, TestMutuallyExclusiveFirstSuppressed): |
| 2957 | pass |
| 2958 | |
| 2959 | |
| 2960 | class TestMutuallyExclusiveManySuppressedParent( |
| 2961 | MEPBase, TestMutuallyExclusiveManySuppressed): |
| 2962 | pass |
| 2963 | |
| 2964 | |
| 2965 | class TestMutuallyExclusiveOptionalAndPositionalParent( |
| 2966 | MEPBase, TestMutuallyExclusiveOptionalAndPositional): |
| 2967 | pass |
| 2968 | |
| 2969 | |
| 2970 | class TestMutuallyExclusiveOptionalsMixedParent( |
| 2971 | MEPBase, TestMutuallyExclusiveOptionalsMixed): |
| 2972 | pass |
| 2973 | |
| 2974 | |
| 2975 | class TestMutuallyExclusiveOptionalsAndPositionalsMixedParent( |
| 2976 | MEPBase, TestMutuallyExclusiveOptionalsAndPositionalsMixed): |
| 2977 | pass |
| 2978 | |
| 2979 | # ================= |
| 2980 | # Set default tests |
| 2981 | # ================= |
| 2982 | |
| 2983 | class TestSetDefaults(TestCase): |
| 2984 | |
| 2985 | def test_set_defaults_no_args(self): |
| 2986 | parser = ErrorRaisingArgumentParser() |
| 2987 | parser.set_defaults(x='foo') |
| 2988 | parser.set_defaults(y='bar', z=1) |
| 2989 | self.assertEqual(NS(x='foo', y='bar', z=1), |
| 2990 | parser.parse_args([])) |
| 2991 | self.assertEqual(NS(x='foo', y='bar', z=1), |
| 2992 | parser.parse_args([], NS())) |
| 2993 | self.assertEqual(NS(x='baz', y='bar', z=1), |
| 2994 | parser.parse_args([], NS(x='baz'))) |
| 2995 | self.assertEqual(NS(x='baz', y='bar', z=2), |
| 2996 | parser.parse_args([], NS(x='baz', z=2))) |
| 2997 | |
| 2998 | def test_set_defaults_with_args(self): |
| 2999 | parser = ErrorRaisingArgumentParser() |
| 3000 | parser.set_defaults(x='foo', y='bar') |
| 3001 | parser.add_argument('-x', default='xfoox') |
| 3002 | self.assertEqual(NS(x='xfoox', y='bar'), |
| 3003 | parser.parse_args([])) |
| 3004 | self.assertEqual(NS(x='xfoox', y='bar'), |
| 3005 | parser.parse_args([], NS())) |
| 3006 | self.assertEqual(NS(x='baz', y='bar'), |
| 3007 | parser.parse_args([], NS(x='baz'))) |
| 3008 | self.assertEqual(NS(x='1', y='bar'), |
| 3009 | parser.parse_args('-x 1'.split())) |
| 3010 | self.assertEqual(NS(x='1', y='bar'), |
| 3011 | parser.parse_args('-x 1'.split(), NS())) |
| 3012 | self.assertEqual(NS(x='1', y='bar'), |
| 3013 | parser.parse_args('-x 1'.split(), NS(x='baz'))) |
| 3014 | |
| 3015 | def test_set_defaults_subparsers(self): |
| 3016 | parser = ErrorRaisingArgumentParser() |
| 3017 | parser.set_defaults(x='foo') |
| 3018 | subparsers = parser.add_subparsers() |
| 3019 | parser_a = subparsers.add_parser('a') |
| 3020 | parser_a.set_defaults(y='bar') |
| 3021 | self.assertEqual(NS(x='foo', y='bar'), |
| 3022 | parser.parse_args('a'.split())) |
| 3023 | |
| 3024 | def test_set_defaults_parents(self): |
| 3025 | parent = ErrorRaisingArgumentParser(add_help=False) |
| 3026 | parent.set_defaults(x='foo') |
| 3027 | parser = ErrorRaisingArgumentParser(parents=[parent]) |
| 3028 | self.assertEqual(NS(x='foo'), parser.parse_args([])) |
| 3029 | |
R David Murray | 7570cbd | 2014-10-17 19:55:11 -0400 | [diff] [blame] | 3030 | def test_set_defaults_on_parent_and_subparser(self): |
| 3031 | parser = argparse.ArgumentParser() |
| 3032 | xparser = parser.add_subparsers().add_parser('X') |
| 3033 | parser.set_defaults(foo=1) |
| 3034 | xparser.set_defaults(foo=2) |
| 3035 | self.assertEqual(NS(foo=2), parser.parse_args(['X'])) |
| 3036 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3037 | def test_set_defaults_same_as_add_argument(self): |
| 3038 | parser = ErrorRaisingArgumentParser() |
| 3039 | parser.set_defaults(w='W', x='X', y='Y', z='Z') |
| 3040 | parser.add_argument('-w') |
| 3041 | parser.add_argument('-x', default='XX') |
| 3042 | parser.add_argument('y', nargs='?') |
| 3043 | parser.add_argument('z', nargs='?', default='ZZ') |
| 3044 | |
| 3045 | # defaults set previously |
| 3046 | self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'), |
| 3047 | parser.parse_args([])) |
| 3048 | |
| 3049 | # reset defaults |
| 3050 | parser.set_defaults(w='WW', x='X', y='YY', z='Z') |
| 3051 | self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'), |
| 3052 | parser.parse_args([])) |
| 3053 | |
| 3054 | def test_set_defaults_same_as_add_argument_group(self): |
| 3055 | parser = ErrorRaisingArgumentParser() |
| 3056 | parser.set_defaults(w='W', x='X', y='Y', z='Z') |
| 3057 | group = parser.add_argument_group('foo') |
| 3058 | group.add_argument('-w') |
| 3059 | group.add_argument('-x', default='XX') |
| 3060 | group.add_argument('y', nargs='?') |
| 3061 | group.add_argument('z', nargs='?', default='ZZ') |
| 3062 | |
| 3063 | |
| 3064 | # defaults set previously |
| 3065 | self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'), |
| 3066 | parser.parse_args([])) |
| 3067 | |
| 3068 | # reset defaults |
| 3069 | parser.set_defaults(w='WW', x='X', y='YY', z='Z') |
| 3070 | self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'), |
| 3071 | parser.parse_args([])) |
| 3072 | |
| 3073 | # ================= |
| 3074 | # Get default tests |
| 3075 | # ================= |
| 3076 | |
| 3077 | class TestGetDefault(TestCase): |
| 3078 | |
| 3079 | def test_get_default(self): |
| 3080 | parser = ErrorRaisingArgumentParser() |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 3081 | self.assertIsNone(parser.get_default("foo")) |
| 3082 | self.assertIsNone(parser.get_default("bar")) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3083 | |
| 3084 | parser.add_argument("--foo") |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 3085 | self.assertIsNone(parser.get_default("foo")) |
| 3086 | self.assertIsNone(parser.get_default("bar")) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3087 | |
| 3088 | parser.add_argument("--bar", type=int, default=42) |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 3089 | self.assertIsNone(parser.get_default("foo")) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3090 | self.assertEqual(42, parser.get_default("bar")) |
| 3091 | |
| 3092 | parser.set_defaults(foo="badger") |
| 3093 | self.assertEqual("badger", parser.get_default("foo")) |
| 3094 | self.assertEqual(42, parser.get_default("bar")) |
| 3095 | |
| 3096 | # ========================== |
| 3097 | # Namespace 'contains' tests |
| 3098 | # ========================== |
| 3099 | |
| 3100 | class TestNamespaceContainsSimple(TestCase): |
| 3101 | |
| 3102 | def test_empty(self): |
| 3103 | ns = argparse.Namespace() |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 3104 | self.assertNotIn('', ns) |
| 3105 | self.assertNotIn('x', ns) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3106 | |
| 3107 | def test_non_empty(self): |
| 3108 | ns = argparse.Namespace(x=1, y=2) |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 3109 | self.assertNotIn('', ns) |
| 3110 | self.assertIn('x', ns) |
| 3111 | self.assertIn('y', ns) |
| 3112 | self.assertNotIn('xx', ns) |
| 3113 | self.assertNotIn('z', ns) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3114 | |
| 3115 | # ===================== |
| 3116 | # Help formatting tests |
| 3117 | # ===================== |
| 3118 | |
| 3119 | class TestHelpFormattingMetaclass(type): |
| 3120 | |
| 3121 | def __init__(cls, name, bases, bodydict): |
| 3122 | if name == 'HelpTestCase': |
| 3123 | return |
| 3124 | |
| 3125 | class AddTests(object): |
| 3126 | |
| 3127 | def __init__(self, test_class, func_suffix, std_name): |
| 3128 | self.func_suffix = func_suffix |
| 3129 | self.std_name = std_name |
| 3130 | |
| 3131 | for test_func in [self.test_format, |
| 3132 | self.test_print, |
| 3133 | self.test_print_file]: |
| 3134 | test_name = '%s_%s' % (test_func.__name__, func_suffix) |
| 3135 | |
| 3136 | def test_wrapper(self, test_func=test_func): |
| 3137 | test_func(self) |
| 3138 | try: |
| 3139 | test_wrapper.__name__ = test_name |
| 3140 | except TypeError: |
| 3141 | pass |
| 3142 | setattr(test_class, test_name, test_wrapper) |
| 3143 | |
| 3144 | def _get_parser(self, tester): |
| 3145 | parser = argparse.ArgumentParser( |
| 3146 | *tester.parser_signature.args, |
| 3147 | **tester.parser_signature.kwargs) |
Steven Bethard | 8a6a198 | 2011-03-27 13:53:53 +0200 | [diff] [blame] | 3148 | for argument_sig in getattr(tester, 'argument_signatures', []): |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3149 | parser.add_argument(*argument_sig.args, |
| 3150 | **argument_sig.kwargs) |
Steven Bethard | 8a6a198 | 2011-03-27 13:53:53 +0200 | [diff] [blame] | 3151 | group_sigs = getattr(tester, 'argument_group_signatures', []) |
| 3152 | for group_sig, argument_sigs in group_sigs: |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3153 | group = parser.add_argument_group(*group_sig.args, |
| 3154 | **group_sig.kwargs) |
| 3155 | for argument_sig in argument_sigs: |
| 3156 | group.add_argument(*argument_sig.args, |
| 3157 | **argument_sig.kwargs) |
Steven Bethard | 8a6a198 | 2011-03-27 13:53:53 +0200 | [diff] [blame] | 3158 | subparsers_sigs = getattr(tester, 'subparsers_signatures', []) |
| 3159 | if subparsers_sigs: |
| 3160 | subparsers = parser.add_subparsers() |
| 3161 | for subparser_sig in subparsers_sigs: |
| 3162 | subparsers.add_parser(*subparser_sig.args, |
| 3163 | **subparser_sig.kwargs) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3164 | return parser |
| 3165 | |
| 3166 | def _test(self, tester, parser_text): |
| 3167 | expected_text = getattr(tester, self.func_suffix) |
| 3168 | expected_text = textwrap.dedent(expected_text) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3169 | tester.assertEqual(expected_text, parser_text) |
| 3170 | |
| 3171 | def test_format(self, tester): |
| 3172 | parser = self._get_parser(tester) |
| 3173 | format = getattr(parser, 'format_%s' % self.func_suffix) |
| 3174 | self._test(tester, format()) |
| 3175 | |
| 3176 | def test_print(self, tester): |
| 3177 | parser = self._get_parser(tester) |
| 3178 | print_ = getattr(parser, 'print_%s' % self.func_suffix) |
| 3179 | old_stream = getattr(sys, self.std_name) |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 3180 | setattr(sys, self.std_name, StdIOBuffer()) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3181 | try: |
| 3182 | print_() |
| 3183 | parser_text = getattr(sys, self.std_name).getvalue() |
| 3184 | finally: |
| 3185 | setattr(sys, self.std_name, old_stream) |
| 3186 | self._test(tester, parser_text) |
| 3187 | |
| 3188 | def test_print_file(self, tester): |
| 3189 | parser = self._get_parser(tester) |
| 3190 | print_ = getattr(parser, 'print_%s' % self.func_suffix) |
Benjamin Peterson | b48af54 | 2010-04-11 20:43:16 +0000 | [diff] [blame] | 3191 | sfile = StdIOBuffer() |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3192 | print_(sfile) |
| 3193 | parser_text = sfile.getvalue() |
| 3194 | self._test(tester, parser_text) |
| 3195 | |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 3196 | # add tests for {format,print}_{usage,help} |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3197 | for func_suffix, std_name in [('usage', 'stdout'), |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 3198 | ('help', 'stdout')]: |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3199 | AddTests(cls, func_suffix, std_name) |
| 3200 | |
| 3201 | bases = TestCase, |
| 3202 | HelpTestCase = TestHelpFormattingMetaclass('HelpTestCase', bases, {}) |
| 3203 | |
| 3204 | |
| 3205 | class TestHelpBiggerOptionals(HelpTestCase): |
| 3206 | """Make sure that argument help aligns when options are longer""" |
| 3207 | |
| 3208 | parser_signature = Sig(prog='PROG', description='DESCRIPTION', |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 3209 | epilog='EPILOG') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3210 | argument_signatures = [ |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 3211 | Sig('-v', '--version', action='version', version='0.1'), |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3212 | Sig('-x', action='store_true', help='X HELP'), |
| 3213 | Sig('--y', help='Y HELP'), |
| 3214 | Sig('foo', help='FOO HELP'), |
| 3215 | Sig('bar', help='BAR HELP'), |
| 3216 | ] |
| 3217 | argument_group_signatures = [] |
| 3218 | usage = '''\ |
| 3219 | usage: PROG [-h] [-v] [-x] [--y Y] foo bar |
| 3220 | ''' |
| 3221 | help = usage + '''\ |
| 3222 | |
| 3223 | DESCRIPTION |
| 3224 | |
| 3225 | positional arguments: |
| 3226 | foo FOO HELP |
| 3227 | bar BAR HELP |
| 3228 | |
| 3229 | optional arguments: |
| 3230 | -h, --help show this help message and exit |
| 3231 | -v, --version show program's version number and exit |
| 3232 | -x X HELP |
| 3233 | --y Y Y HELP |
| 3234 | |
| 3235 | EPILOG |
| 3236 | ''' |
| 3237 | version = '''\ |
| 3238 | 0.1 |
| 3239 | ''' |
| 3240 | |
Serhiy Storchaka | f451112 | 2014-01-09 23:14:27 +0200 | [diff] [blame] | 3241 | class TestShortColumns(HelpTestCase): |
| 3242 | '''Test extremely small number of columns. |
| 3243 | |
| 3244 | TestCase prevents "COLUMNS" from being too small in the tests themselves, |
Martin Panter | 2e4571a | 2015-11-14 01:07:43 +0000 | [diff] [blame] | 3245 | but we don't want any exceptions thrown in such cases. Only ugly representation. |
Serhiy Storchaka | f451112 | 2014-01-09 23:14:27 +0200 | [diff] [blame] | 3246 | ''' |
| 3247 | def setUp(self): |
Hai Shi | 4660597 | 2020-08-04 00:49:18 +0800 | [diff] [blame] | 3248 | env = os_helper.EnvironmentVarGuard() |
Serhiy Storchaka | f451112 | 2014-01-09 23:14:27 +0200 | [diff] [blame] | 3249 | env.set("COLUMNS", '15') |
| 3250 | self.addCleanup(env.__exit__) |
| 3251 | |
| 3252 | parser_signature = TestHelpBiggerOptionals.parser_signature |
| 3253 | argument_signatures = TestHelpBiggerOptionals.argument_signatures |
| 3254 | argument_group_signatures = TestHelpBiggerOptionals.argument_group_signatures |
| 3255 | usage = '''\ |
| 3256 | usage: PROG |
| 3257 | [-h] |
| 3258 | [-v] |
| 3259 | [-x] |
| 3260 | [--y Y] |
| 3261 | foo |
| 3262 | bar |
| 3263 | ''' |
| 3264 | help = usage + '''\ |
| 3265 | |
| 3266 | DESCRIPTION |
| 3267 | |
| 3268 | positional arguments: |
| 3269 | foo |
| 3270 | FOO HELP |
| 3271 | bar |
| 3272 | BAR HELP |
| 3273 | |
| 3274 | optional arguments: |
| 3275 | -h, --help |
| 3276 | show this |
| 3277 | help |
| 3278 | message and |
| 3279 | exit |
| 3280 | -v, --version |
| 3281 | show |
| 3282 | program's |
| 3283 | version |
| 3284 | number and |
| 3285 | exit |
| 3286 | -x |
| 3287 | X HELP |
| 3288 | --y Y |
| 3289 | Y HELP |
| 3290 | |
| 3291 | EPILOG |
| 3292 | ''' |
| 3293 | version = TestHelpBiggerOptionals.version |
| 3294 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3295 | |
| 3296 | class TestHelpBiggerOptionalGroups(HelpTestCase): |
| 3297 | """Make sure that argument help aligns when options are longer""" |
| 3298 | |
| 3299 | parser_signature = Sig(prog='PROG', description='DESCRIPTION', |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 3300 | epilog='EPILOG') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3301 | argument_signatures = [ |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 3302 | Sig('-v', '--version', action='version', version='0.1'), |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3303 | Sig('-x', action='store_true', help='X HELP'), |
| 3304 | Sig('--y', help='Y HELP'), |
| 3305 | Sig('foo', help='FOO HELP'), |
| 3306 | Sig('bar', help='BAR HELP'), |
| 3307 | ] |
| 3308 | argument_group_signatures = [ |
| 3309 | (Sig('GROUP TITLE', description='GROUP DESCRIPTION'), [ |
| 3310 | Sig('baz', help='BAZ HELP'), |
| 3311 | Sig('-z', nargs='+', help='Z HELP')]), |
| 3312 | ] |
| 3313 | usage = '''\ |
| 3314 | usage: PROG [-h] [-v] [-x] [--y Y] [-z Z [Z ...]] foo bar baz |
| 3315 | ''' |
| 3316 | help = usage + '''\ |
| 3317 | |
| 3318 | DESCRIPTION |
| 3319 | |
| 3320 | positional arguments: |
| 3321 | foo FOO HELP |
| 3322 | bar BAR HELP |
| 3323 | |
| 3324 | optional arguments: |
| 3325 | -h, --help show this help message and exit |
| 3326 | -v, --version show program's version number and exit |
| 3327 | -x X HELP |
| 3328 | --y Y Y HELP |
| 3329 | |
| 3330 | GROUP TITLE: |
| 3331 | GROUP DESCRIPTION |
| 3332 | |
| 3333 | baz BAZ HELP |
| 3334 | -z Z [Z ...] Z HELP |
| 3335 | |
| 3336 | EPILOG |
| 3337 | ''' |
| 3338 | version = '''\ |
| 3339 | 0.1 |
| 3340 | ''' |
| 3341 | |
| 3342 | |
| 3343 | class TestHelpBiggerPositionals(HelpTestCase): |
| 3344 | """Make sure that help aligns when arguments are longer""" |
| 3345 | |
| 3346 | parser_signature = Sig(usage='USAGE', description='DESCRIPTION') |
| 3347 | argument_signatures = [ |
| 3348 | Sig('-x', action='store_true', help='X HELP'), |
| 3349 | Sig('--y', help='Y HELP'), |
| 3350 | Sig('ekiekiekifekang', help='EKI HELP'), |
| 3351 | Sig('bar', help='BAR HELP'), |
| 3352 | ] |
| 3353 | argument_group_signatures = [] |
| 3354 | usage = '''\ |
| 3355 | usage: USAGE |
| 3356 | ''' |
| 3357 | help = usage + '''\ |
| 3358 | |
| 3359 | DESCRIPTION |
| 3360 | |
| 3361 | positional arguments: |
| 3362 | ekiekiekifekang EKI HELP |
| 3363 | bar BAR HELP |
| 3364 | |
| 3365 | optional arguments: |
| 3366 | -h, --help show this help message and exit |
| 3367 | -x X HELP |
| 3368 | --y Y Y HELP |
| 3369 | ''' |
| 3370 | |
| 3371 | version = '' |
| 3372 | |
| 3373 | |
| 3374 | class TestHelpReformatting(HelpTestCase): |
| 3375 | """Make sure that text after short names starts on the first line""" |
| 3376 | |
| 3377 | parser_signature = Sig( |
| 3378 | prog='PROG', |
| 3379 | description=' oddly formatted\n' |
| 3380 | 'description\n' |
| 3381 | '\n' |
| 3382 | 'that is so long that it should go onto multiple ' |
| 3383 | 'lines when wrapped') |
| 3384 | argument_signatures = [ |
| 3385 | Sig('-x', metavar='XX', help='oddly\n' |
| 3386 | ' formatted -x help'), |
| 3387 | Sig('y', metavar='yyy', help='normal y help'), |
| 3388 | ] |
| 3389 | argument_group_signatures = [ |
| 3390 | (Sig('title', description='\n' |
| 3391 | ' oddly formatted group\n' |
| 3392 | '\n' |
| 3393 | 'description'), |
| 3394 | [Sig('-a', action='store_true', |
| 3395 | help=' oddly \n' |
| 3396 | 'formatted -a help \n' |
| 3397 | ' again, so long that it should be wrapped over ' |
| 3398 | 'multiple lines')]), |
| 3399 | ] |
| 3400 | usage = '''\ |
| 3401 | usage: PROG [-h] [-x XX] [-a] yyy |
| 3402 | ''' |
| 3403 | help = usage + '''\ |
| 3404 | |
| 3405 | oddly formatted description that is so long that it should go onto \ |
| 3406 | multiple |
| 3407 | lines when wrapped |
| 3408 | |
| 3409 | positional arguments: |
| 3410 | yyy normal y help |
| 3411 | |
| 3412 | optional arguments: |
| 3413 | -h, --help show this help message and exit |
| 3414 | -x XX oddly formatted -x help |
| 3415 | |
| 3416 | title: |
| 3417 | oddly formatted group description |
| 3418 | |
| 3419 | -a oddly formatted -a help again, so long that it should \ |
| 3420 | be wrapped |
| 3421 | over multiple lines |
| 3422 | ''' |
| 3423 | version = '' |
| 3424 | |
| 3425 | |
| 3426 | class TestHelpWrappingShortNames(HelpTestCase): |
| 3427 | """Make sure that text after short names starts on the first line""" |
| 3428 | |
| 3429 | parser_signature = Sig(prog='PROG', description= 'D\nD' * 30) |
| 3430 | argument_signatures = [ |
| 3431 | Sig('-x', metavar='XX', help='XHH HX' * 20), |
| 3432 | Sig('y', metavar='yyy', help='YH YH' * 20), |
| 3433 | ] |
| 3434 | argument_group_signatures = [ |
| 3435 | (Sig('ALPHAS'), [ |
| 3436 | Sig('-a', action='store_true', help='AHHH HHA' * 10)]), |
| 3437 | ] |
| 3438 | usage = '''\ |
| 3439 | usage: PROG [-h] [-x XX] [-a] yyy |
| 3440 | ''' |
| 3441 | help = usage + '''\ |
| 3442 | |
| 3443 | D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \ |
| 3444 | DD DD DD |
| 3445 | DD DD DD DD D |
| 3446 | |
| 3447 | positional arguments: |
| 3448 | yyy YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \ |
| 3449 | YHYH YHYH |
| 3450 | YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH |
| 3451 | |
| 3452 | optional arguments: |
| 3453 | -h, --help show this help message and exit |
| 3454 | -x XX XHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH \ |
| 3455 | HXXHH HXXHH |
| 3456 | HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HX |
| 3457 | |
| 3458 | ALPHAS: |
| 3459 | -a AHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH \ |
| 3460 | HHAAHHH |
| 3461 | HHAAHHH HHAAHHH HHA |
| 3462 | ''' |
| 3463 | version = '' |
| 3464 | |
| 3465 | |
| 3466 | class TestHelpWrappingLongNames(HelpTestCase): |
| 3467 | """Make sure that text after long names starts on the next line""" |
| 3468 | |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 3469 | parser_signature = Sig(usage='USAGE', description= 'D D' * 30) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3470 | argument_signatures = [ |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 3471 | Sig('-v', '--version', action='version', version='V V' * 30), |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3472 | Sig('-x', metavar='X' * 25, help='XH XH' * 20), |
| 3473 | Sig('y', metavar='y' * 25, help='YH YH' * 20), |
| 3474 | ] |
| 3475 | argument_group_signatures = [ |
| 3476 | (Sig('ALPHAS'), [ |
| 3477 | Sig('-a', metavar='A' * 25, help='AH AH' * 20), |
| 3478 | Sig('z', metavar='z' * 25, help='ZH ZH' * 20)]), |
| 3479 | ] |
| 3480 | usage = '''\ |
| 3481 | usage: USAGE |
| 3482 | ''' |
| 3483 | help = usage + '''\ |
| 3484 | |
| 3485 | D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \ |
| 3486 | DD DD DD |
| 3487 | DD DD DD DD D |
| 3488 | |
| 3489 | positional arguments: |
| 3490 | yyyyyyyyyyyyyyyyyyyyyyyyy |
| 3491 | YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \ |
| 3492 | YHYH YHYH |
| 3493 | YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH |
| 3494 | |
| 3495 | optional arguments: |
| 3496 | -h, --help show this help message and exit |
| 3497 | -v, --version show program's version number and exit |
| 3498 | -x XXXXXXXXXXXXXXXXXXXXXXXXX |
| 3499 | XH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH \ |
| 3500 | XHXH XHXH |
| 3501 | XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XH |
| 3502 | |
| 3503 | ALPHAS: |
| 3504 | -a AAAAAAAAAAAAAAAAAAAAAAAAA |
| 3505 | AH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH \ |
| 3506 | AHAH AHAH |
| 3507 | AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AH |
| 3508 | zzzzzzzzzzzzzzzzzzzzzzzzz |
| 3509 | ZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH \ |
| 3510 | ZHZH ZHZH |
| 3511 | ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZH |
| 3512 | ''' |
| 3513 | version = '''\ |
| 3514 | V VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV \ |
| 3515 | VV VV VV |
| 3516 | VV VV VV VV V |
| 3517 | ''' |
| 3518 | |
| 3519 | |
| 3520 | class TestHelpUsage(HelpTestCase): |
| 3521 | """Test basic usage messages""" |
| 3522 | |
| 3523 | parser_signature = Sig(prog='PROG') |
| 3524 | argument_signatures = [ |
| 3525 | Sig('-w', nargs='+', help='w'), |
| 3526 | Sig('-x', nargs='*', help='x'), |
| 3527 | Sig('a', help='a'), |
| 3528 | Sig('b', help='b', nargs=2), |
| 3529 | Sig('c', help='c', nargs='?'), |
Rémi Lapeyre | 6a517c6 | 2019-09-13 12:17:43 +0200 | [diff] [blame] | 3530 | Sig('--foo', help='Whether to foo', action=argparse.BooleanOptionalAction), |
| 3531 | Sig('--bar', help='Whether to bar', default=True, |
| 3532 | action=argparse.BooleanOptionalAction), |
| 3533 | Sig('-f', '--foobar', '--barfoo', action=argparse.BooleanOptionalAction), |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3534 | ] |
| 3535 | argument_group_signatures = [ |
| 3536 | (Sig('group'), [ |
| 3537 | Sig('-y', nargs='?', help='y'), |
| 3538 | Sig('-z', nargs=3, help='z'), |
| 3539 | Sig('d', help='d', nargs='*'), |
| 3540 | Sig('e', help='e', nargs='+'), |
| 3541 | ]) |
| 3542 | ] |
| 3543 | usage = '''\ |
Brandt Bucher | a0ed99b | 2019-11-11 12:47:48 -0800 | [diff] [blame] | 3544 | usage: PROG [-h] [-w W [W ...]] [-x [X ...]] [--foo | --no-foo] |
Rémi Lapeyre | 6a517c6 | 2019-09-13 12:17:43 +0200 | [diff] [blame] | 3545 | [--bar | --no-bar] |
| 3546 | [-f | --foobar | --no-foobar | --barfoo | --no-barfoo] [-y [Y]] |
| 3547 | [-z Z Z Z] |
Brandt Bucher | a0ed99b | 2019-11-11 12:47:48 -0800 | [diff] [blame] | 3548 | a b b [c] [d ...] e [e ...] |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3549 | ''' |
| 3550 | help = usage + '''\ |
| 3551 | |
| 3552 | positional arguments: |
Rémi Lapeyre | 6a517c6 | 2019-09-13 12:17:43 +0200 | [diff] [blame] | 3553 | a a |
| 3554 | b b |
| 3555 | c c |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3556 | |
| 3557 | optional arguments: |
Rémi Lapeyre | 6a517c6 | 2019-09-13 12:17:43 +0200 | [diff] [blame] | 3558 | -h, --help show this help message and exit |
| 3559 | -w W [W ...] w |
Brandt Bucher | a0ed99b | 2019-11-11 12:47:48 -0800 | [diff] [blame] | 3560 | -x [X ...] x |
Rémi Lapeyre | 6a517c6 | 2019-09-13 12:17:43 +0200 | [diff] [blame] | 3561 | --foo, --no-foo Whether to foo |
| 3562 | --bar, --no-bar Whether to bar (default: True) |
| 3563 | -f, --foobar, --no-foobar, --barfoo, --no-barfoo |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3564 | |
| 3565 | group: |
Rémi Lapeyre | 6a517c6 | 2019-09-13 12:17:43 +0200 | [diff] [blame] | 3566 | -y [Y] y |
| 3567 | -z Z Z Z z |
| 3568 | d d |
| 3569 | e e |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 3570 | ''' |
| 3571 | version = '' |
| 3572 | |
| 3573 | |
| 3574 | class TestHelpOnlyUserGroups(HelpTestCase): |
| 3575 | """Test basic usage messages""" |
| 3576 | |
| 3577 | parser_signature = Sig(prog='PROG', add_help=False) |
| 3578 | argument_signatures = [] |
| 3579 | argument_group_signatures = [ |
| 3580 | (Sig('xxxx'), [ |
| 3581 | Sig('-x', help='x'), |
| 3582 | Sig('a', help='a'), |
| 3583 | ]), |
| 3584 | (Sig('yyyy'), [ |
| 3585 | Sig('b', help='b'), |
| 3586 | Sig('-y', help='y'), |
| 3587 | ]), |
| 3588 | ] |
| 3589 | usage = '''\ |
| 3590 | usage: PROG [-x X] [-y Y] a b |
| 3591 | ''' |
| 3592 | help = usage + '''\ |
| 3593 | |
| 3594 | xxxx: |
| 3595 | -x X x |
| 3596 | a a |
| 3597 | |
| 3598 | yyyy: |
| 3599 | b b |
| 3600 | -y Y y |
| 3601 | ''' |
| 3602 | version = '' |
| 3603 | |
| 3604 | |
| 3605 | class TestHelpUsageLongProg(HelpTestCase): |
| 3606 | """Test usage messages where the prog is long""" |
| 3607 | |
| 3608 | parser_signature = Sig(prog='P' * 60) |
| 3609 | argument_signatures = [ |
| 3610 | Sig('-w', metavar='W'), |
| 3611 | Sig('-x', metavar='X'), |
| 3612 | Sig('a'), |
| 3613 | Sig('b'), |
| 3614 | ] |
| 3615 | argument_group_signatures = [] |
| 3616 | usage = '''\ |
| 3617 | usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP |
| 3618 | [-h] [-w W] [-x X] a b |
| 3619 | ''' |
| 3620 | help = usage + '''\ |
| 3621 | |
| 3622 | positional arguments: |
| 3623 | a |
| 3624 | b |
| 3625 | |
| 3626 | optional arguments: |
| 3627 | -h, --help show this help message and exit |
| 3628 | -w W |
| 3629 | -x X |
| 3630 | ''' |
| 3631 | version = '' |
| 3632 | |
| 3633 | |
| 3634 | class TestHelpUsageLongProgOptionsWrap(HelpTestCase): |
| 3635 | """Test usage messages where the prog is long and the optionals wrap""" |
| 3636 | |
| 3637 | parser_signature = Sig(prog='P' * 60) |
| 3638 | argument_signatures = [ |
| 3639 | Sig('-w', metavar='W' * 25), |
| 3640 | Sig('-x', metavar='X' * 25), |
| 3641 | Sig('-y', metavar='Y' * 25), |
| 3642 | Sig('-z', metavar='Z' * 25), |
| 3643 | Sig('a'), |
| 3644 | Sig('b'), |
| 3645 | ] |
| 3646 | argument_group_signatures = [] |
| 3647 | usage = '''\ |
| 3648 | usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP |
| 3649 | [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \ |
| 3650 | [-x XXXXXXXXXXXXXXXXXXXXXXXXX] |
| 3651 | [-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ] |
| 3652 | a b |
| 3653 | ''' |
| 3654 | help = usage + '''\ |
| 3655 | |
| 3656 | positional arguments: |
| 3657 | a |
| 3658 | b |
| 3659 | |
| 3660 | optional arguments: |
| 3661 | -h, --help show this help message and exit |
| 3662 | -w WWWWWWWWWWWWWWWWWWWWWWWWW |
| 3663 | -x XXXXXXXXXXXXXXXXXXXXXXXXX |
| 3664 | -y YYYYYYYYYYYYYYYYYYYYYYYYY |
| 3665 | -z ZZZZZZZZZZZZZZZZZZZZZZZZZ |
| 3666 | ''' |
| 3667 | version = '' |
| 3668 | |
| 3669 | |
| 3670 | class TestHelpUsageLongProgPositionalsWrap(HelpTestCase): |
| 3671 | """Test usage messages where the prog is long and the positionals wrap""" |
| 3672 | |
| 3673 | parser_signature = Sig(prog='P' * 60, add_help=False) |
| 3674 | argument_signatures = [ |
| 3675 | Sig('a' * 25), |
| 3676 | Sig('b' * 25), |
| 3677 | Sig('c' * 25), |
| 3678 | ] |
| 3679 | argument_group_signatures = [] |
| 3680 | usage = '''\ |
| 3681 | usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP |
| 3682 | aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb |
| 3683 | ccccccccccccccccccccccccc |
| 3684 | ''' |
| 3685 | help = usage + '''\ |
| 3686 | |
| 3687 | positional arguments: |
| 3688 | aaaaaaaaaaaaaaaaaaaaaaaaa |
| 3689 | bbbbbbbbbbbbbbbbbbbbbbbbb |
| 3690 | ccccccccccccccccccccccccc |
| 3691 | ''' |
| 3692 | version = '' |
| 3693 | |
| 3694 | |
| 3695 | class TestHelpUsageOptionalsWrap(HelpTestCase): |
| 3696 | """Test usage messages where the optionals wrap""" |
| 3697 | |
| 3698 | parser_signature = Sig(prog='PROG') |
| 3699 | argument_signatures = [ |
| 3700 | Sig('-w', metavar='W' * 25), |
| 3701 | Sig('-x', metavar='X' * 25), |
| 3702 | Sig('-y', metavar='Y' * 25), |
| 3703 | Sig('-z', metavar='Z' * 25), |
| 3704 | Sig('a'), |
| 3705 | Sig('b'), |
| 3706 | Sig('c'), |
| 3707 | ] |
| 3708 | argument_group_signatures = [] |
| 3709 | usage = '''\ |
| 3710 | usage: PROG [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \ |
| 3711 | [-x XXXXXXXXXXXXXXXXXXXXXXXXX] |
| 3712 | [-y YYYYYYYYYYYYYYYYYYYYYYYYY] \ |
| 3713 | [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ] |
| 3714 | a b c |
| 3715 | ''' |
| 3716 | help = usage + '''\ |
| 3717 | |
| 3718 | positional arguments: |
| 3719 | a |
| 3720 | b |
| 3721 | c |
| 3722 | |
| 3723 | optional arguments: |
| 3724 | -h, --help show this help message and exit |
| 3725 | -w WWWWWWWWWWWWWWWWWWWWWWWWW |
| 3726 | -x XXXXXXXXXXXXXXXXXXXXXXXXX |
| 3727 | -y YYYYYYYYYYYYYYYYYYYYYYYYY |
| 3728 | -z ZZZZZZZZZZZZZZZZZZZZZZZZZ |
| 3729 | ''' |
| 3730 | version = '' |
| 3731 | |
| 3732 | |
| 3733 | class TestHelpUsagePositionalsWrap(HelpTestCase): |
| 3734 | """Test usage messages where the positionals wrap""" |
| 3735 | |
| 3736 | parser_signature = Sig(prog='PROG') |
| 3737 | argument_signatures = [ |
| 3738 | Sig('-x'), |
| 3739 | Sig('-y'), |
| 3740 | Sig('-z'), |
| 3741 | Sig('a' * 25), |
| 3742 | Sig('b' * 25), |
| 3743 | Sig('c' * 25), |
| 3744 | ] |
| 3745 | argument_group_signatures = [] |
| 3746 | usage = '''\ |
| 3747 | usage: PROG [-h] [-x X] [-y Y] [-z Z] |
| 3748 | aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb |
| 3749 | ccccccccccccccccccccccccc |
| 3750 | ''' |
| 3751 | help = usage + '''\ |
| 3752 | |
| 3753 | positional arguments: |
| 3754 | aaaaaaaaaaaaaaaaaaaaaaaaa |
| 3755 | bbbbbbbbbbbbbbbbbbbbbbbbb |
| 3756 | ccccccccccccccccccccccccc |
| 3757 | |
| 3758 | optional arguments: |
| 3759 | -h, --help show this help message and exit |
| 3760 | -x X |
| 3761 | -y Y |
| 3762 | -z Z |
| 3763 | ''' |
| 3764 | version = '' |
| 3765 | |
| 3766 | |
| 3767 | class TestHelpUsageOptionalsPositionalsWrap(HelpTestCase): |
| 3768 | """Test usage messages where the optionals and positionals wrap""" |
| 3769 | |
| 3770 | parser_signature = Sig(prog='PROG') |
| 3771 | argument_signatures = [ |
| 3772 | Sig('-x', metavar='X' * 25), |
| 3773 | Sig('-y', metavar='Y' * 25), |
| 3774 | Sig('-z', metavar='Z' * 25), |
| 3775 | Sig('a' * 25), |
| 3776 | Sig('b' * 25), |
| 3777 | Sig('c' * 25), |
| 3778 | ] |
| 3779 | argument_group_signatures = [] |
| 3780 | usage = '''\ |
| 3781 | usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \ |
| 3782 | [-y YYYYYYYYYYYYYYYYYYYYYYYYY] |
| 3783 | [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ] |
| 3784 | aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb |
| 3785 | ccccccccccccccccccccccccc |
| 3786 | ''' |
| 3787 | help = usage + '''\ |
| 3788 | |
| 3789 | positional arguments: |
| 3790 | aaaaaaaaaaaaaaaaaaaaaaaaa |
| 3791 | bbbbbbbbbbbbbbbbbbbbbbbbb |
| 3792 | ccccccccccccccccccccccccc |
| 3793 | |
| 3794 | optional arguments: |
| 3795 | -h, --help show this help message and exit |
| 3796 | -x XXXXXXXXXXXXXXXXXXXXXXXXX |
| 3797 | -y YYYYYYYYYYYYYYYYYYYYYYYYY |
| 3798 | -z ZZZZZZZZZZZZZZZZZZZZZZZZZ |
| 3799 | ''' |
| 3800 | version = '' |
| 3801 | |
| 3802 | |
| 3803 | class TestHelpUsageOptionalsOnlyWrap(HelpTestCase): |
| 3804 | """Test usage messages where there are only optionals and they wrap""" |
| 3805 | |
| 3806 | parser_signature = Sig(prog='PROG') |
| 3807 | argument_signatures = [ |
| 3808 | Sig('-x', metavar='X' * 25), |
| 3809 | Sig('-y', metavar='Y' * 25), |
| 3810 | Sig('-z', metavar='Z' * 25), |
| 3811 | ] |
| 3812 | argument_group_signatures = [] |
| 3813 | usage = '''\ |
| 3814 | usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \ |
| 3815 | [-y YYYYYYYYYYYYYYYYYYYYYYYYY] |
| 3816 | [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ] |
| 3817 | ''' |
| 3818 | help = usage + '''\ |
| 3819 | |
| 3820 | optional arguments: |
| 3821 | -h, --help show this help message and exit |
| 3822 | -x XXXXXXXXXXXXXXXXXXXXXXXXX |
| 3823 | -y YYYYYYYYYYYYYYYYYYYYYYYYY |
| 3824 | -z ZZZZZZZZZZZZZZZZZZZZZZZZZ |
| 3825 | ''' |
| 3826 | version = '' |
| 3827 | |
| 3828 | |
| 3829 | class TestHelpUsagePositionalsOnlyWrap(HelpTestCase): |
| 3830 | """Test usage messages where there are only positionals and they wrap""" |
| 3831 | |
| 3832 | parser_signature = Sig(prog='PROG', add_help=False) |
| 3833 | argument_signatures = [ |
| 3834 | Sig('a' * 25), |
| 3835 | Sig('b' * 25), |
| 3836 | Sig('c' * 25), |
| 3837 | ] |
| 3838 | argument_group_signatures = [] |
| 3839 | usage = '''\ |
| 3840 | usage: PROG aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb |
| 3841 | ccccccccccccccccccccccccc |
| 3842 | ''' |
| 3843 | help = usage + '''\ |
| 3844 | |
| 3845 | positional arguments: |
| 3846 | aaaaaaaaaaaaaaaaaaaaaaaaa |
| 3847 | bbbbbbbbbbbbbbbbbbbbbbbbb |
| 3848 | ccccccccccccccccccccccccc |
| 3849 | ''' |
| 3850 | version = '' |
| 3851 | |
| 3852 | |
| 3853 | class TestHelpVariableExpansion(HelpTestCase): |
| 3854 | """Test that variables are expanded properly in help messages""" |
| 3855 | |
| 3856 | parser_signature = Sig(prog='PROG') |
| 3857 | argument_signatures = [ |
| 3858 | Sig('-x', type=int, |
| 3859 | help='x %(prog)s %(default)s %(type)s %%'), |
| 3860 | Sig('-y', action='store_const', default=42, const='XXX', |
| 3861 | help='y %(prog)s %(default)s %(const)s'), |
| 3862 | Sig('--foo', choices='abc', |
| 3863 | help='foo %(prog)s %(default)s %(choices)s'), |
| 3864 | Sig('--bar', default='baz', choices=[1, 2], metavar='BBB', |
| 3865 | help='bar %(prog)s %(default)s %(dest)s'), |
| 3866 | Sig('spam', help='spam %(prog)s %(default)s'), |
| 3867 | Sig('badger', default=0.5, help='badger %(prog)s %(default)s'), |
| 3868 | ] |
| 3869 | argument_group_signatures = [ |
| 3870 | (Sig('group'), [ |
| 3871 | Sig('-a', help='a %(prog)s %(default)s'), |
| 3872 | Sig('-b', default=-1, help='b %(prog)s %(default)s'), |
| 3873 | ]) |
| 3874 | ] |
| 3875 | usage = ('''\ |
| 3876 | usage: PROG [-h] [-x X] [-y] [--foo {a,b,c}] [--bar BBB] [-a A] [-b B] |
| 3877 | spam badger |
| 3878 | ''') |
| 3879 | help = usage + '''\ |
| 3880 | |
| 3881 | positional arguments: |
| 3882 | spam spam PROG None |
| 3883 | badger badger PROG 0.5 |
| 3884 | |
| 3885 | optional arguments: |
| 3886 | -h, --help show this help message and exit |
| 3887 | -x X x PROG None int % |
| 3888 | -y y PROG 42 XXX |
| 3889 | --foo {a,b,c} foo PROG None a, b, c |
| 3890 | --bar BBB bar PROG baz bar |
| 3891 | |
| 3892 | group: |
| 3893 | -a A a PROG None |
| 3894 | -b B b PROG -1 |
| 3895 | ''' |
| 3896 | version = '' |
| 3897 | |
| 3898 | |
| 3899 | class TestHelpVariableExpansionUsageSupplied(HelpTestCase): |
| 3900 | """Test that variables are expanded properly when usage= is present""" |
| 3901 | |
| 3902 | parser_signature = Sig(prog='PROG', usage='%(prog)s FOO') |
| 3903 | argument_signatures = [] |
| 3904 | argument_group_signatures = [] |
| 3905 | usage = ('''\ |
| 3906 | usage: PROG FOO |
| 3907 | ''') |
| 3908 | help = usage + '''\ |
| 3909 | |
| 3910 | optional arguments: |
| 3911 | -h, --help show this help message and exit |
| 3912 | ''' |
| 3913 | version = '' |
| 3914 | |
| 3915 | |
| 3916 | class TestHelpVariableExpansionNoArguments(HelpTestCase): |
| 3917 | """Test that variables are expanded properly with no arguments""" |
| 3918 | |
| 3919 | parser_signature = Sig(prog='PROG', add_help=False) |
| 3920 | argument_signatures = [] |
| 3921 | argument_group_signatures = [] |
| 3922 | usage = ('''\ |
| 3923 | usage: PROG |
| 3924 | ''') |
| 3925 | help = usage |
| 3926 | version = '' |
| 3927 | |
| 3928 | |
| 3929 | class TestHelpSuppressUsage(HelpTestCase): |
| 3930 | """Test that items can be suppressed in usage messages""" |
| 3931 | |
| 3932 | parser_signature = Sig(prog='PROG', usage=argparse.SUPPRESS) |
| 3933 | argument_signatures = [ |
| 3934 | Sig('--foo', help='foo help'), |
| 3935 | Sig('spam', help='spam help'), |
| 3936 | ] |
| 3937 | argument_group_signatures = [] |
| 3938 | help = '''\ |
| 3939 | positional arguments: |
| 3940 | spam spam help |
| 3941 | |
| 3942 | optional arguments: |
| 3943 | -h, --help show this help message and exit |
| 3944 | --foo FOO foo help |
| 3945 | ''' |
| 3946 | usage = '' |
| 3947 | version = '' |
| 3948 | |
| 3949 | |
| 3950 | class TestHelpSuppressOptional(HelpTestCase): |
| 3951 | """Test that optional arguments can be suppressed in help messages""" |
| 3952 | |
| 3953 | parser_signature = Sig(prog='PROG', add_help=False) |
| 3954 | argument_signatures = [ |
| 3955 | Sig('--foo', help=argparse.SUPPRESS), |
| 3956 | Sig('spam', help='spam help'), |
| 3957 | ] |
| 3958 | argument_group_signatures = [] |
| 3959 | usage = '''\ |
| 3960 | usage: PROG spam |
| 3961 | ''' |
| 3962 | help = usage + '''\ |
| 3963 | |
| 3964 | positional arguments: |
| 3965 | spam spam help |
| 3966 | ''' |
| 3967 | version = '' |
| 3968 | |
| 3969 | |
| 3970 | class TestHelpSuppressOptionalGroup(HelpTestCase): |
| 3971 | """Test that optional groups can be suppressed in help messages""" |
| 3972 | |
| 3973 | parser_signature = Sig(prog='PROG') |
| 3974 | argument_signatures = [ |
| 3975 | Sig('--foo', help='foo help'), |
| 3976 | Sig('spam', help='spam help'), |
| 3977 | ] |
| 3978 | argument_group_signatures = [ |
| 3979 | (Sig('group'), [Sig('--bar', help=argparse.SUPPRESS)]), |
| 3980 | ] |
| 3981 | usage = '''\ |
| 3982 | usage: PROG [-h] [--foo FOO] spam |
| 3983 | ''' |
| 3984 | help = usage + '''\ |
| 3985 | |
| 3986 | positional arguments: |
| 3987 | spam spam help |
| 3988 | |
| 3989 | optional arguments: |
| 3990 | -h, --help show this help message and exit |
| 3991 | --foo FOO foo help |
| 3992 | ''' |
| 3993 | version = '' |
| 3994 | |
| 3995 | |
| 3996 | class TestHelpSuppressPositional(HelpTestCase): |
| 3997 | """Test that positional arguments can be suppressed in help messages""" |
| 3998 | |
| 3999 | parser_signature = Sig(prog='PROG') |
| 4000 | argument_signatures = [ |
| 4001 | Sig('--foo', help='foo help'), |
| 4002 | Sig('spam', help=argparse.SUPPRESS), |
| 4003 | ] |
| 4004 | argument_group_signatures = [] |
| 4005 | usage = '''\ |
| 4006 | usage: PROG [-h] [--foo FOO] |
| 4007 | ''' |
| 4008 | help = usage + '''\ |
| 4009 | |
| 4010 | optional arguments: |
| 4011 | -h, --help show this help message and exit |
| 4012 | --foo FOO foo help |
| 4013 | ''' |
| 4014 | version = '' |
| 4015 | |
| 4016 | |
| 4017 | class TestHelpRequiredOptional(HelpTestCase): |
| 4018 | """Test that required options don't look optional""" |
| 4019 | |
| 4020 | parser_signature = Sig(prog='PROG') |
| 4021 | argument_signatures = [ |
| 4022 | Sig('--foo', required=True, help='foo help'), |
| 4023 | ] |
| 4024 | argument_group_signatures = [] |
| 4025 | usage = '''\ |
| 4026 | usage: PROG [-h] --foo FOO |
| 4027 | ''' |
| 4028 | help = usage + '''\ |
| 4029 | |
| 4030 | optional arguments: |
| 4031 | -h, --help show this help message and exit |
| 4032 | --foo FOO foo help |
| 4033 | ''' |
| 4034 | version = '' |
| 4035 | |
| 4036 | |
| 4037 | class TestHelpAlternatePrefixChars(HelpTestCase): |
| 4038 | """Test that options display with different prefix characters""" |
| 4039 | |
| 4040 | parser_signature = Sig(prog='PROG', prefix_chars='^;', add_help=False) |
| 4041 | argument_signatures = [ |
| 4042 | Sig('^^foo', action='store_true', help='foo help'), |
| 4043 | Sig(';b', ';;bar', help='bar help'), |
| 4044 | ] |
| 4045 | argument_group_signatures = [] |
| 4046 | usage = '''\ |
| 4047 | usage: PROG [^^foo] [;b BAR] |
| 4048 | ''' |
| 4049 | help = usage + '''\ |
| 4050 | |
| 4051 | optional arguments: |
| 4052 | ^^foo foo help |
| 4053 | ;b BAR, ;;bar BAR bar help |
| 4054 | ''' |
| 4055 | version = '' |
| 4056 | |
| 4057 | |
| 4058 | class TestHelpNoHelpOptional(HelpTestCase): |
| 4059 | """Test that the --help argument can be suppressed help messages""" |
| 4060 | |
| 4061 | parser_signature = Sig(prog='PROG', add_help=False) |
| 4062 | argument_signatures = [ |
| 4063 | Sig('--foo', help='foo help'), |
| 4064 | Sig('spam', help='spam help'), |
| 4065 | ] |
| 4066 | argument_group_signatures = [] |
| 4067 | usage = '''\ |
| 4068 | usage: PROG [--foo FOO] spam |
| 4069 | ''' |
| 4070 | help = usage + '''\ |
| 4071 | |
| 4072 | positional arguments: |
| 4073 | spam spam help |
| 4074 | |
| 4075 | optional arguments: |
| 4076 | --foo FOO foo help |
| 4077 | ''' |
| 4078 | version = '' |
| 4079 | |
| 4080 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4081 | class TestHelpNone(HelpTestCase): |
| 4082 | """Test that no errors occur if no help is specified""" |
| 4083 | |
| 4084 | parser_signature = Sig(prog='PROG') |
| 4085 | argument_signatures = [ |
| 4086 | Sig('--foo'), |
| 4087 | Sig('spam'), |
| 4088 | ] |
| 4089 | argument_group_signatures = [] |
| 4090 | usage = '''\ |
| 4091 | usage: PROG [-h] [--foo FOO] spam |
| 4092 | ''' |
| 4093 | help = usage + '''\ |
| 4094 | |
| 4095 | positional arguments: |
| 4096 | spam |
| 4097 | |
| 4098 | optional arguments: |
| 4099 | -h, --help show this help message and exit |
| 4100 | --foo FOO |
| 4101 | ''' |
| 4102 | version = '' |
| 4103 | |
| 4104 | |
| 4105 | class TestHelpTupleMetavar(HelpTestCase): |
| 4106 | """Test specifying metavar as a tuple""" |
| 4107 | |
| 4108 | parser_signature = Sig(prog='PROG') |
| 4109 | argument_signatures = [ |
| 4110 | Sig('-w', help='w', nargs='+', metavar=('W1', 'W2')), |
| 4111 | Sig('-x', help='x', nargs='*', metavar=('X1', 'X2')), |
| 4112 | Sig('-y', help='y', nargs=3, metavar=('Y1', 'Y2', 'Y3')), |
| 4113 | Sig('-z', help='z', nargs='?', metavar=('Z1', )), |
| 4114 | ] |
| 4115 | argument_group_signatures = [] |
| 4116 | usage = '''\ |
| 4117 | usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] \ |
| 4118 | [-z [Z1]] |
| 4119 | ''' |
| 4120 | help = usage + '''\ |
| 4121 | |
| 4122 | optional arguments: |
| 4123 | -h, --help show this help message and exit |
| 4124 | -w W1 [W2 ...] w |
| 4125 | -x [X1 [X2 ...]] x |
| 4126 | -y Y1 Y2 Y3 y |
| 4127 | -z [Z1] z |
| 4128 | ''' |
| 4129 | version = '' |
| 4130 | |
| 4131 | |
| 4132 | class TestHelpRawText(HelpTestCase): |
| 4133 | """Test the RawTextHelpFormatter""" |
| 4134 | |
| 4135 | parser_signature = Sig( |
| 4136 | prog='PROG', formatter_class=argparse.RawTextHelpFormatter, |
| 4137 | description='Keep the formatting\n' |
| 4138 | ' exactly as it is written\n' |
| 4139 | '\n' |
| 4140 | 'here\n') |
| 4141 | |
| 4142 | argument_signatures = [ |
| 4143 | Sig('--foo', help=' foo help should also\n' |
| 4144 | 'appear as given here'), |
| 4145 | Sig('spam', help='spam help'), |
| 4146 | ] |
| 4147 | argument_group_signatures = [ |
| 4148 | (Sig('title', description=' This text\n' |
| 4149 | ' should be indented\n' |
| 4150 | ' exactly like it is here\n'), |
| 4151 | [Sig('--bar', help='bar help')]), |
| 4152 | ] |
| 4153 | usage = '''\ |
| 4154 | usage: PROG [-h] [--foo FOO] [--bar BAR] spam |
| 4155 | ''' |
| 4156 | help = usage + '''\ |
| 4157 | |
| 4158 | Keep the formatting |
| 4159 | exactly as it is written |
| 4160 | |
| 4161 | here |
| 4162 | |
| 4163 | positional arguments: |
| 4164 | spam spam help |
| 4165 | |
| 4166 | optional arguments: |
| 4167 | -h, --help show this help message and exit |
| 4168 | --foo FOO foo help should also |
| 4169 | appear as given here |
| 4170 | |
| 4171 | title: |
| 4172 | This text |
| 4173 | should be indented |
| 4174 | exactly like it is here |
| 4175 | |
| 4176 | --bar BAR bar help |
| 4177 | ''' |
| 4178 | version = '' |
| 4179 | |
| 4180 | |
| 4181 | class TestHelpRawDescription(HelpTestCase): |
| 4182 | """Test the RawTextHelpFormatter""" |
| 4183 | |
| 4184 | parser_signature = Sig( |
| 4185 | prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter, |
| 4186 | description='Keep the formatting\n' |
| 4187 | ' exactly as it is written\n' |
| 4188 | '\n' |
| 4189 | 'here\n') |
| 4190 | |
| 4191 | argument_signatures = [ |
| 4192 | Sig('--foo', help=' foo help should not\n' |
| 4193 | ' retain this odd formatting'), |
| 4194 | Sig('spam', help='spam help'), |
| 4195 | ] |
| 4196 | argument_group_signatures = [ |
| 4197 | (Sig('title', description=' This text\n' |
| 4198 | ' should be indented\n' |
| 4199 | ' exactly like it is here\n'), |
| 4200 | [Sig('--bar', help='bar help')]), |
| 4201 | ] |
| 4202 | usage = '''\ |
| 4203 | usage: PROG [-h] [--foo FOO] [--bar BAR] spam |
| 4204 | ''' |
| 4205 | help = usage + '''\ |
| 4206 | |
| 4207 | Keep the formatting |
| 4208 | exactly as it is written |
| 4209 | |
| 4210 | here |
| 4211 | |
| 4212 | positional arguments: |
| 4213 | spam spam help |
| 4214 | |
| 4215 | optional arguments: |
| 4216 | -h, --help show this help message and exit |
| 4217 | --foo FOO foo help should not retain this odd formatting |
| 4218 | |
| 4219 | title: |
| 4220 | This text |
| 4221 | should be indented |
| 4222 | exactly like it is here |
| 4223 | |
| 4224 | --bar BAR bar help |
| 4225 | ''' |
| 4226 | version = '' |
| 4227 | |
| 4228 | |
| 4229 | class TestHelpArgumentDefaults(HelpTestCase): |
| 4230 | """Test the ArgumentDefaultsHelpFormatter""" |
| 4231 | |
| 4232 | parser_signature = Sig( |
| 4233 | prog='PROG', formatter_class=argparse.ArgumentDefaultsHelpFormatter, |
| 4234 | description='description') |
| 4235 | |
| 4236 | argument_signatures = [ |
| 4237 | Sig('--foo', help='foo help - oh and by the way, %(default)s'), |
| 4238 | Sig('--bar', action='store_true', help='bar help'), |
| 4239 | Sig('spam', help='spam help'), |
| 4240 | Sig('badger', nargs='?', default='wooden', help='badger help'), |
| 4241 | ] |
| 4242 | argument_group_signatures = [ |
| 4243 | (Sig('title', description='description'), |
| 4244 | [Sig('--baz', type=int, default=42, help='baz help')]), |
| 4245 | ] |
| 4246 | usage = '''\ |
| 4247 | usage: PROG [-h] [--foo FOO] [--bar] [--baz BAZ] spam [badger] |
| 4248 | ''' |
| 4249 | help = usage + '''\ |
| 4250 | |
| 4251 | description |
| 4252 | |
| 4253 | positional arguments: |
| 4254 | spam spam help |
| 4255 | badger badger help (default: wooden) |
| 4256 | |
| 4257 | optional arguments: |
| 4258 | -h, --help show this help message and exit |
| 4259 | --foo FOO foo help - oh and by the way, None |
| 4260 | --bar bar help (default: False) |
| 4261 | |
| 4262 | title: |
| 4263 | description |
| 4264 | |
| 4265 | --baz BAZ baz help (default: 42) |
| 4266 | ''' |
| 4267 | version = '' |
| 4268 | |
Steven Bethard | 50fe593 | 2010-05-24 03:47:38 +0000 | [diff] [blame] | 4269 | class TestHelpVersionAction(HelpTestCase): |
| 4270 | """Test the default help for the version action""" |
| 4271 | |
| 4272 | parser_signature = Sig(prog='PROG', description='description') |
| 4273 | argument_signatures = [Sig('-V', '--version', action='version', version='3.6')] |
| 4274 | argument_group_signatures = [] |
| 4275 | usage = '''\ |
| 4276 | usage: PROG [-h] [-V] |
| 4277 | ''' |
| 4278 | help = usage + '''\ |
| 4279 | |
| 4280 | description |
| 4281 | |
| 4282 | optional arguments: |
| 4283 | -h, --help show this help message and exit |
| 4284 | -V, --version show program's version number and exit |
| 4285 | ''' |
| 4286 | version = '' |
| 4287 | |
Berker Peksag | ecb75e2 | 2015-04-10 16:11:12 +0300 | [diff] [blame] | 4288 | |
| 4289 | class TestHelpVersionActionSuppress(HelpTestCase): |
| 4290 | """Test that the --version argument can be suppressed in help messages""" |
| 4291 | |
| 4292 | parser_signature = Sig(prog='PROG') |
| 4293 | argument_signatures = [ |
| 4294 | Sig('-v', '--version', action='version', version='1.0', |
| 4295 | help=argparse.SUPPRESS), |
| 4296 | Sig('--foo', help='foo help'), |
| 4297 | Sig('spam', help='spam help'), |
| 4298 | ] |
| 4299 | argument_group_signatures = [] |
| 4300 | usage = '''\ |
| 4301 | usage: PROG [-h] [--foo FOO] spam |
| 4302 | ''' |
| 4303 | help = usage + '''\ |
| 4304 | |
| 4305 | positional arguments: |
| 4306 | spam spam help |
| 4307 | |
| 4308 | optional arguments: |
| 4309 | -h, --help show this help message and exit |
| 4310 | --foo FOO foo help |
| 4311 | ''' |
| 4312 | |
| 4313 | |
Steven Bethard | 8a6a198 | 2011-03-27 13:53:53 +0200 | [diff] [blame] | 4314 | class TestHelpSubparsersOrdering(HelpTestCase): |
| 4315 | """Test ordering of subcommands in help matches the code""" |
| 4316 | parser_signature = Sig(prog='PROG', |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 4317 | description='display some subcommands') |
| 4318 | argument_signatures = [Sig('-v', '--version', action='version', version='0.1')] |
Steven Bethard | 8a6a198 | 2011-03-27 13:53:53 +0200 | [diff] [blame] | 4319 | |
| 4320 | subparsers_signatures = [Sig(name=name) |
| 4321 | for name in ('a', 'b', 'c', 'd', 'e')] |
| 4322 | |
| 4323 | usage = '''\ |
| 4324 | usage: PROG [-h] [-v] {a,b,c,d,e} ... |
| 4325 | ''' |
| 4326 | |
| 4327 | help = usage + '''\ |
| 4328 | |
| 4329 | display some subcommands |
| 4330 | |
| 4331 | positional arguments: |
| 4332 | {a,b,c,d,e} |
| 4333 | |
| 4334 | optional arguments: |
| 4335 | -h, --help show this help message and exit |
| 4336 | -v, --version show program's version number and exit |
| 4337 | ''' |
| 4338 | |
| 4339 | version = '''\ |
| 4340 | 0.1 |
| 4341 | ''' |
| 4342 | |
| 4343 | class TestHelpSubparsersWithHelpOrdering(HelpTestCase): |
| 4344 | """Test ordering of subcommands in help matches the code""" |
| 4345 | parser_signature = Sig(prog='PROG', |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 4346 | description='display some subcommands') |
| 4347 | argument_signatures = [Sig('-v', '--version', action='version', version='0.1')] |
Steven Bethard | 8a6a198 | 2011-03-27 13:53:53 +0200 | [diff] [blame] | 4348 | |
| 4349 | subcommand_data = (('a', 'a subcommand help'), |
| 4350 | ('b', 'b subcommand help'), |
| 4351 | ('c', 'c subcommand help'), |
| 4352 | ('d', 'd subcommand help'), |
| 4353 | ('e', 'e subcommand help'), |
| 4354 | ) |
| 4355 | |
| 4356 | subparsers_signatures = [Sig(name=name, help=help) |
| 4357 | for name, help in subcommand_data] |
| 4358 | |
| 4359 | usage = '''\ |
| 4360 | usage: PROG [-h] [-v] {a,b,c,d,e} ... |
| 4361 | ''' |
| 4362 | |
| 4363 | help = usage + '''\ |
| 4364 | |
| 4365 | display some subcommands |
| 4366 | |
| 4367 | positional arguments: |
| 4368 | {a,b,c,d,e} |
| 4369 | a a subcommand help |
| 4370 | b b subcommand help |
| 4371 | c c subcommand help |
| 4372 | d d subcommand help |
| 4373 | e e subcommand help |
| 4374 | |
| 4375 | optional arguments: |
| 4376 | -h, --help show this help message and exit |
| 4377 | -v, --version show program's version number and exit |
| 4378 | ''' |
| 4379 | |
| 4380 | version = '''\ |
| 4381 | 0.1 |
| 4382 | ''' |
| 4383 | |
| 4384 | |
Steven Bethard | 0331e90 | 2011-03-26 14:48:04 +0100 | [diff] [blame] | 4385 | |
| 4386 | class TestHelpMetavarTypeFormatter(HelpTestCase): |
Steven Bethard | 0331e90 | 2011-03-26 14:48:04 +0100 | [diff] [blame] | 4387 | |
| 4388 | def custom_type(string): |
| 4389 | return string |
| 4390 | |
| 4391 | parser_signature = Sig(prog='PROG', description='description', |
| 4392 | formatter_class=argparse.MetavarTypeHelpFormatter) |
| 4393 | argument_signatures = [Sig('a', type=int), |
| 4394 | Sig('-b', type=custom_type), |
| 4395 | Sig('-c', type=float, metavar='SOME FLOAT')] |
| 4396 | argument_group_signatures = [] |
| 4397 | usage = '''\ |
| 4398 | usage: PROG [-h] [-b custom_type] [-c SOME FLOAT] int |
| 4399 | ''' |
| 4400 | help = usage + '''\ |
| 4401 | |
| 4402 | description |
| 4403 | |
| 4404 | positional arguments: |
| 4405 | int |
| 4406 | |
| 4407 | optional arguments: |
| 4408 | -h, --help show this help message and exit |
| 4409 | -b custom_type |
| 4410 | -c SOME FLOAT |
| 4411 | ''' |
| 4412 | version = '' |
| 4413 | |
| 4414 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4415 | # ===================================== |
| 4416 | # Optional/Positional constructor tests |
| 4417 | # ===================================== |
| 4418 | |
| 4419 | class TestInvalidArgumentConstructors(TestCase): |
| 4420 | """Test a bunch of invalid Argument constructors""" |
| 4421 | |
| 4422 | def assertTypeError(self, *args, **kwargs): |
| 4423 | parser = argparse.ArgumentParser() |
| 4424 | self.assertRaises(TypeError, parser.add_argument, |
| 4425 | *args, **kwargs) |
| 4426 | |
| 4427 | def assertValueError(self, *args, **kwargs): |
| 4428 | parser = argparse.ArgumentParser() |
| 4429 | self.assertRaises(ValueError, parser.add_argument, |
| 4430 | *args, **kwargs) |
| 4431 | |
| 4432 | def test_invalid_keyword_arguments(self): |
| 4433 | self.assertTypeError('-x', bar=None) |
| 4434 | self.assertTypeError('-y', callback='foo') |
| 4435 | self.assertTypeError('-y', callback_args=()) |
| 4436 | self.assertTypeError('-y', callback_kwargs={}) |
| 4437 | |
| 4438 | def test_missing_destination(self): |
| 4439 | self.assertTypeError() |
| 4440 | for action in ['append', 'store']: |
| 4441 | self.assertTypeError(action=action) |
| 4442 | |
| 4443 | def test_invalid_option_strings(self): |
| 4444 | self.assertValueError('--') |
| 4445 | self.assertValueError('---') |
| 4446 | |
| 4447 | def test_invalid_type(self): |
| 4448 | self.assertValueError('--foo', type='int') |
Steven Bethard | 7cb20a8 | 2011-04-04 01:53:02 +0200 | [diff] [blame] | 4449 | self.assertValueError('--foo', type=(int, float)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4450 | |
| 4451 | def test_invalid_action(self): |
| 4452 | self.assertValueError('-x', action='foo') |
| 4453 | self.assertValueError('foo', action='baz') |
Steven Bethard | 7cb20a8 | 2011-04-04 01:53:02 +0200 | [diff] [blame] | 4454 | self.assertValueError('--foo', action=('store', 'append')) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4455 | parser = argparse.ArgumentParser() |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 4456 | with self.assertRaises(ValueError) as cm: |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4457 | parser.add_argument("--foo", action="store-true") |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 4458 | self.assertIn('unknown action', str(cm.exception)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4459 | |
| 4460 | def test_multiple_dest(self): |
| 4461 | parser = argparse.ArgumentParser() |
| 4462 | parser.add_argument(dest='foo') |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 4463 | with self.assertRaises(ValueError) as cm: |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4464 | parser.add_argument('bar', dest='baz') |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 4465 | self.assertIn('dest supplied twice for positional argument', |
| 4466 | str(cm.exception)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4467 | |
| 4468 | def test_no_argument_actions(self): |
| 4469 | for action in ['store_const', 'store_true', 'store_false', |
| 4470 | 'append_const', 'count']: |
| 4471 | for attrs in [dict(type=int), dict(nargs='+'), |
| 4472 | dict(choices='ab')]: |
| 4473 | self.assertTypeError('-x', action=action, **attrs) |
| 4474 | |
| 4475 | def test_no_argument_no_const_actions(self): |
| 4476 | # options with zero arguments |
| 4477 | for action in ['store_true', 'store_false', 'count']: |
| 4478 | |
| 4479 | # const is always disallowed |
| 4480 | self.assertTypeError('-x', const='foo', action=action) |
| 4481 | |
| 4482 | # nargs is always disallowed |
| 4483 | self.assertTypeError('-x', nargs='*', action=action) |
| 4484 | |
| 4485 | def test_more_than_one_argument_actions(self): |
| 4486 | for action in ['store', 'append']: |
| 4487 | |
| 4488 | # nargs=0 is disallowed |
| 4489 | self.assertValueError('-x', nargs=0, action=action) |
| 4490 | self.assertValueError('spam', nargs=0, action=action) |
| 4491 | |
| 4492 | # const is disallowed with non-optional arguments |
| 4493 | for nargs in [1, '*', '+']: |
| 4494 | self.assertValueError('-x', const='foo', |
| 4495 | nargs=nargs, action=action) |
| 4496 | self.assertValueError('spam', const='foo', |
| 4497 | nargs=nargs, action=action) |
| 4498 | |
| 4499 | def test_required_const_actions(self): |
| 4500 | for action in ['store_const', 'append_const']: |
| 4501 | |
| 4502 | # nargs is always disallowed |
| 4503 | self.assertTypeError('-x', nargs='+', action=action) |
| 4504 | |
| 4505 | def test_parsers_action_missing_params(self): |
| 4506 | self.assertTypeError('command', action='parsers') |
| 4507 | self.assertTypeError('command', action='parsers', prog='PROG') |
| 4508 | self.assertTypeError('command', action='parsers', |
| 4509 | parser_class=argparse.ArgumentParser) |
| 4510 | |
| 4511 | def test_required_positional(self): |
| 4512 | self.assertTypeError('foo', required=True) |
| 4513 | |
| 4514 | def test_user_defined_action(self): |
| 4515 | |
| 4516 | class Success(Exception): |
| 4517 | pass |
| 4518 | |
| 4519 | class Action(object): |
| 4520 | |
| 4521 | def __init__(self, |
| 4522 | option_strings, |
| 4523 | dest, |
| 4524 | const, |
| 4525 | default, |
| 4526 | required=False): |
| 4527 | if dest == 'spam': |
| 4528 | if const is Success: |
| 4529 | if default is Success: |
| 4530 | raise Success() |
| 4531 | |
| 4532 | def __call__(self, *args, **kwargs): |
| 4533 | pass |
| 4534 | |
| 4535 | parser = argparse.ArgumentParser() |
| 4536 | self.assertRaises(Success, parser.add_argument, '--spam', |
| 4537 | action=Action, default=Success, const=Success) |
| 4538 | self.assertRaises(Success, parser.add_argument, 'spam', |
| 4539 | action=Action, default=Success, const=Success) |
| 4540 | |
| 4541 | # ================================ |
| 4542 | # Actions returned by add_argument |
| 4543 | # ================================ |
| 4544 | |
| 4545 | class TestActionsReturned(TestCase): |
| 4546 | |
| 4547 | def test_dest(self): |
| 4548 | parser = argparse.ArgumentParser() |
| 4549 | action = parser.add_argument('--foo') |
| 4550 | self.assertEqual(action.dest, 'foo') |
| 4551 | action = parser.add_argument('-b', '--bar') |
| 4552 | self.assertEqual(action.dest, 'bar') |
| 4553 | action = parser.add_argument('-x', '-y') |
| 4554 | self.assertEqual(action.dest, 'x') |
| 4555 | |
| 4556 | def test_misc(self): |
| 4557 | parser = argparse.ArgumentParser() |
| 4558 | action = parser.add_argument('--foo', nargs='?', const=42, |
| 4559 | default=84, type=int, choices=[1, 2], |
| 4560 | help='FOO', metavar='BAR', dest='baz') |
| 4561 | self.assertEqual(action.nargs, '?') |
| 4562 | self.assertEqual(action.const, 42) |
| 4563 | self.assertEqual(action.default, 84) |
| 4564 | self.assertEqual(action.type, int) |
| 4565 | self.assertEqual(action.choices, [1, 2]) |
| 4566 | self.assertEqual(action.help, 'FOO') |
| 4567 | self.assertEqual(action.metavar, 'BAR') |
| 4568 | self.assertEqual(action.dest, 'baz') |
| 4569 | |
| 4570 | |
| 4571 | # ================================ |
| 4572 | # Argument conflict handling tests |
| 4573 | # ================================ |
| 4574 | |
| 4575 | class TestConflictHandling(TestCase): |
| 4576 | |
| 4577 | def test_bad_type(self): |
| 4578 | self.assertRaises(ValueError, argparse.ArgumentParser, |
| 4579 | conflict_handler='foo') |
| 4580 | |
| 4581 | def test_conflict_error(self): |
| 4582 | parser = argparse.ArgumentParser() |
| 4583 | parser.add_argument('-x') |
| 4584 | self.assertRaises(argparse.ArgumentError, |
| 4585 | parser.add_argument, '-x') |
| 4586 | parser.add_argument('--spam') |
| 4587 | self.assertRaises(argparse.ArgumentError, |
| 4588 | parser.add_argument, '--spam') |
| 4589 | |
| 4590 | def test_resolve_error(self): |
| 4591 | get_parser = argparse.ArgumentParser |
| 4592 | parser = get_parser(prog='PROG', conflict_handler='resolve') |
| 4593 | |
| 4594 | parser.add_argument('-x', help='OLD X') |
| 4595 | parser.add_argument('-x', help='NEW X') |
| 4596 | self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
| 4597 | usage: PROG [-h] [-x X] |
| 4598 | |
| 4599 | optional arguments: |
| 4600 | -h, --help show this help message and exit |
| 4601 | -x X NEW X |
| 4602 | ''')) |
| 4603 | |
| 4604 | parser.add_argument('--spam', metavar='OLD_SPAM') |
| 4605 | parser.add_argument('--spam', metavar='NEW_SPAM') |
| 4606 | self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
| 4607 | usage: PROG [-h] [-x X] [--spam NEW_SPAM] |
| 4608 | |
| 4609 | optional arguments: |
| 4610 | -h, --help show this help message and exit |
| 4611 | -x X NEW X |
| 4612 | --spam NEW_SPAM |
| 4613 | ''')) |
| 4614 | |
| 4615 | |
| 4616 | # ============================= |
| 4617 | # Help and Version option tests |
| 4618 | # ============================= |
| 4619 | |
| 4620 | class TestOptionalsHelpVersionActions(TestCase): |
| 4621 | """Test the help and version actions""" |
| 4622 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4623 | def assertPrintHelpExit(self, parser, args_str): |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 4624 | with self.assertRaises(ArgumentParserError) as cm: |
| 4625 | parser.parse_args(args_str.split()) |
| 4626 | self.assertEqual(parser.format_help(), cm.exception.stdout) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4627 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4628 | def assertArgumentParserError(self, parser, *args): |
| 4629 | self.assertRaises(ArgumentParserError, parser.parse_args, args) |
| 4630 | |
| 4631 | def test_version(self): |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 4632 | parser = ErrorRaisingArgumentParser() |
| 4633 | parser.add_argument('-v', '--version', action='version', version='1.0') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4634 | self.assertPrintHelpExit(parser, '-h') |
| 4635 | self.assertPrintHelpExit(parser, '--help') |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 4636 | self.assertRaises(AttributeError, getattr, parser, 'format_version') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4637 | |
| 4638 | def test_version_format(self): |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 4639 | parser = ErrorRaisingArgumentParser(prog='PPP') |
| 4640 | parser.add_argument('-v', '--version', action='version', version='%(prog)s 3.5') |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 4641 | with self.assertRaises(ArgumentParserError) as cm: |
| 4642 | parser.parse_args(['-v']) |
| 4643 | self.assertEqual('PPP 3.5\n', cm.exception.stdout) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4644 | |
| 4645 | def test_version_no_help(self): |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 4646 | parser = ErrorRaisingArgumentParser(add_help=False) |
| 4647 | parser.add_argument('-v', '--version', action='version', version='1.0') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4648 | self.assertArgumentParserError(parser, '-h') |
| 4649 | self.assertArgumentParserError(parser, '--help') |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 4650 | self.assertRaises(AttributeError, getattr, parser, 'format_version') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4651 | |
| 4652 | def test_version_action(self): |
| 4653 | parser = ErrorRaisingArgumentParser(prog='XXX') |
| 4654 | parser.add_argument('-V', action='version', version='%(prog)s 3.7') |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 4655 | with self.assertRaises(ArgumentParserError) as cm: |
| 4656 | parser.parse_args(['-V']) |
| 4657 | self.assertEqual('XXX 3.7\n', cm.exception.stdout) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4658 | |
| 4659 | def test_no_help(self): |
| 4660 | parser = ErrorRaisingArgumentParser(add_help=False) |
| 4661 | self.assertArgumentParserError(parser, '-h') |
| 4662 | self.assertArgumentParserError(parser, '--help') |
| 4663 | self.assertArgumentParserError(parser, '-v') |
| 4664 | self.assertArgumentParserError(parser, '--version') |
| 4665 | |
| 4666 | def test_alternate_help_version(self): |
| 4667 | parser = ErrorRaisingArgumentParser() |
| 4668 | parser.add_argument('-x', action='help') |
| 4669 | parser.add_argument('-y', action='version') |
| 4670 | self.assertPrintHelpExit(parser, '-x') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4671 | self.assertArgumentParserError(parser, '-v') |
| 4672 | self.assertArgumentParserError(parser, '--version') |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 4673 | self.assertRaises(AttributeError, getattr, parser, 'format_version') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4674 | |
| 4675 | def test_help_version_extra_arguments(self): |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 4676 | parser = ErrorRaisingArgumentParser() |
| 4677 | parser.add_argument('--version', action='version', version='1.0') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4678 | parser.add_argument('-x', action='store_true') |
| 4679 | parser.add_argument('y') |
| 4680 | |
| 4681 | # try all combinations of valid prefixes and suffixes |
| 4682 | valid_prefixes = ['', '-x', 'foo', '-x bar', 'baz -x'] |
| 4683 | valid_suffixes = valid_prefixes + ['--bad-option', 'foo bar baz'] |
| 4684 | for prefix in valid_prefixes: |
| 4685 | for suffix in valid_suffixes: |
| 4686 | format = '%s %%s %s' % (prefix, suffix) |
| 4687 | self.assertPrintHelpExit(parser, format % '-h') |
| 4688 | self.assertPrintHelpExit(parser, format % '--help') |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 4689 | self.assertRaises(AttributeError, getattr, parser, 'format_version') |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4690 | |
| 4691 | |
| 4692 | # ====================== |
| 4693 | # str() and repr() tests |
| 4694 | # ====================== |
| 4695 | |
| 4696 | class TestStrings(TestCase): |
| 4697 | """Test str() and repr() on Optionals and Positionals""" |
| 4698 | |
| 4699 | def assertStringEqual(self, obj, result_string): |
| 4700 | for func in [str, repr]: |
| 4701 | self.assertEqual(func(obj), result_string) |
| 4702 | |
| 4703 | def test_optional(self): |
| 4704 | option = argparse.Action( |
| 4705 | option_strings=['--foo', '-a', '-b'], |
| 4706 | dest='b', |
| 4707 | type='int', |
| 4708 | nargs='+', |
| 4709 | default=42, |
| 4710 | choices=[1, 2, 3], |
| 4711 | help='HELP', |
| 4712 | metavar='METAVAR') |
| 4713 | string = ( |
| 4714 | "Action(option_strings=['--foo', '-a', '-b'], dest='b', " |
| 4715 | "nargs='+', const=None, default=42, type='int', " |
| 4716 | "choices=[1, 2, 3], help='HELP', metavar='METAVAR')") |
| 4717 | self.assertStringEqual(option, string) |
| 4718 | |
| 4719 | def test_argument(self): |
| 4720 | argument = argparse.Action( |
| 4721 | option_strings=[], |
| 4722 | dest='x', |
| 4723 | type=float, |
| 4724 | nargs='?', |
| 4725 | default=2.5, |
| 4726 | choices=[0.5, 1.5, 2.5], |
| 4727 | help='H HH H', |
| 4728 | metavar='MV MV MV') |
| 4729 | string = ( |
| 4730 | "Action(option_strings=[], dest='x', nargs='?', " |
| 4731 | "const=None, default=2.5, type=%r, choices=[0.5, 1.5, 2.5], " |
| 4732 | "help='H HH H', metavar='MV MV MV')" % float) |
| 4733 | self.assertStringEqual(argument, string) |
| 4734 | |
| 4735 | def test_namespace(self): |
| 4736 | ns = argparse.Namespace(foo=42, bar='spam') |
Raymond Hettinger | 9681953 | 2020-05-17 18:53:01 -0700 | [diff] [blame] | 4737 | string = "Namespace(foo=42, bar='spam')" |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4738 | self.assertStringEqual(ns, string) |
| 4739 | |
Berker Peksag | 76b1714 | 2015-07-29 23:51:47 +0300 | [diff] [blame] | 4740 | def test_namespace_starkwargs_notidentifier(self): |
| 4741 | ns = argparse.Namespace(**{'"': 'quote'}) |
| 4742 | string = """Namespace(**{'"': 'quote'})""" |
| 4743 | self.assertStringEqual(ns, string) |
| 4744 | |
| 4745 | def test_namespace_kwargs_and_starkwargs_notidentifier(self): |
| 4746 | ns = argparse.Namespace(a=1, **{'"': 'quote'}) |
| 4747 | string = """Namespace(a=1, **{'"': 'quote'})""" |
| 4748 | self.assertStringEqual(ns, string) |
| 4749 | |
| 4750 | def test_namespace_starkwargs_identifier(self): |
| 4751 | ns = argparse.Namespace(**{'valid': True}) |
| 4752 | string = "Namespace(valid=True)" |
| 4753 | self.assertStringEqual(ns, string) |
| 4754 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4755 | def test_parser(self): |
| 4756 | parser = argparse.ArgumentParser(prog='PROG') |
| 4757 | string = ( |
| 4758 | "ArgumentParser(prog='PROG', usage=None, description=None, " |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 4759 | "formatter_class=%r, conflict_handler='error', " |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4760 | "add_help=True)" % argparse.HelpFormatter) |
| 4761 | self.assertStringEqual(parser, string) |
| 4762 | |
| 4763 | # =============== |
| 4764 | # Namespace tests |
| 4765 | # =============== |
| 4766 | |
| 4767 | class TestNamespace(TestCase): |
| 4768 | |
| 4769 | def test_constructor(self): |
| 4770 | ns = argparse.Namespace() |
| 4771 | self.assertRaises(AttributeError, getattr, ns, 'x') |
| 4772 | |
| 4773 | ns = argparse.Namespace(a=42, b='spam') |
| 4774 | self.assertEqual(ns.a, 42) |
| 4775 | self.assertEqual(ns.b, 'spam') |
| 4776 | |
| 4777 | def test_equality(self): |
| 4778 | ns1 = argparse.Namespace(a=1, b=2) |
| 4779 | ns2 = argparse.Namespace(b=2, a=1) |
| 4780 | ns3 = argparse.Namespace(a=1) |
| 4781 | ns4 = argparse.Namespace(b=2) |
| 4782 | |
| 4783 | self.assertEqual(ns1, ns2) |
| 4784 | self.assertNotEqual(ns1, ns3) |
| 4785 | self.assertNotEqual(ns1, ns4) |
| 4786 | self.assertNotEqual(ns2, ns3) |
| 4787 | self.assertNotEqual(ns2, ns4) |
| 4788 | self.assertTrue(ns1 != ns3) |
| 4789 | self.assertTrue(ns1 != ns4) |
| 4790 | self.assertTrue(ns2 != ns3) |
| 4791 | self.assertTrue(ns2 != ns4) |
| 4792 | |
Berker Peksag | c16387b | 2016-09-28 17:21:52 +0300 | [diff] [blame] | 4793 | def test_equality_returns_notimplemented(self): |
Raymond Hettinger | dea46ec | 2014-05-26 00:43:27 -0700 | [diff] [blame] | 4794 | # See issue 21481 |
| 4795 | ns = argparse.Namespace(a=1, b=2) |
| 4796 | self.assertIs(ns.__eq__(None), NotImplemented) |
| 4797 | self.assertIs(ns.__ne__(None), NotImplemented) |
| 4798 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4799 | |
| 4800 | # =================== |
| 4801 | # File encoding tests |
| 4802 | # =================== |
| 4803 | |
| 4804 | class TestEncoding(TestCase): |
| 4805 | |
| 4806 | def _test_module_encoding(self, path): |
| 4807 | path, _ = os.path.splitext(path) |
| 4808 | path += ".py" |
Victor Stinner | 272d888 | 2017-06-16 08:59:01 +0200 | [diff] [blame] | 4809 | with open(path, 'r', encoding='utf-8') as f: |
Antoine Pitrou | b86680e | 2010-10-14 21:15:17 +0000 | [diff] [blame] | 4810 | f.read() |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4811 | |
| 4812 | def test_argparse_module_encoding(self): |
| 4813 | self._test_module_encoding(argparse.__file__) |
| 4814 | |
| 4815 | def test_test_argparse_module_encoding(self): |
| 4816 | self._test_module_encoding(__file__) |
| 4817 | |
| 4818 | # =================== |
| 4819 | # ArgumentError tests |
| 4820 | # =================== |
| 4821 | |
| 4822 | class TestArgumentError(TestCase): |
| 4823 | |
| 4824 | def test_argument_error(self): |
| 4825 | msg = "my error here" |
| 4826 | error = argparse.ArgumentError(None, msg) |
| 4827 | self.assertEqual(str(error), msg) |
| 4828 | |
| 4829 | # ======================= |
| 4830 | # ArgumentTypeError tests |
| 4831 | # ======================= |
| 4832 | |
R. David Murray | 722b5fd | 2010-11-20 03:48:58 +0000 | [diff] [blame] | 4833 | class TestArgumentTypeError(TestCase): |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4834 | |
| 4835 | def test_argument_type_error(self): |
| 4836 | |
| 4837 | def spam(string): |
| 4838 | raise argparse.ArgumentTypeError('spam!') |
| 4839 | |
| 4840 | parser = ErrorRaisingArgumentParser(prog='PROG', add_help=False) |
| 4841 | parser.add_argument('x', type=spam) |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 4842 | with self.assertRaises(ArgumentParserError) as cm: |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4843 | parser.parse_args(['XXX']) |
Berker Peksag | 1c5f56a | 2014-07-06 09:33:20 +0300 | [diff] [blame] | 4844 | self.assertEqual('usage: PROG x\nPROG: error: argument x: spam!\n', |
| 4845 | cm.exception.stderr) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4846 | |
R David Murray | f97c59a | 2011-06-09 12:34:07 -0400 | [diff] [blame] | 4847 | # ========================= |
| 4848 | # MessageContentError tests |
| 4849 | # ========================= |
| 4850 | |
| 4851 | class TestMessageContentError(TestCase): |
| 4852 | |
| 4853 | def test_missing_argument_name_in_message(self): |
| 4854 | parser = ErrorRaisingArgumentParser(prog='PROG', usage='') |
| 4855 | parser.add_argument('req_pos', type=str) |
| 4856 | parser.add_argument('-req_opt', type=int, required=True) |
| 4857 | parser.add_argument('need_one', type=str, nargs='+') |
| 4858 | |
| 4859 | with self.assertRaises(ArgumentParserError) as cm: |
| 4860 | parser.parse_args([]) |
| 4861 | msg = str(cm.exception) |
| 4862 | self.assertRegex(msg, 'req_pos') |
| 4863 | self.assertRegex(msg, 'req_opt') |
| 4864 | self.assertRegex(msg, 'need_one') |
| 4865 | with self.assertRaises(ArgumentParserError) as cm: |
| 4866 | parser.parse_args(['myXargument']) |
| 4867 | msg = str(cm.exception) |
| 4868 | self.assertNotIn(msg, 'req_pos') |
| 4869 | self.assertRegex(msg, 'req_opt') |
| 4870 | self.assertRegex(msg, 'need_one') |
| 4871 | with self.assertRaises(ArgumentParserError) as cm: |
| 4872 | parser.parse_args(['myXargument', '-req_opt=1']) |
| 4873 | msg = str(cm.exception) |
| 4874 | self.assertNotIn(msg, 'req_pos') |
| 4875 | self.assertNotIn(msg, 'req_opt') |
| 4876 | self.assertRegex(msg, 'need_one') |
| 4877 | |
| 4878 | def test_optional_optional_not_in_message(self): |
| 4879 | parser = ErrorRaisingArgumentParser(prog='PROG', usage='') |
| 4880 | parser.add_argument('req_pos', type=str) |
| 4881 | parser.add_argument('--req_opt', type=int, required=True) |
| 4882 | parser.add_argument('--opt_opt', type=bool, nargs='?', |
| 4883 | default=True) |
| 4884 | with self.assertRaises(ArgumentParserError) as cm: |
| 4885 | parser.parse_args([]) |
| 4886 | msg = str(cm.exception) |
| 4887 | self.assertRegex(msg, 'req_pos') |
| 4888 | self.assertRegex(msg, 'req_opt') |
| 4889 | self.assertNotIn(msg, 'opt_opt') |
| 4890 | with self.assertRaises(ArgumentParserError) as cm: |
| 4891 | parser.parse_args(['--req_opt=1']) |
| 4892 | msg = str(cm.exception) |
| 4893 | self.assertRegex(msg, 'req_pos') |
| 4894 | self.assertNotIn(msg, 'req_opt') |
| 4895 | self.assertNotIn(msg, 'opt_opt') |
| 4896 | |
| 4897 | def test_optional_positional_not_in_message(self): |
| 4898 | parser = ErrorRaisingArgumentParser(prog='PROG', usage='') |
| 4899 | parser.add_argument('req_pos') |
| 4900 | parser.add_argument('optional_positional', nargs='?', default='eggs') |
| 4901 | with self.assertRaises(ArgumentParserError) as cm: |
| 4902 | parser.parse_args([]) |
| 4903 | msg = str(cm.exception) |
| 4904 | self.assertRegex(msg, 'req_pos') |
| 4905 | self.assertNotIn(msg, 'optional_positional') |
| 4906 | |
| 4907 | |
R David Murray | 6fb8fb1 | 2012-08-31 22:45:20 -0400 | [diff] [blame] | 4908 | # ================================================ |
| 4909 | # Check that the type function is called only once |
| 4910 | # ================================================ |
| 4911 | |
| 4912 | class TestTypeFunctionCallOnlyOnce(TestCase): |
| 4913 | |
| 4914 | def test_type_function_call_only_once(self): |
| 4915 | def spam(string_to_convert): |
| 4916 | self.assertEqual(string_to_convert, 'spam!') |
| 4917 | return 'foo_converted' |
| 4918 | |
| 4919 | parser = argparse.ArgumentParser() |
| 4920 | parser.add_argument('--foo', type=spam, default='bar') |
| 4921 | args = parser.parse_args('--foo spam!'.split()) |
| 4922 | self.assertEqual(NS(foo='foo_converted'), args) |
| 4923 | |
Barry Warsaw | eaae1b7 | 2012-09-12 14:34:50 -0400 | [diff] [blame] | 4924 | # ================================================================== |
| 4925 | # Check semantics regarding the default argument and type conversion |
| 4926 | # ================================================================== |
R David Murray | 6fb8fb1 | 2012-08-31 22:45:20 -0400 | [diff] [blame] | 4927 | |
Barry Warsaw | eaae1b7 | 2012-09-12 14:34:50 -0400 | [diff] [blame] | 4928 | class TestTypeFunctionCalledOnDefault(TestCase): |
R David Murray | 6fb8fb1 | 2012-08-31 22:45:20 -0400 | [diff] [blame] | 4929 | |
| 4930 | def test_type_function_call_with_non_string_default(self): |
| 4931 | def spam(int_to_convert): |
| 4932 | self.assertEqual(int_to_convert, 0) |
| 4933 | return 'foo_converted' |
| 4934 | |
| 4935 | parser = argparse.ArgumentParser() |
| 4936 | parser.add_argument('--foo', type=spam, default=0) |
| 4937 | args = parser.parse_args([]) |
Barry Warsaw | eaae1b7 | 2012-09-12 14:34:50 -0400 | [diff] [blame] | 4938 | # foo should *not* be converted because its default is not a string. |
| 4939 | self.assertEqual(NS(foo=0), args) |
| 4940 | |
| 4941 | def test_type_function_call_with_string_default(self): |
| 4942 | def spam(int_to_convert): |
| 4943 | return 'foo_converted' |
| 4944 | |
| 4945 | parser = argparse.ArgumentParser() |
| 4946 | parser.add_argument('--foo', type=spam, default='0') |
| 4947 | args = parser.parse_args([]) |
| 4948 | # foo is converted because its default is a string. |
R David Murray | 6fb8fb1 | 2012-08-31 22:45:20 -0400 | [diff] [blame] | 4949 | self.assertEqual(NS(foo='foo_converted'), args) |
| 4950 | |
Barry Warsaw | eaae1b7 | 2012-09-12 14:34:50 -0400 | [diff] [blame] | 4951 | def test_no_double_type_conversion_of_default(self): |
| 4952 | def extend(str_to_convert): |
| 4953 | return str_to_convert + '*' |
| 4954 | |
| 4955 | parser = argparse.ArgumentParser() |
| 4956 | parser.add_argument('--test', type=extend, default='*') |
| 4957 | args = parser.parse_args([]) |
| 4958 | # The test argument will be two stars, one coming from the default |
| 4959 | # value and one coming from the type conversion being called exactly |
| 4960 | # once. |
| 4961 | self.assertEqual(NS(test='**'), args) |
| 4962 | |
Barry Warsaw | 4b2f9e9 | 2012-09-11 22:38:47 -0400 | [diff] [blame] | 4963 | def test_issue_15906(self): |
| 4964 | # Issue #15906: When action='append', type=str, default=[] are |
| 4965 | # providing, the dest value was the string representation "[]" when it |
| 4966 | # should have been an empty list. |
| 4967 | parser = argparse.ArgumentParser() |
| 4968 | parser.add_argument('--test', dest='test', type=str, |
| 4969 | default=[], action='append') |
| 4970 | args = parser.parse_args([]) |
| 4971 | self.assertEqual(args.test, []) |
| 4972 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4973 | # ====================== |
| 4974 | # parse_known_args tests |
| 4975 | # ====================== |
| 4976 | |
| 4977 | class TestParseKnownArgs(TestCase): |
| 4978 | |
R David Murray | b522828 | 2012-09-08 12:08:01 -0400 | [diff] [blame] | 4979 | def test_arguments_tuple(self): |
| 4980 | parser = argparse.ArgumentParser() |
| 4981 | parser.parse_args(()) |
| 4982 | |
| 4983 | def test_arguments_list(self): |
| 4984 | parser = argparse.ArgumentParser() |
| 4985 | parser.parse_args([]) |
| 4986 | |
| 4987 | def test_arguments_tuple_positional(self): |
| 4988 | parser = argparse.ArgumentParser() |
| 4989 | parser.add_argument('x') |
| 4990 | parser.parse_args(('x',)) |
| 4991 | |
| 4992 | def test_arguments_list_positional(self): |
| 4993 | parser = argparse.ArgumentParser() |
| 4994 | parser.add_argument('x') |
| 4995 | parser.parse_args(['x']) |
| 4996 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 4997 | def test_optionals(self): |
| 4998 | parser = argparse.ArgumentParser() |
| 4999 | parser.add_argument('--foo') |
| 5000 | args, extras = parser.parse_known_args('--foo F --bar --baz'.split()) |
| 5001 | self.assertEqual(NS(foo='F'), args) |
| 5002 | self.assertEqual(['--bar', '--baz'], extras) |
| 5003 | |
| 5004 | def test_mixed(self): |
| 5005 | parser = argparse.ArgumentParser() |
| 5006 | parser.add_argument('-v', nargs='?', const=1, type=int) |
| 5007 | parser.add_argument('--spam', action='store_false') |
| 5008 | parser.add_argument('badger') |
| 5009 | |
| 5010 | argv = ["B", "C", "--foo", "-v", "3", "4"] |
| 5011 | args, extras = parser.parse_known_args(argv) |
| 5012 | self.assertEqual(NS(v=3, spam=True, badger="B"), args) |
| 5013 | self.assertEqual(["C", "--foo", "4"], extras) |
| 5014 | |
R. David Murray | 0f6b9d2 | 2017-09-06 20:25:40 -0400 | [diff] [blame] | 5015 | # =========================== |
| 5016 | # parse_intermixed_args tests |
| 5017 | # =========================== |
| 5018 | |
| 5019 | class TestIntermixedArgs(TestCase): |
| 5020 | def test_basic(self): |
| 5021 | # test parsing intermixed optionals and positionals |
| 5022 | parser = argparse.ArgumentParser(prog='PROG') |
| 5023 | parser.add_argument('--foo', dest='foo') |
| 5024 | bar = parser.add_argument('--bar', dest='bar', required=True) |
| 5025 | parser.add_argument('cmd') |
| 5026 | parser.add_argument('rest', nargs='*', type=int) |
| 5027 | argv = 'cmd --foo x 1 --bar y 2 3'.split() |
| 5028 | args = parser.parse_intermixed_args(argv) |
| 5029 | # rest gets [1,2,3] despite the foo and bar strings |
| 5030 | self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args) |
| 5031 | |
| 5032 | args, extras = parser.parse_known_args(argv) |
| 5033 | # cannot parse the '1,2,3' |
| 5034 | self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[]), args) |
| 5035 | self.assertEqual(["1", "2", "3"], extras) |
| 5036 | |
| 5037 | argv = 'cmd --foo x 1 --error 2 --bar y 3'.split() |
| 5038 | args, extras = parser.parse_known_intermixed_args(argv) |
| 5039 | # unknown optionals go into extras |
| 5040 | self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1]), args) |
| 5041 | self.assertEqual(['--error', '2', '3'], extras) |
| 5042 | |
| 5043 | # restores attributes that were temporarily changed |
| 5044 | self.assertIsNone(parser.usage) |
| 5045 | self.assertEqual(bar.required, True) |
| 5046 | |
| 5047 | def test_remainder(self): |
| 5048 | # Intermixed and remainder are incompatible |
| 5049 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 5050 | parser.add_argument('-z') |
| 5051 | parser.add_argument('x') |
| 5052 | parser.add_argument('y', nargs='...') |
| 5053 | argv = 'X A B -z Z'.split() |
| 5054 | # intermixed fails with '...' (also 'A...') |
| 5055 | # self.assertRaises(TypeError, parser.parse_intermixed_args, argv) |
| 5056 | with self.assertRaises(TypeError) as cm: |
| 5057 | parser.parse_intermixed_args(argv) |
| 5058 | self.assertRegex(str(cm.exception), r'\.\.\.') |
| 5059 | |
| 5060 | def test_exclusive(self): |
| 5061 | # mutually exclusive group; intermixed works fine |
| 5062 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 5063 | group = parser.add_mutually_exclusive_group(required=True) |
| 5064 | group.add_argument('--foo', action='store_true', help='FOO') |
| 5065 | group.add_argument('--spam', help='SPAM') |
| 5066 | parser.add_argument('badger', nargs='*', default='X', help='BADGER') |
| 5067 | args = parser.parse_intermixed_args('1 --foo 2'.split()) |
| 5068 | self.assertEqual(NS(badger=['1', '2'], foo=True, spam=None), args) |
| 5069 | self.assertRaises(ArgumentParserError, parser.parse_intermixed_args, '1 2'.split()) |
| 5070 | self.assertEqual(group.required, True) |
| 5071 | |
| 5072 | def test_exclusive_incompatible(self): |
| 5073 | # mutually exclusive group including positional - fail |
| 5074 | parser = ErrorRaisingArgumentParser(prog='PROG') |
| 5075 | group = parser.add_mutually_exclusive_group(required=True) |
| 5076 | group.add_argument('--foo', action='store_true', help='FOO') |
| 5077 | group.add_argument('--spam', help='SPAM') |
| 5078 | group.add_argument('badger', nargs='*', default='X', help='BADGER') |
| 5079 | self.assertRaises(TypeError, parser.parse_intermixed_args, []) |
| 5080 | self.assertEqual(group.required, True) |
| 5081 | |
| 5082 | class TestIntermixedMessageContentError(TestCase): |
| 5083 | # case where Intermixed gives different error message |
| 5084 | # error is raised by 1st parsing step |
| 5085 | def test_missing_argument_name_in_message(self): |
| 5086 | parser = ErrorRaisingArgumentParser(prog='PROG', usage='') |
| 5087 | parser.add_argument('req_pos', type=str) |
| 5088 | parser.add_argument('-req_opt', type=int, required=True) |
| 5089 | |
| 5090 | with self.assertRaises(ArgumentParserError) as cm: |
| 5091 | parser.parse_args([]) |
| 5092 | msg = str(cm.exception) |
| 5093 | self.assertRegex(msg, 'req_pos') |
| 5094 | self.assertRegex(msg, 'req_opt') |
| 5095 | |
| 5096 | with self.assertRaises(ArgumentParserError) as cm: |
| 5097 | parser.parse_intermixed_args([]) |
| 5098 | msg = str(cm.exception) |
| 5099 | self.assertNotRegex(msg, 'req_pos') |
| 5100 | self.assertRegex(msg, 'req_opt') |
| 5101 | |
Steven Bethard | 8d9a462 | 2011-03-26 17:33:56 +0100 | [diff] [blame] | 5102 | # ========================== |
| 5103 | # add_argument metavar tests |
| 5104 | # ========================== |
| 5105 | |
| 5106 | class TestAddArgumentMetavar(TestCase): |
| 5107 | |
| 5108 | EXPECTED_MESSAGE = "length of metavar tuple does not match nargs" |
| 5109 | |
| 5110 | def do_test_no_exception(self, nargs, metavar): |
| 5111 | parser = argparse.ArgumentParser() |
| 5112 | parser.add_argument("--foo", nargs=nargs, metavar=metavar) |
| 5113 | |
| 5114 | def do_test_exception(self, nargs, metavar): |
| 5115 | parser = argparse.ArgumentParser() |
| 5116 | with self.assertRaises(ValueError) as cm: |
| 5117 | parser.add_argument("--foo", nargs=nargs, metavar=metavar) |
| 5118 | self.assertEqual(cm.exception.args[0], self.EXPECTED_MESSAGE) |
| 5119 | |
| 5120 | # Unit tests for different values of metavar when nargs=None |
| 5121 | |
| 5122 | def test_nargs_None_metavar_string(self): |
| 5123 | self.do_test_no_exception(nargs=None, metavar="1") |
| 5124 | |
| 5125 | def test_nargs_None_metavar_length0(self): |
| 5126 | self.do_test_exception(nargs=None, metavar=tuple()) |
| 5127 | |
| 5128 | def test_nargs_None_metavar_length1(self): |
wim glenn | 66f02aa | 2018-06-08 05:12:49 -0500 | [diff] [blame] | 5129 | self.do_test_no_exception(nargs=None, metavar=("1",)) |
Steven Bethard | 8d9a462 | 2011-03-26 17:33:56 +0100 | [diff] [blame] | 5130 | |
| 5131 | def test_nargs_None_metavar_length2(self): |
| 5132 | self.do_test_exception(nargs=None, metavar=("1", "2")) |
| 5133 | |
| 5134 | def test_nargs_None_metavar_length3(self): |
| 5135 | self.do_test_exception(nargs=None, metavar=("1", "2", "3")) |
| 5136 | |
| 5137 | # Unit tests for different values of metavar when nargs=? |
| 5138 | |
| 5139 | def test_nargs_optional_metavar_string(self): |
| 5140 | self.do_test_no_exception(nargs="?", metavar="1") |
| 5141 | |
| 5142 | def test_nargs_optional_metavar_length0(self): |
| 5143 | self.do_test_exception(nargs="?", metavar=tuple()) |
| 5144 | |
| 5145 | def test_nargs_optional_metavar_length1(self): |
wim glenn | 66f02aa | 2018-06-08 05:12:49 -0500 | [diff] [blame] | 5146 | self.do_test_no_exception(nargs="?", metavar=("1",)) |
Steven Bethard | 8d9a462 | 2011-03-26 17:33:56 +0100 | [diff] [blame] | 5147 | |
| 5148 | def test_nargs_optional_metavar_length2(self): |
| 5149 | self.do_test_exception(nargs="?", metavar=("1", "2")) |
| 5150 | |
| 5151 | def test_nargs_optional_metavar_length3(self): |
| 5152 | self.do_test_exception(nargs="?", metavar=("1", "2", "3")) |
| 5153 | |
| 5154 | # Unit tests for different values of metavar when nargs=* |
| 5155 | |
| 5156 | def test_nargs_zeroormore_metavar_string(self): |
| 5157 | self.do_test_no_exception(nargs="*", metavar="1") |
| 5158 | |
| 5159 | def test_nargs_zeroormore_metavar_length0(self): |
| 5160 | self.do_test_exception(nargs="*", metavar=tuple()) |
| 5161 | |
| 5162 | def test_nargs_zeroormore_metavar_length1(self): |
Brandt Bucher | a0ed99b | 2019-11-11 12:47:48 -0800 | [diff] [blame] | 5163 | self.do_test_no_exception(nargs="*", metavar=("1",)) |
Steven Bethard | 8d9a462 | 2011-03-26 17:33:56 +0100 | [diff] [blame] | 5164 | |
| 5165 | def test_nargs_zeroormore_metavar_length2(self): |
| 5166 | self.do_test_no_exception(nargs="*", metavar=("1", "2")) |
| 5167 | |
| 5168 | def test_nargs_zeroormore_metavar_length3(self): |
| 5169 | self.do_test_exception(nargs="*", metavar=("1", "2", "3")) |
| 5170 | |
| 5171 | # Unit tests for different values of metavar when nargs=+ |
| 5172 | |
| 5173 | def test_nargs_oneormore_metavar_string(self): |
| 5174 | self.do_test_no_exception(nargs="+", metavar="1") |
| 5175 | |
| 5176 | def test_nargs_oneormore_metavar_length0(self): |
| 5177 | self.do_test_exception(nargs="+", metavar=tuple()) |
| 5178 | |
| 5179 | def test_nargs_oneormore_metavar_length1(self): |
wim glenn | 66f02aa | 2018-06-08 05:12:49 -0500 | [diff] [blame] | 5180 | self.do_test_exception(nargs="+", metavar=("1",)) |
Steven Bethard | 8d9a462 | 2011-03-26 17:33:56 +0100 | [diff] [blame] | 5181 | |
| 5182 | def test_nargs_oneormore_metavar_length2(self): |
| 5183 | self.do_test_no_exception(nargs="+", metavar=("1", "2")) |
| 5184 | |
| 5185 | def test_nargs_oneormore_metavar_length3(self): |
| 5186 | self.do_test_exception(nargs="+", metavar=("1", "2", "3")) |
| 5187 | |
| 5188 | # Unit tests for different values of metavar when nargs=... |
| 5189 | |
| 5190 | def test_nargs_remainder_metavar_string(self): |
| 5191 | self.do_test_no_exception(nargs="...", metavar="1") |
| 5192 | |
| 5193 | def test_nargs_remainder_metavar_length0(self): |
| 5194 | self.do_test_no_exception(nargs="...", metavar=tuple()) |
| 5195 | |
| 5196 | def test_nargs_remainder_metavar_length1(self): |
wim glenn | 66f02aa | 2018-06-08 05:12:49 -0500 | [diff] [blame] | 5197 | self.do_test_no_exception(nargs="...", metavar=("1",)) |
Steven Bethard | 8d9a462 | 2011-03-26 17:33:56 +0100 | [diff] [blame] | 5198 | |
| 5199 | def test_nargs_remainder_metavar_length2(self): |
| 5200 | self.do_test_no_exception(nargs="...", metavar=("1", "2")) |
| 5201 | |
| 5202 | def test_nargs_remainder_metavar_length3(self): |
| 5203 | self.do_test_no_exception(nargs="...", metavar=("1", "2", "3")) |
| 5204 | |
| 5205 | # Unit tests for different values of metavar when nargs=A... |
| 5206 | |
| 5207 | def test_nargs_parser_metavar_string(self): |
| 5208 | self.do_test_no_exception(nargs="A...", metavar="1") |
| 5209 | |
| 5210 | def test_nargs_parser_metavar_length0(self): |
| 5211 | self.do_test_exception(nargs="A...", metavar=tuple()) |
| 5212 | |
| 5213 | def test_nargs_parser_metavar_length1(self): |
wim glenn | 66f02aa | 2018-06-08 05:12:49 -0500 | [diff] [blame] | 5214 | self.do_test_no_exception(nargs="A...", metavar=("1",)) |
Steven Bethard | 8d9a462 | 2011-03-26 17:33:56 +0100 | [diff] [blame] | 5215 | |
| 5216 | def test_nargs_parser_metavar_length2(self): |
| 5217 | self.do_test_exception(nargs="A...", metavar=("1", "2")) |
| 5218 | |
| 5219 | def test_nargs_parser_metavar_length3(self): |
| 5220 | self.do_test_exception(nargs="A...", metavar=("1", "2", "3")) |
| 5221 | |
| 5222 | # Unit tests for different values of metavar when nargs=1 |
| 5223 | |
| 5224 | def test_nargs_1_metavar_string(self): |
| 5225 | self.do_test_no_exception(nargs=1, metavar="1") |
| 5226 | |
| 5227 | def test_nargs_1_metavar_length0(self): |
| 5228 | self.do_test_exception(nargs=1, metavar=tuple()) |
| 5229 | |
| 5230 | def test_nargs_1_metavar_length1(self): |
wim glenn | 66f02aa | 2018-06-08 05:12:49 -0500 | [diff] [blame] | 5231 | self.do_test_no_exception(nargs=1, metavar=("1",)) |
Steven Bethard | 8d9a462 | 2011-03-26 17:33:56 +0100 | [diff] [blame] | 5232 | |
| 5233 | def test_nargs_1_metavar_length2(self): |
| 5234 | self.do_test_exception(nargs=1, metavar=("1", "2")) |
| 5235 | |
| 5236 | def test_nargs_1_metavar_length3(self): |
| 5237 | self.do_test_exception(nargs=1, metavar=("1", "2", "3")) |
| 5238 | |
| 5239 | # Unit tests for different values of metavar when nargs=2 |
| 5240 | |
| 5241 | def test_nargs_2_metavar_string(self): |
| 5242 | self.do_test_no_exception(nargs=2, metavar="1") |
| 5243 | |
| 5244 | def test_nargs_2_metavar_length0(self): |
| 5245 | self.do_test_exception(nargs=2, metavar=tuple()) |
| 5246 | |
| 5247 | def test_nargs_2_metavar_length1(self): |
wim glenn | 66f02aa | 2018-06-08 05:12:49 -0500 | [diff] [blame] | 5248 | self.do_test_exception(nargs=2, metavar=("1",)) |
Steven Bethard | 8d9a462 | 2011-03-26 17:33:56 +0100 | [diff] [blame] | 5249 | |
| 5250 | def test_nargs_2_metavar_length2(self): |
| 5251 | self.do_test_no_exception(nargs=2, metavar=("1", "2")) |
| 5252 | |
| 5253 | def test_nargs_2_metavar_length3(self): |
| 5254 | self.do_test_exception(nargs=2, metavar=("1", "2", "3")) |
| 5255 | |
| 5256 | # Unit tests for different values of metavar when nargs=3 |
| 5257 | |
| 5258 | def test_nargs_3_metavar_string(self): |
| 5259 | self.do_test_no_exception(nargs=3, metavar="1") |
| 5260 | |
| 5261 | def test_nargs_3_metavar_length0(self): |
| 5262 | self.do_test_exception(nargs=3, metavar=tuple()) |
| 5263 | |
| 5264 | def test_nargs_3_metavar_length1(self): |
wim glenn | 66f02aa | 2018-06-08 05:12:49 -0500 | [diff] [blame] | 5265 | self.do_test_exception(nargs=3, metavar=("1",)) |
Steven Bethard | 8d9a462 | 2011-03-26 17:33:56 +0100 | [diff] [blame] | 5266 | |
| 5267 | def test_nargs_3_metavar_length2(self): |
| 5268 | self.do_test_exception(nargs=3, metavar=("1", "2")) |
| 5269 | |
| 5270 | def test_nargs_3_metavar_length3(self): |
| 5271 | self.do_test_no_exception(nargs=3, metavar=("1", "2", "3")) |
| 5272 | |
tmblweed | 4b3e975 | 2019-08-01 21:57:13 -0700 | [diff] [blame] | 5273 | |
| 5274 | class TestInvalidNargs(TestCase): |
| 5275 | |
| 5276 | EXPECTED_INVALID_MESSAGE = "invalid nargs value" |
| 5277 | EXPECTED_RANGE_MESSAGE = ("nargs for store actions must be != 0; if you " |
| 5278 | "have nothing to store, actions such as store " |
| 5279 | "true or store const may be more appropriate") |
| 5280 | |
| 5281 | def do_test_range_exception(self, nargs): |
| 5282 | parser = argparse.ArgumentParser() |
| 5283 | with self.assertRaises(ValueError) as cm: |
| 5284 | parser.add_argument("--foo", nargs=nargs) |
| 5285 | self.assertEqual(cm.exception.args[0], self.EXPECTED_RANGE_MESSAGE) |
| 5286 | |
| 5287 | def do_test_invalid_exception(self, nargs): |
| 5288 | parser = argparse.ArgumentParser() |
| 5289 | with self.assertRaises(ValueError) as cm: |
| 5290 | parser.add_argument("--foo", nargs=nargs) |
| 5291 | self.assertEqual(cm.exception.args[0], self.EXPECTED_INVALID_MESSAGE) |
| 5292 | |
| 5293 | # Unit tests for different values of nargs |
| 5294 | |
| 5295 | def test_nargs_alphabetic(self): |
| 5296 | self.do_test_invalid_exception(nargs='a') |
| 5297 | self.do_test_invalid_exception(nargs="abcd") |
| 5298 | |
| 5299 | def test_nargs_zero(self): |
| 5300 | self.do_test_range_exception(nargs=0) |
| 5301 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 5302 | # ============================ |
| 5303 | # from argparse import * tests |
| 5304 | # ============================ |
| 5305 | |
| 5306 | class TestImportStar(TestCase): |
| 5307 | |
| 5308 | def test(self): |
| 5309 | for name in argparse.__all__: |
| 5310 | self.assertTrue(hasattr(argparse, name)) |
| 5311 | |
Steven Bethard | 72c5538 | 2010-11-01 15:23:12 +0000 | [diff] [blame] | 5312 | def test_all_exports_everything_but_modules(self): |
| 5313 | items = [ |
| 5314 | name |
| 5315 | for name, value in vars(argparse).items() |
Éric Araujo | 1215915 | 2010-12-04 17:31:49 +0000 | [diff] [blame] | 5316 | if not (name.startswith("_") or name == 'ngettext') |
Steven Bethard | 72c5538 | 2010-11-01 15:23:12 +0000 | [diff] [blame] | 5317 | if not inspect.ismodule(value) |
| 5318 | ] |
| 5319 | self.assertEqual(sorted(items), sorted(argparse.__all__)) |
| 5320 | |
wim glenn | 66f02aa | 2018-06-08 05:12:49 -0500 | [diff] [blame] | 5321 | |
| 5322 | class TestWrappingMetavar(TestCase): |
| 5323 | |
| 5324 | def setUp(self): |
Berker Peksag | 74102c9 | 2018-07-25 18:23:44 +0300 | [diff] [blame] | 5325 | super().setUp() |
wim glenn | 66f02aa | 2018-06-08 05:12:49 -0500 | [diff] [blame] | 5326 | self.parser = ErrorRaisingArgumentParser( |
| 5327 | 'this_is_spammy_prog_with_a_long_name_sorry_about_the_name' |
| 5328 | ) |
| 5329 | # this metavar was triggering library assertion errors due to usage |
| 5330 | # message formatting incorrectly splitting on the ] chars within |
| 5331 | metavar = '<http[s]://example:1234>' |
| 5332 | self.parser.add_argument('--proxy', metavar=metavar) |
| 5333 | |
| 5334 | def test_help_with_metavar(self): |
| 5335 | help_text = self.parser.format_help() |
| 5336 | self.assertEqual(help_text, textwrap.dedent('''\ |
| 5337 | usage: this_is_spammy_prog_with_a_long_name_sorry_about_the_name |
| 5338 | [-h] [--proxy <http[s]://example:1234>] |
| 5339 | |
| 5340 | optional arguments: |
| 5341 | -h, --help show this help message and exit |
| 5342 | --proxy <http[s]://example:1234> |
| 5343 | ''')) |
| 5344 | |
| 5345 | |
Hai Shi | f545638 | 2019-09-12 05:56:05 -0500 | [diff] [blame] | 5346 | class TestExitOnError(TestCase): |
| 5347 | |
| 5348 | def setUp(self): |
| 5349 | self.parser = argparse.ArgumentParser(exit_on_error=False) |
| 5350 | self.parser.add_argument('--integers', metavar='N', type=int) |
| 5351 | |
| 5352 | def test_exit_on_error_with_good_args(self): |
| 5353 | ns = self.parser.parse_args('--integers 4'.split()) |
| 5354 | self.assertEqual(ns, argparse.Namespace(integers=4)) |
| 5355 | |
| 5356 | def test_exit_on_error_with_bad_args(self): |
| 5357 | with self.assertRaises(argparse.ArgumentError): |
| 5358 | self.parser.parse_args('--integers a'.split()) |
| 5359 | |
| 5360 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 5361 | def test_main(): |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 5362 | support.run_unittest(__name__) |
Benjamin Peterson | 4fd181c | 2010-03-02 23:46:42 +0000 | [diff] [blame] | 5363 | # Remove global references to avoid looking like we have refleaks. |
| 5364 | RFile.seen = {} |
| 5365 | WFile.seen = set() |
| 5366 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 5367 | |
| 5368 | |
| 5369 | if __name__ == '__main__': |
| 5370 | test_main() |