| 1 |
# Author: Steven J. Bethard <[email protected]>. |
| 2 |
|
| 3 |
import _colorize |
| 4 |
import contextlib |
| 5 |
import functools |
| 6 |
import inspect |
| 7 |
import io |
| 8 |
import operator |
| 9 |
import os |
| 10 |
import py_compile |
| 11 |
import shutil |
| 12 |
import stat |
| 13 |
import sys |
| 14 |
import textwrap |
| 15 |
import tempfile |
| 16 |
import unittest |
| 17 |
import argparse |
| 18 |
import warnings |
| 19 |
|
| 20 |
from enum import StrEnum |
| 21 |
from test.support import ( |
| 22 |
captured_stderr, |
| 23 |
force_not_colorized, |
| 24 |
force_not_colorized_test_class, |
| 25 |
swap_attr, |
| 26 |
) |
| 27 |
from test.support import import_helper |
| 28 |
from test.support import os_helper |
| 29 |
from test.support import script_helper |
| 30 |
from test.support.i18n_helper import TestTranslationsBase, update_translation_snapshots |
| 31 |
from unittest import mock |
| 32 |
|
| 33 |
|
| 34 |
py = os.path.basename(sys.executable) |
| 35 |
|
| 36 |
|
| 37 |
class StdIOBuffer(io.TextIOWrapper): |
| 38 |
'''Replacement for writable io.StringIO that behaves more like real file |
| 39 |
|
| 40 |
Unlike StringIO, provides a buffer attribute that holds the underlying |
| 41 |
binary data, allowing it to replace sys.stdout/sys.stderr in more |
| 42 |
contexts. |
| 43 |
''' |
| 44 |
|
| 45 |
def __init__(self, initial_value='', newline='\n'): |
| 46 |
initial_value = initial_value.encode('utf-8') |
| 47 |
super().__init__(io.BufferedWriter(io.BytesIO(initial_value)), |
| 48 |
'utf-8', newline=newline) |
| 49 |
|
| 50 |
def getvalue(self): |
| 51 |
self.flush() |
| 52 |
return self.buffer.raw.getvalue().decode('utf-8') |
| 53 |
|
| 54 |
|
| 55 |
class StdStreamTest(unittest.TestCase): |
| 56 |
|
| 57 |
def test_skip_invalid_stderr(self): |
| 58 |
parser = argparse.ArgumentParser() |
| 59 |
with ( |
| 60 |
contextlib.redirect_stderr(None), |
| 61 |
mock.patch('argparse._sys.exit') |
| 62 |
): |
| 63 |
parser.exit(status=0, message='foo') |
| 64 |
|
| 65 |
def test_skip_invalid_stdout(self): |
| 66 |
parser = argparse.ArgumentParser() |
| 67 |
for func in ( |
| 68 |
parser.print_usage, |
| 69 |
parser.print_help, |
| 70 |
functools.partial(parser.parse_args, ['-h']) |
| 71 |
): |
| 72 |
with ( |
| 73 |
self.subTest(func=func), |
| 74 |
contextlib.redirect_stdout(None), |
| 75 |
# argparse uses stderr as a fallback |
| 76 |
StdIOBuffer() as mocked_stderr, |
| 77 |
contextlib.redirect_stderr(mocked_stderr), |
| 78 |
mock.patch('argparse._sys.exit'), |
| 79 |
): |
| 80 |
func() |
| 81 |
self.assertRegex(mocked_stderr.getvalue(), r'usage:') |
| 82 |
|
| 83 |
|
| 84 |
class TestArgumentParserPickleable(unittest.TestCase): |
| 85 |
|
| 86 |
@force_not_colorized |
| 87 |
def test_pickle_roundtrip(self): |
| 88 |
import pickle |
| 89 |
parser = argparse.ArgumentParser(exit_on_error=False) |
| 90 |
parser.add_argument('--foo', type=int, default=42) |
| 91 |
parser.add_argument('bar', nargs='?', default='baz') |
| 92 |
for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 93 |
with self.subTest(protocol=proto): |
| 94 |
# Try to pickle and unpickle the parser |
| 95 |
parser2 = pickle.loads(pickle.dumps(parser, protocol=proto)) |
| 96 |
# Check that the round-tripped parser still works |
| 97 |
ns = parser2.parse_args(['--foo', '123', 'quux']) |
| 98 |
self.assertEqual(ns.foo, 123) |
| 99 |
self.assertEqual(ns.bar, 'quux') |
| 100 |
ns2 = parser2.parse_args([]) |
| 101 |
self.assertEqual(ns2.foo, 42) |
| 102 |
self.assertEqual(ns2.bar, 'baz') |
| 103 |
|
| 104 |
|
| 105 |
class TestCase(unittest.TestCase): |
| 106 |
|
| 107 |
def setUp(self): |
| 108 |
# The tests assume that line wrapping occurs at 80 columns, but this |
| 109 |
# behaviour can be overridden by setting the COLUMNS environment |
| 110 |
# variable. To ensure that this width is used, set COLUMNS to 80. |
| 111 |
env = self.enterContext(os_helper.EnvironmentVarGuard()) |
| 112 |
env['COLUMNS'] = '80' |
| 113 |
|
| 114 |
|
| 115 |
@os_helper.skip_unless_working_chmod |
| 116 |
class TempDirMixin(object): |
| 117 |
|
| 118 |
def setUp(self): |
| 119 |
self.temp_dir = tempfile.mkdtemp() |
| 120 |
self.old_dir = os.getcwd() |
| 121 |
os.chdir(self.temp_dir) |
| 122 |
|
| 123 |
def tearDown(self): |
| 124 |
os.chdir(self.old_dir) |
| 125 |
for root, dirs, files in os.walk(self.temp_dir, topdown=False): |
| 126 |
for name in files: |
| 127 |
os.chmod(os.path.join(self.temp_dir, name), stat.S_IWRITE) |
| 128 |
shutil.rmtree(self.temp_dir, True) |
| 129 |
|
| 130 |
def create_writable_file(self, filename): |
| 131 |
file_path = os.path.join(self.temp_dir, filename) |
| 132 |
with open(file_path, 'w', encoding="utf-8") as file: |
| 133 |
file.write(filename) |
| 134 |
return file_path |
| 135 |
|
| 136 |
def create_readonly_file(self, filename): |
| 137 |
os.chmod(self.create_writable_file(filename), stat.S_IREAD) |
| 138 |
|
| 139 |
class Sig(object): |
| 140 |
|
| 141 |
def __init__(self, *args, **kwargs): |
| 142 |
self.args = args |
| 143 |
self.kwargs = kwargs |
| 144 |
|
| 145 |
|
| 146 |
class NS(object): |
| 147 |
|
| 148 |
def __init__(self, **kwargs): |
| 149 |
self.__dict__.update(kwargs) |
| 150 |
|
| 151 |
def __repr__(self): |
| 152 |
sorted_items = sorted(self.__dict__.items()) |
| 153 |
kwarg_str = ', '.join(['%s=%r' % tup for tup in sorted_items]) |
| 154 |
return '%s(%s)' % (type(self).__name__, kwarg_str) |
| 155 |
|
| 156 |
def __eq__(self, other): |
| 157 |
return vars(self) == vars(other) |
| 158 |
|
| 159 |
|
| 160 |
class ArgumentParserError(Exception): |
| 161 |
|
| 162 |
def __init__(self, message, stdout=None, stderr=None, error_code=None): |
| 163 |
Exception.__init__(self, message, stdout, stderr) |
| 164 |
self.message = message |
| 165 |
self.stdout = stdout |
| 166 |
self.stderr = stderr |
| 167 |
self.error_code = error_code |
| 168 |
|
| 169 |
|
| 170 |
def stderr_to_parser_error(parse_args, *args, **kwargs): |
| 171 |
# if this is being called recursively and stderr or stdout is already being |
| 172 |
# redirected, simply call the function and let the enclosing function |
| 173 |
# catch the exception |
| 174 |
if isinstance(sys.stderr, StdIOBuffer) or isinstance(sys.stdout, StdIOBuffer): |
| 175 |
return parse_args(*args, **kwargs) |
| 176 |
|
| 177 |
# if this is not being called recursively, redirect stderr and |
| 178 |
# use it as the ArgumentParserError message |
| 179 |
old_stdout = sys.stdout |
| 180 |
old_stderr = sys.stderr |
| 181 |
sys.stdout = StdIOBuffer() |
| 182 |
sys.stderr = StdIOBuffer() |
| 183 |
try: |
| 184 |
try: |
| 185 |
result = parse_args(*args, **kwargs) |
| 186 |
for key in list(vars(result)): |
| 187 |
attr = getattr(result, key) |
| 188 |
if attr is sys.stdout: |
| 189 |
setattr(result, key, old_stdout) |
| 190 |
elif attr is sys.stdout.buffer: |
| 191 |
setattr(result, key, getattr(old_stdout, 'buffer', BIN_STDOUT_SENTINEL)) |
| 192 |
elif attr is sys.stderr: |
| 193 |
setattr(result, key, old_stderr) |
| 194 |
elif attr is sys.stderr.buffer: |
| 195 |
setattr(result, key, getattr(old_stderr, 'buffer', BIN_STDERR_SENTINEL)) |
| 196 |
return result |
| 197 |
except SystemExit as e: |
| 198 |
code = e.code |
| 199 |
stdout = sys.stdout.getvalue() |
| 200 |
stderr = sys.stderr.getvalue() |
| 201 |
raise ArgumentParserError( |
| 202 |
"SystemExit", stdout, stderr, code) from None |
| 203 |
finally: |
| 204 |
sys.stdout = old_stdout |
| 205 |
sys.stderr = old_stderr |
| 206 |
|
| 207 |
|
| 208 |
class ErrorRaisingArgumentParser(argparse.ArgumentParser): |
| 209 |
|
| 210 |
def parse_args(self, *args, **kwargs): |
| 211 |
parse_args = super(ErrorRaisingArgumentParser, self).parse_args |
| 212 |
return stderr_to_parser_error(parse_args, *args, **kwargs) |
| 213 |
|
| 214 |
def exit(self, *args, **kwargs): |
| 215 |
exit = super(ErrorRaisingArgumentParser, self).exit |
| 216 |
return stderr_to_parser_error(exit, *args, **kwargs) |
| 217 |
|
| 218 |
def error(self, *args, **kwargs): |
| 219 |
error = super(ErrorRaisingArgumentParser, self).error |
| 220 |
return stderr_to_parser_error(error, *args, **kwargs) |
| 221 |
|
| 222 |
|
| 223 |
class ParserTesterMetaclass(type): |
| 224 |
"""Adds parser tests using the class attributes. |
| 225 |
|
| 226 |
Classes of this type should specify the following attributes: |
| 227 |
|
| 228 |
argument_signatures -- a list of Sig objects which specify |
| 229 |
the signatures of Argument objects to be created |
| 230 |
failures -- a list of args lists that should cause the parser |
| 231 |
to fail |
| 232 |
successes -- a list of (initial_args, options, remaining_args) tuples |
| 233 |
where initial_args specifies the string args to be parsed, |
| 234 |
options is a dict that should match the vars() of the options |
| 235 |
parsed out of initial_args, and remaining_args should be any |
| 236 |
remaining unparsed arguments |
| 237 |
""" |
| 238 |
|
| 239 |
def __init__(cls, name, bases, bodydict): |
| 240 |
if name == 'ParserTestCase': |
| 241 |
return |
| 242 |
|
| 243 |
# default parser signature is empty |
| 244 |
if not hasattr(cls, 'parser_signature'): |
| 245 |
cls.parser_signature = Sig() |
| 246 |
if not hasattr(cls, 'parser_class'): |
| 247 |
cls.parser_class = ErrorRaisingArgumentParser |
| 248 |
|
| 249 |
# --------------------------------------- |
| 250 |
# functions for adding optional arguments |
| 251 |
# --------------------------------------- |
| 252 |
def no_groups(parser, argument_signatures): |
| 253 |
"""Add all arguments directly to the parser""" |
| 254 |
for sig in argument_signatures: |
| 255 |
parser.add_argument(*sig.args, **sig.kwargs) |
| 256 |
|
| 257 |
def one_group(parser, argument_signatures): |
| 258 |
"""Add all arguments under a single group in the parser""" |
| 259 |
group = parser.add_argument_group('foo') |
| 260 |
for sig in argument_signatures: |
| 261 |
group.add_argument(*sig.args, **sig.kwargs) |
| 262 |
|
| 263 |
def many_groups(parser, argument_signatures): |
| 264 |
"""Add each argument in its own group to the parser""" |
| 265 |
for i, sig in enumerate(argument_signatures): |
| 266 |
group = parser.add_argument_group('foo:%i' % i) |
| 267 |
group.add_argument(*sig.args, **sig.kwargs) |
| 268 |
|
| 269 |
# -------------------------- |
| 270 |
# functions for parsing args |
| 271 |
# -------------------------- |
| 272 |
def listargs(parser, args): |
| 273 |
"""Parse the args by passing in a list""" |
| 274 |
return parser.parse_args(args) |
| 275 |
|
| 276 |
def sysargs(parser, args): |
| 277 |
"""Parse the args by defaulting to sys.argv""" |
| 278 |
old_sys_argv = sys.argv |
| 279 |
sys.argv = [old_sys_argv[0]] + args |
| 280 |
try: |
| 281 |
return parser.parse_args() |
| 282 |
finally: |
| 283 |
sys.argv = old_sys_argv |
| 284 |
|
| 285 |
# class that holds the combination of one optional argument |
| 286 |
# addition method and one arg parsing method |
| 287 |
class AddTests(object): |
| 288 |
|
| 289 |
def __init__(self, tester_cls, add_arguments, parse_args): |
| 290 |
self._add_arguments = add_arguments |
| 291 |
self._parse_args = parse_args |
| 292 |
|
| 293 |
add_arguments_name = self._add_arguments.__name__ |
| 294 |
parse_args_name = self._parse_args.__name__ |
| 295 |
for test_func in [self.test_failures, self.test_successes]: |
| 296 |
func_name = test_func.__name__ |
| 297 |
names = func_name, add_arguments_name, parse_args_name |
| 298 |
test_name = '_'.join(names) |
| 299 |
|
| 300 |
def wrapper(self, test_func=test_func): |
| 301 |
test_func(self) |
| 302 |
try: |
| 303 |
wrapper.__name__ = test_name |
| 304 |
except TypeError: |
| 305 |
pass |
| 306 |
setattr(tester_cls, test_name, wrapper) |
| 307 |
|
| 308 |
def _get_parser(self, tester): |
| 309 |
args = tester.parser_signature.args |
| 310 |
kwargs = tester.parser_signature.kwargs |
| 311 |
parser = tester.parser_class(*args, **kwargs) |
| 312 |
self._add_arguments(parser, tester.argument_signatures) |
| 313 |
return parser |
| 314 |
|
| 315 |
def test_failures(self, tester): |
| 316 |
parser = self._get_parser(tester) |
| 317 |
for args_str in tester.failures: |
| 318 |
args = args_str.split() |
| 319 |
with tester.subTest(args=args): |
| 320 |
with tester.assertRaises(ArgumentParserError, msg=args): |
| 321 |
parser.parse_args(args) |
| 322 |
|
| 323 |
def test_successes(self, tester): |
| 324 |
parser = self._get_parser(tester) |
| 325 |
for args, expected_ns in tester.successes: |
| 326 |
if isinstance(args, str): |
| 327 |
args = args.split() |
| 328 |
with tester.subTest(args=args): |
| 329 |
result_ns = self._parse_args(parser, args) |
| 330 |
tester.assertEqual(expected_ns, result_ns) |
| 331 |
|
| 332 |
# add tests for each combination of an optionals adding method |
| 333 |
# and an arg parsing method |
| 334 |
for add_arguments in [no_groups, one_group, many_groups]: |
| 335 |
for parse_args in [listargs, sysargs]: |
| 336 |
AddTests(cls, add_arguments, parse_args) |
| 337 |
|
| 338 |
bases = TestCase, |
| 339 |
ParserTestCase = ParserTesterMetaclass('ParserTestCase', bases, {}) |
| 340 |
|
| 341 |
# =============== |
| 342 |
# Optionals tests |
| 343 |
# =============== |
| 344 |
|
| 345 |
class TestOptionalsSingleDash(ParserTestCase): |
| 346 |
"""Test an Optional with a single-dash option string""" |
| 347 |
|
| 348 |
argument_signatures = [Sig('-x')] |
| 349 |
failures = ['-x', 'a', '--foo', '-x --foo', '-x -y'] |
| 350 |
successes = [ |
| 351 |
('', NS(x=None)), |
| 352 |
('-x a', NS(x='a')), |
| 353 |
('-xa', NS(x='a')), |
| 354 |
('-x -1', NS(x='-1')), |
| 355 |
('-x-1', NS(x='-1')), |
| 356 |
] |
| 357 |
|
| 358 |
|
| 359 |
class TestOptionalsSingleDashCombined(ParserTestCase): |
| 360 |
"""Test an Optional with a single-dash option string""" |
| 361 |
|
| 362 |
argument_signatures = [ |
| 363 |
Sig('-x', action='store_true'), |
| 364 |
Sig('-yyy', action='store_const', const=42), |
| 365 |
Sig('-z'), |
| 366 |
] |
| 367 |
failures = ['a', '--foo', '-xa', '-x --foo', '-x -z', '-z -x', |
| 368 |
'-yx', '-yz a', '-yyyx', '-yyyza', '-xyza', '-x='] |
| 369 |
successes = [ |
| 370 |
('', NS(x=False, yyy=None, z=None)), |
| 371 |
('-x', NS(x=True, yyy=None, z=None)), |
| 372 |
('-za', NS(x=False, yyy=None, z='a')), |
| 373 |
('-z a', NS(x=False, yyy=None, z='a')), |
| 374 |
('-xza', NS(x=True, yyy=None, z='a')), |
| 375 |
('-xz a', NS(x=True, yyy=None, z='a')), |
| 376 |
('-x -za', NS(x=True, yyy=None, z='a')), |
| 377 |
('-x -z a', NS(x=True, yyy=None, z='a')), |
| 378 |
('-y', NS(x=False, yyy=42, z=None)), |
| 379 |
('-yyy', NS(x=False, yyy=42, z=None)), |
| 380 |
('-x -yyy -za', NS(x=True, yyy=42, z='a')), |
| 381 |
('-x -yyy -z a', NS(x=True, yyy=42, z='a')), |
| 382 |
] |
| 383 |
|
| 384 |
|
| 385 |
class TestOptionalsSingleDashLong(ParserTestCase): |
| 386 |
"""Test an Optional with a multi-character single-dash option string""" |
| 387 |
|
| 388 |
argument_signatures = [Sig('-foo')] |
| 389 |
failures = ['-foo', 'a', '--foo', '-foo --foo', '-foo -y', '-fooa'] |
| 390 |
successes = [ |
| 391 |
('', NS(foo=None)), |
| 392 |
('-foo a', NS(foo='a')), |
| 393 |
('-foo -1', NS(foo='-1')), |
| 394 |
('-fo a', NS(foo='a')), |
| 395 |
('-f a', NS(foo='a')), |
| 396 |
] |
| 397 |
|
| 398 |
|
| 399 |
class TestOptionalsSingleDashSubsetAmbiguous(ParserTestCase): |
| 400 |
"""Test Optionals where option strings are subsets of each other""" |
| 401 |
|
| 402 |
argument_signatures = [Sig('-f'), Sig('-foobar'), Sig('-foorab')] |
| 403 |
failures = ['-f', '-foo', '-fo', '-foo b', '-foob', '-fooba', '-foora'] |
| 404 |
successes = [ |
| 405 |
('', NS(f=None, foobar=None, foorab=None)), |
| 406 |
('-f a', NS(f='a', foobar=None, foorab=None)), |
| 407 |
('-fa', NS(f='a', foobar=None, foorab=None)), |
| 408 |
('-foa', NS(f='oa', foobar=None, foorab=None)), |
| 409 |
('-fooa', NS(f='ooa', foobar=None, foorab=None)), |
| 410 |
('-foobar a', NS(f=None, foobar='a', foorab=None)), |
| 411 |
('-foorab a', NS(f=None, foobar=None, foorab='a')), |
| 412 |
] |
| 413 |
|
| 414 |
|
| 415 |
class TestOptionalsSingleDashAmbiguous(ParserTestCase): |
| 416 |
"""Test Optionals that partially match but are not subsets""" |
| 417 |
|
| 418 |
argument_signatures = [Sig('-foobar'), Sig('-foorab')] |
| 419 |
failures = ['-f', '-f a', '-fa', '-foa', '-foo', '-fo', '-foo b', |
| 420 |
'-f=a', '-foo=b'] |
| 421 |
successes = [ |
| 422 |
('', NS(foobar=None, foorab=None)), |
| 423 |
('-foob a', NS(foobar='a', foorab=None)), |
| 424 |
('-foob=a', NS(foobar='a', foorab=None)), |
| 425 |
('-foor a', NS(foobar=None, foorab='a')), |
| 426 |
('-foor=a', NS(foobar=None, foorab='a')), |
| 427 |
('-fooba a', NS(foobar='a', foorab=None)), |
| 428 |
('-fooba=a', NS(foobar='a', foorab=None)), |
| 429 |
('-foora a', NS(foobar=None, foorab='a')), |
| 430 |
('-foora=a', NS(foobar=None, foorab='a')), |
| 431 |
('-foobar a', NS(foobar='a', foorab=None)), |
| 432 |
('-foobar=a', NS(foobar='a', foorab=None)), |
| 433 |
('-foorab a', NS(foobar=None, foorab='a')), |
| 434 |
('-foorab=a', NS(foobar=None, foorab='a')), |
| 435 |
] |
| 436 |
|
| 437 |
|
| 438 |
class TestOptionalsNumeric(ParserTestCase): |
| 439 |
"""Test an Optional with a short opt string""" |
| 440 |
|
| 441 |
argument_signatures = [Sig('-1', dest='one')] |
| 442 |
failures = ['-1', 'a', '-1 --foo', '-1 -y', '-1 -1', '-1 -2'] |
| 443 |
successes = [ |
| 444 |
('', NS(one=None)), |
| 445 |
('-1 a', NS(one='a')), |
| 446 |
('-1a', NS(one='a')), |
| 447 |
('-1-2', NS(one='-2')), |
| 448 |
] |
| 449 |
|
| 450 |
|
| 451 |
class TestOptionalsDoubleDash(ParserTestCase): |
| 452 |
"""Test an Optional with a double-dash option string""" |
| 453 |
|
| 454 |
argument_signatures = [Sig('--foo')] |
| 455 |
failures = ['--foo', '-f', '-f a', 'a', '--foo -x', '--foo --bar'] |
| 456 |
successes = [ |
| 457 |
('', NS(foo=None)), |
| 458 |
('--foo a', NS(foo='a')), |
| 459 |
('--foo=a', NS(foo='a')), |
| 460 |
('--foo -2.5', NS(foo='-2.5')), |
| 461 |
('--foo=-2.5', NS(foo='-2.5')), |
| 462 |
] |
| 463 |
|
| 464 |
|
| 465 |
class TestOptionalsDoubleDashPartialMatch(ParserTestCase): |
| 466 |
"""Tests partial matching with a double-dash option string""" |
| 467 |
|
| 468 |
argument_signatures = [ |
| 469 |
Sig('--badger', action='store_true'), |
| 470 |
Sig('--bat'), |
| 471 |
] |
| 472 |
failures = ['--bar', '--b', '--ba', '--b=2', '--ba=4', '--badge 5'] |
| 473 |
successes = [ |
| 474 |
('', NS(badger=False, bat=None)), |
| 475 |
('--bat X', NS(badger=False, bat='X')), |
| 476 |
('--bad', NS(badger=True, bat=None)), |
| 477 |
('--badg', NS(badger=True, bat=None)), |
| 478 |
('--badge', NS(badger=True, bat=None)), |
| 479 |
('--badger', NS(badger=True, bat=None)), |
| 480 |
] |
| 481 |
|
| 482 |
|
| 483 |
class TestOptionalsDoubleDashPrefixMatch(ParserTestCase): |
| 484 |
"""Tests when one double-dash option string is a prefix of another""" |
| 485 |
|
| 486 |
argument_signatures = [ |
| 487 |
Sig('--badger', action='store_true'), |
| 488 |
Sig('--ba'), |
| 489 |
] |
| 490 |
failures = ['--bar', '--b', '--ba', '--b=2', '--badge 5'] |
| 491 |
successes = [ |
| 492 |
('', NS(badger=False, ba=None)), |
| 493 |
('--ba X', NS(badger=False, ba='X')), |
| 494 |
('--ba=X', NS(badger=False, ba='X')), |
| 495 |
('--bad', NS(badger=True, ba=None)), |
| 496 |
('--badg', NS(badger=True, ba=None)), |
| 497 |
('--badge', NS(badger=True, ba=None)), |
| 498 |
('--badger', NS(badger=True, ba=None)), |
| 499 |
] |
| 500 |
|
| 501 |
|
| 502 |
class TestOptionalsSingleDoubleDash(ParserTestCase): |
| 503 |
"""Test an Optional with single- and double-dash option strings""" |
| 504 |
|
| 505 |
argument_signatures = [ |
| 506 |
Sig('-f', action='store_true'), |
| 507 |
Sig('--bar'), |
| 508 |
Sig('-baz', action='store_const', const=42), |
| 509 |
] |
| 510 |
failures = ['--bar', '-fbar', '-fbaz', '-bazf', '-b B', 'B'] |
| 511 |
successes = [ |
| 512 |
('', NS(f=False, bar=None, baz=None)), |
| 513 |
('-f', NS(f=True, bar=None, baz=None)), |
| 514 |
('--ba B', NS(f=False, bar='B', baz=None)), |
| 515 |
('-f --bar B', NS(f=True, bar='B', baz=None)), |
| 516 |
('-f -b', NS(f=True, bar=None, baz=42)), |
| 517 |
('-ba -f', NS(f=True, bar=None, baz=42)), |
| 518 |
] |
| 519 |
|
| 520 |
|
| 521 |
class TestOptionalsAlternatePrefixChars(ParserTestCase): |
| 522 |
"""Test an Optional with option strings with custom prefixes""" |
| 523 |
|
| 524 |
parser_signature = Sig(prefix_chars='+:/', add_help=False) |
| 525 |
argument_signatures = [ |
| 526 |
Sig('+f', action='store_true'), |
| 527 |
Sig('::bar'), |
| 528 |
Sig('/baz', action='store_const', const=42), |
| 529 |
] |
| 530 |
failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz', '-h', '--help', '+h', '::help', '/help'] |
| 531 |
successes = [ |
| 532 |
('', NS(f=False, bar=None, baz=None)), |
| 533 |
('+f', NS(f=True, bar=None, baz=None)), |
| 534 |
('::ba B', NS(f=False, bar='B', baz=None)), |
| 535 |
('+f ::bar B', NS(f=True, bar='B', baz=None)), |
| 536 |
('+f /b', NS(f=True, bar=None, baz=42)), |
| 537 |
('/ba +f', NS(f=True, bar=None, baz=42)), |
| 538 |
] |
| 539 |
|
| 540 |
|
| 541 |
class TestOptionalsAlternatePrefixCharsAddedHelp(ParserTestCase): |
| 542 |
"""When ``-`` not in prefix_chars, default operators created for help |
| 543 |
should use the prefix_chars in use rather than - or -- |
| 544 |
http://bugs.python.org/issue9444""" |
| 545 |
|
| 546 |
parser_signature = Sig(prefix_chars='+:/', add_help=True) |
| 547 |
argument_signatures = [ |
| 548 |
Sig('+f', action='store_true'), |
| 549 |
Sig('::bar'), |
| 550 |
Sig('/baz', action='store_const', const=42), |
| 551 |
] |
| 552 |
failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz'] |
| 553 |
successes = [ |
| 554 |
('', NS(f=False, bar=None, baz=None)), |
| 555 |
('+f', NS(f=True, bar=None, baz=None)), |
| 556 |
('::ba B', NS(f=False, bar='B', baz=None)), |
| 557 |
('+f ::bar B', NS(f=True, bar='B', baz=None)), |
| 558 |
('+f /b', NS(f=True, bar=None, baz=42)), |
| 559 |
('/ba +f', NS(f=True, bar=None, baz=42)) |
| 560 |
] |
| 561 |
|
| 562 |
|
| 563 |
class TestOptionalsAlternatePrefixCharsMultipleShortArgs(ParserTestCase): |
| 564 |
"""Verify that Optionals must be called with their defined prefixes""" |
| 565 |
|
| 566 |
parser_signature = Sig(prefix_chars='+-', add_help=False) |
| 567 |
argument_signatures = [ |
| 568 |
Sig('-x', action='store_true'), |
| 569 |
Sig('+y', action='store_true'), |
| 570 |
Sig('+z', action='store_true'), |
| 571 |
] |
| 572 |
failures = ['-w', |
| 573 |
'-xyz', |
| 574 |
'+x', |
| 575 |
'-y', |
| 576 |
'+xyz', |
| 577 |
] |
| 578 |
successes = [ |
| 579 |
('', NS(x=False, y=False, z=False)), |
| 580 |
('-x', NS(x=True, y=False, z=False)), |
| 581 |
('+y -x', NS(x=True, y=True, z=False)), |
| 582 |
('+yz -x', NS(x=True, y=True, z=True)), |
| 583 |
] |
| 584 |
|
| 585 |
|
| 586 |
class TestOptionalsShortLong(ParserTestCase): |
| 587 |
"""Test a combination of single- and double-dash option strings""" |
| 588 |
|
| 589 |
argument_signatures = [ |
| 590 |
Sig('-v', '--verbose', '-n', '--noisy', action='store_true'), |
| 591 |
] |
| 592 |
failures = ['--x --verbose', '-N', 'a', '-v x'] |
| 593 |
successes = [ |
| 594 |
('', NS(verbose=False)), |
| 595 |
('-v', NS(verbose=True)), |
| 596 |
('--verbose', NS(verbose=True)), |
| 597 |
('-n', NS(verbose=True)), |
| 598 |
('--noisy', NS(verbose=True)), |
| 599 |
] |
| 600 |
|
| 601 |
|
| 602 |
class TestOptionalsDest(ParserTestCase): |
| 603 |
"""Tests various means of setting destination""" |
| 604 |
|
| 605 |
argument_signatures = [Sig('--foo-bar'), Sig('--baz', dest='zabbaz')] |
| 606 |
failures = ['a'] |
| 607 |
successes = [ |
| 608 |
('--foo-bar f', NS(foo_bar='f', zabbaz=None)), |
| 609 |
('--baz g', NS(foo_bar=None, zabbaz='g')), |
| 610 |
('--foo-bar h --baz i', NS(foo_bar='h', zabbaz='i')), |
| 611 |
('--baz j --foo-bar k', NS(foo_bar='k', zabbaz='j')), |
| 612 |
] |
| 613 |
|
| 614 |
|
| 615 |
class TestOptionalsDefault(ParserTestCase): |
| 616 |
"""Tests specifying a default for an Optional""" |
| 617 |
|
| 618 |
argument_signatures = [Sig('-x'), Sig('-y', default=42)] |
| 619 |
failures = ['a'] |
| 620 |
successes = [ |
| 621 |
('', NS(x=None, y=42)), |
| 622 |
('-xx', NS(x='x', y=42)), |
| 623 |
('-yy', NS(x=None, y='y')), |
| 624 |
] |
| 625 |
|
| 626 |
|
| 627 |
class TestOptionalsNargsDefault(ParserTestCase): |
| 628 |
"""Tests not specifying the number of args for an Optional""" |
| 629 |
|
| 630 |
argument_signatures = [Sig('-x')] |
| 631 |
failures = ['a', '-x'] |
| 632 |
successes = [ |
| 633 |
('', NS(x=None)), |
| 634 |
('-x a', NS(x='a')), |
| 635 |
] |
| 636 |
|
| 637 |
|
| 638 |
class TestOptionalsNargs1(ParserTestCase): |
| 639 |
"""Tests specifying 1 arg for an Optional""" |
| 640 |
|
| 641 |
argument_signatures = [Sig('-x', nargs=1)] |
| 642 |
failures = ['a', '-x'] |
| 643 |
successes = [ |
| 644 |
('', NS(x=None)), |
| 645 |
('-x a', NS(x=['a'])), |
| 646 |
] |
| 647 |
|
| 648 |
|
| 649 |
class TestOptionalsNargs3(ParserTestCase): |
| 650 |
"""Tests specifying 3 args for an Optional""" |
| 651 |
|
| 652 |
argument_signatures = [Sig('-x', nargs=3)] |
| 653 |
failures = ['a', '-x', '-x a', '-x a b', 'a -x', 'a -x b'] |
| 654 |
successes = [ |
| 655 |
('', NS(x=None)), |
| 656 |
('-x a b c', NS(x=['a', 'b', 'c'])), |
| 657 |
] |
| 658 |
|
| 659 |
|
| 660 |
class TestOptionalsNargsOptional(ParserTestCase): |
| 661 |
"""Tests specifying an Optional arg for an Optional""" |
| 662 |
|
| 663 |
argument_signatures = [ |
| 664 |
Sig('-w', nargs='?'), |
| 665 |
Sig('-x', nargs='?', const=42), |
| 666 |
Sig('-y', nargs='?', default='spam'), |
| 667 |
Sig('-z', nargs='?', type=int, const='42', default='84', choices=[1, 2]), |
| 668 |
] |
| 669 |
failures = ['2', '-z a', '-z 42', '-z 84'] |
| 670 |
successes = [ |
| 671 |
('', NS(w=None, x=None, y='spam', z=84)), |
| 672 |
('-w', NS(w=None, x=None, y='spam', z=84)), |
| 673 |
('-w 2', NS(w='2', x=None, y='spam', z=84)), |
| 674 |
('-x', NS(w=None, x=42, y='spam', z=84)), |
| 675 |
('-x 2', NS(w=None, x='2', y='spam', z=84)), |
| 676 |
('-y', NS(w=None, x=None, y=None, z=84)), |
| 677 |
('-y 2', NS(w=None, x=None, y='2', z=84)), |
| 678 |
('-z', NS(w=None, x=None, y='spam', z=42)), |
| 679 |
('-z 2', NS(w=None, x=None, y='spam', z=2)), |
| 680 |
] |
| 681 |
|
| 682 |
|
| 683 |
class TestOptionalsNargsZeroOrMore(ParserTestCase): |
| 684 |
"""Tests specifying args for an Optional that accepts zero or more""" |
| 685 |
|
| 686 |
argument_signatures = [ |
| 687 |
Sig('-x', nargs='*'), |
| 688 |
Sig('-y', nargs='*', default='spam'), |
| 689 |
] |
| 690 |
failures = ['a'] |
| 691 |
successes = [ |
| 692 |
('', NS(x=None, y='spam')), |
| 693 |
('-x', NS(x=[], y='spam')), |
| 694 |
('-x a', NS(x=['a'], y='spam')), |
| 695 |
('-x a b', NS(x=['a', 'b'], y='spam')), |
| 696 |
('-y', NS(x=None, y=[])), |
| 697 |
('-y a', NS(x=None, y=['a'])), |
| 698 |
('-y a b', NS(x=None, y=['a', 'b'])), |
| 699 |
] |
| 700 |
|
| 701 |
|
| 702 |
class TestOptionalsNargsOneOrMore(ParserTestCase): |
| 703 |
"""Tests specifying args for an Optional that accepts one or more""" |
| 704 |
|
| 705 |
argument_signatures = [ |
| 706 |
Sig('-x', nargs='+'), |
| 707 |
Sig('-y', nargs='+', default='spam'), |
| 708 |
] |
| 709 |
failures = ['a', '-x', '-y', 'a -x', 'a -y b'] |
| 710 |
successes = [ |
| 711 |
('', NS(x=None, y='spam')), |
| 712 |
('-x a', NS(x=['a'], y='spam')), |
| 713 |
('-x a b', NS(x=['a', 'b'], y='spam')), |
| 714 |
('-y a', NS(x=None, y=['a'])), |
| 715 |
('-y a b', NS(x=None, y=['a', 'b'])), |
| 716 |
] |
| 717 |
|
| 718 |
|
| 719 |
class TestOptionalsChoices(ParserTestCase): |
| 720 |
"""Tests specifying the choices for an Optional""" |
| 721 |
|
| 722 |
argument_signatures = [ |
| 723 |
Sig('-f', choices='abc'), |
| 724 |
Sig('-g', type=int, choices=range(5))] |
| 725 |
failures = ['a', '-f d', '-f ab', '-fad', '-ga', '-g 6'] |
| 726 |
successes = [ |
| 727 |
('', NS(f=None, g=None)), |
| 728 |
('-f a', NS(f='a', g=None)), |
| 729 |
('-f c', NS(f='c', g=None)), |
| 730 |
('-g 0', NS(f=None, g=0)), |
| 731 |
('-g 03', NS(f=None, g=3)), |
| 732 |
('-fb -g4', NS(f='b', g=4)), |
| 733 |
] |
| 734 |
|
| 735 |
|
| 736 |
class TestOptionalsRequired(ParserTestCase): |
| 737 |
"""Tests an optional action that is required""" |
| 738 |
|
| 739 |
argument_signatures = [ |
| 740 |
Sig('-x', type=int, required=True), |
| 741 |
] |
| 742 |
failures = ['a', ''] |
| 743 |
successes = [ |
| 744 |
('-x 1', NS(x=1)), |
| 745 |
('-x42', NS(x=42)), |
| 746 |
] |
| 747 |
|
| 748 |
|
| 749 |
class TestOptionalsActionStore(ParserTestCase): |
| 750 |
"""Tests the store action for an Optional""" |
| 751 |
|
| 752 |
argument_signatures = [Sig('-x', action='store')] |
| 753 |
failures = ['a', 'a -x'] |
| 754 |
successes = [ |
| 755 |
('', NS(x=None)), |
| 756 |
('-xfoo', NS(x='foo')), |
| 757 |
] |
| 758 |
|
| 759 |
|
| 760 |
class TestOptionalsActionStoreConst(ParserTestCase): |
| 761 |
"""Tests the store_const action for an Optional""" |
| 762 |
|
| 763 |
argument_signatures = [Sig('-y', action='store_const', const=object)] |
| 764 |
failures = ['a'] |
| 765 |
successes = [ |
| 766 |
('', NS(y=None)), |
| 767 |
('-y', NS(y=object)), |
| 768 |
] |
| 769 |
|
| 770 |
|
| 771 |
class TestOptionalsActionStoreFalse(ParserTestCase): |
| 772 |
"""Tests the store_false action for an Optional""" |
| 773 |
|
| 774 |
argument_signatures = [Sig('-z', action='store_false')] |
| 775 |
failures = ['a', '-za', '-z a'] |
| 776 |
successes = [ |
| 777 |
('', NS(z=True)), |
| 778 |
('-z', NS(z=False)), |
| 779 |
] |
| 780 |
|
| 781 |
|
| 782 |
class TestOptionalsActionStoreTrue(ParserTestCase): |
| 783 |
"""Tests the store_true action for an Optional""" |
| 784 |
|
| 785 |
argument_signatures = [Sig('--apple', action='store_true')] |
| 786 |
failures = ['a', '--apple=b', '--apple b'] |
| 787 |
successes = [ |
| 788 |
('', NS(apple=False)), |
| 789 |
('--apple', NS(apple=True)), |
| 790 |
] |
| 791 |
|
| 792 |
class TestBooleanOptionalAction(ParserTestCase): |
| 793 |
"""Tests BooleanOptionalAction""" |
| 794 |
|
| 795 |
argument_signatures = [Sig('--foo', action=argparse.BooleanOptionalAction)] |
| 796 |
failures = ['--foo bar', '--foo=bar'] |
| 797 |
successes = [ |
| 798 |
('', NS(foo=None)), |
| 799 |
('--foo', NS(foo=True)), |
| 800 |
('--no-foo', NS(foo=False)), |
| 801 |
('--foo --no-foo', NS(foo=False)), # useful for aliases |
| 802 |
('--no-foo --foo', NS(foo=True)), |
| 803 |
] |
| 804 |
|
| 805 |
def test_const(self): |
| 806 |
# See bpo-40862 |
| 807 |
parser = argparse.ArgumentParser() |
| 808 |
with self.assertRaises(TypeError) as cm: |
| 809 |
parser.add_argument('--foo', const=True, action=argparse.BooleanOptionalAction) |
| 810 |
|
| 811 |
self.assertIn("got an unexpected keyword argument 'const'", str(cm.exception)) |
| 812 |
|
| 813 |
def test_invalid_name(self): |
| 814 |
parser = argparse.ArgumentParser() |
| 815 |
with self.assertRaises(ValueError) as cm: |
| 816 |
parser.add_argument('--no-foo', action=argparse.BooleanOptionalAction) |
| 817 |
self.assertEqual(str(cm.exception), |
| 818 |
"invalid option name '--no-foo' for BooleanOptionalAction") |
| 819 |
|
| 820 |
class TestBooleanOptionalActionRequired(ParserTestCase): |
| 821 |
"""Tests BooleanOptionalAction required""" |
| 822 |
|
| 823 |
argument_signatures = [ |
| 824 |
Sig('--foo', required=True, action=argparse.BooleanOptionalAction) |
| 825 |
] |
| 826 |
failures = [''] |
| 827 |
successes = [ |
| 828 |
('--foo', NS(foo=True)), |
| 829 |
('--no-foo', NS(foo=False)), |
| 830 |
] |
| 831 |
|
| 832 |
class TestOptionalsActionAppend(ParserTestCase): |
| 833 |
"""Tests the append action for an Optional""" |
| 834 |
|
| 835 |
argument_signatures = [Sig('--baz', action='append')] |
| 836 |
failures = ['a', '--baz', 'a --baz', '--baz a b'] |
| 837 |
successes = [ |
| 838 |
('', NS(baz=None)), |
| 839 |
('--baz a', NS(baz=['a'])), |
| 840 |
('--baz a --baz b', NS(baz=['a', 'b'])), |
| 841 |
] |
| 842 |
|
| 843 |
|
| 844 |
class TestOptionalsActionAppendWithDefault(ParserTestCase): |
| 845 |
"""Tests the append action for an Optional""" |
| 846 |
|
| 847 |
argument_signatures = [Sig('--baz', action='append', default=['X'])] |
| 848 |
failures = ['a', '--baz', 'a --baz', '--baz a b'] |
| 849 |
successes = [ |
| 850 |
('', NS(baz=['X'])), |
| 851 |
('--baz a', NS(baz=['X', 'a'])), |
| 852 |
('--baz a --baz b', NS(baz=['X', 'a', 'b'])), |
| 853 |
] |
| 854 |
|
| 855 |
|
| 856 |
class TestConstActionsMissingConstKwarg(ParserTestCase): |
| 857 |
"""Tests that const gets default value of None when not provided""" |
| 858 |
|
| 859 |
argument_signatures = [ |
| 860 |
Sig('-f', action='append_const'), |
| 861 |
Sig('--foo', action='append_const'), |
| 862 |
Sig('-b', action='store_const'), |
| 863 |
Sig('--bar', action='store_const') |
| 864 |
] |
| 865 |
failures = ['-f v', '--foo=bar', '--foo bar'] |
| 866 |
successes = [ |
| 867 |
('', NS(f=None, foo=None, b=None, bar=None)), |
| 868 |
('-f', NS(f=[None], foo=None, b=None, bar=None)), |
| 869 |
('--foo', NS(f=None, foo=[None], b=None, bar=None)), |
| 870 |
('-b', NS(f=None, foo=None, b=None, bar=None)), |
| 871 |
('--bar', NS(f=None, foo=None, b=None, bar=None)), |
| 872 |
] |
| 873 |
|
| 874 |
|
| 875 |
class TestOptionalsActionAppendConst(ParserTestCase): |
| 876 |
"""Tests the append_const action for an Optional""" |
| 877 |
|
| 878 |
argument_signatures = [ |
| 879 |
Sig('-b', action='append_const', const=Exception), |
| 880 |
Sig('-c', action='append', dest='b'), |
| 881 |
] |
| 882 |
failures = ['a', '-c', 'a -c', '-bx', '-b x'] |
| 883 |
successes = [ |
| 884 |
('', NS(b=None)), |
| 885 |
('-b', NS(b=[Exception])), |
| 886 |
('-b -cx -b -cyz', NS(b=[Exception, 'x', Exception, 'yz'])), |
| 887 |
] |
| 888 |
|
| 889 |
|
| 890 |
class TestOptionalsActionAppendConstWithDefault(ParserTestCase): |
| 891 |
"""Tests the append_const action for an Optional""" |
| 892 |
|
| 893 |
argument_signatures = [ |
| 894 |
Sig('-b', action='append_const', const=Exception, default=['X']), |
| 895 |
Sig('-c', action='append', dest='b'), |
| 896 |
] |
| 897 |
failures = ['a', '-c', 'a -c', '-bx', '-b x'] |
| 898 |
successes = [ |
| 899 |
('', NS(b=['X'])), |
| 900 |
('-b', NS(b=['X', Exception])), |
| 901 |
('-b -cx -b -cyz', NS(b=['X', Exception, 'x', Exception, 'yz'])), |
| 902 |
] |
| 903 |
|
| 904 |
|
| 905 |
class TestOptionalsActionCount(ParserTestCase): |
| 906 |
"""Tests the count action for an Optional""" |
| 907 |
|
| 908 |
argument_signatures = [Sig('-x', action='count')] |
| 909 |
failures = ['a', '-x a', '-x b', '-x a -x b'] |
| 910 |
successes = [ |
| 911 |
('', NS(x=None)), |
| 912 |
('-x', NS(x=1)), |
| 913 |
] |
| 914 |
|
| 915 |
|
| 916 |
class TestOptionalsAllowLongAbbreviation(ParserTestCase): |
| 917 |
"""Allow long options to be abbreviated unambiguously""" |
| 918 |
|
| 919 |
argument_signatures = [ |
| 920 |
Sig('--foo'), |
| 921 |
Sig('--foobaz'), |
| 922 |
Sig('--fooble', action='store_true'), |
| 923 |
] |
| 924 |
failures = ['--foob 5', '--foob'] |
| 925 |
successes = [ |
| 926 |
('', NS(foo=None, foobaz=None, fooble=False)), |
| 927 |
('--foo 7', NS(foo='7', foobaz=None, fooble=False)), |
| 928 |
('--foo=7', NS(foo='7', foobaz=None, fooble=False)), |
| 929 |
('--fooba a', NS(foo=None, foobaz='a', fooble=False)), |
| 930 |
('--fooba=a', NS(foo=None, foobaz='a', fooble=False)), |
| 931 |
('--foobl --foo g', NS(foo='g', foobaz=None, fooble=True)), |
| 932 |
] |
| 933 |
|
| 934 |
|
| 935 |
class TestOptionalsDisallowLongAbbreviation(ParserTestCase): |
| 936 |
"""Do not allow abbreviations of long options at all""" |
| 937 |
|
| 938 |
parser_signature = Sig(allow_abbrev=False) |
| 939 |
argument_signatures = [ |
| 940 |
Sig('--foo'), |
| 941 |
Sig('--foodle', action='store_true'), |
| 942 |
Sig('--foonly'), |
| 943 |
] |
| 944 |
failures = ['-foon 3', '--foon 3', '--food', '--food --foo 2'] |
| 945 |
successes = [ |
| 946 |
('', NS(foo=None, foodle=False, foonly=None)), |
| 947 |
('--foo 3', NS(foo='3', foodle=False, foonly=None)), |
| 948 |
('--foonly 7 --foodle --foo 2', NS(foo='2', foodle=True, foonly='7')), |
| 949 |
] |
| 950 |
|
| 951 |
|
| 952 |
class TestOptionalsDisallowLongAbbreviationPrefixChars(ParserTestCase): |
| 953 |
"""Disallowing abbreviations works with alternative prefix characters""" |
| 954 |
|
| 955 |
parser_signature = Sig(prefix_chars='+', allow_abbrev=False) |
| 956 |
argument_signatures = [ |
| 957 |
Sig('++foo'), |
| 958 |
Sig('++foodle', action='store_true'), |
| 959 |
Sig('++foonly'), |
| 960 |
] |
| 961 |
failures = ['+foon 3', '++foon 3', '++food', '++food ++foo 2'] |
| 962 |
successes = [ |
| 963 |
('', NS(foo=None, foodle=False, foonly=None)), |
| 964 |
('++foo 3', NS(foo='3', foodle=False, foonly=None)), |
| 965 |
('++foonly 7 ++foodle ++foo 2', NS(foo='2', foodle=True, foonly='7')), |
| 966 |
] |
| 967 |
|
| 968 |
|
| 969 |
class TestOptionalsDisallowSingleDashLongAbbreviation(ParserTestCase): |
| 970 |
"""Do not allow abbreviations of long options at all""" |
| 971 |
|
| 972 |
parser_signature = Sig(allow_abbrev=False) |
| 973 |
argument_signatures = [ |
| 974 |
Sig('-foo'), |
| 975 |
Sig('-foodle', action='store_true'), |
| 976 |
Sig('-foonly'), |
| 977 |
] |
| 978 |
failures = ['-foon 3', '-food', '-food -foo 2'] |
| 979 |
successes = [ |
| 980 |
('', NS(foo=None, foodle=False, foonly=None)), |
| 981 |
('-foo 3', NS(foo='3', foodle=False, foonly=None)), |
| 982 |
('-foonly 7 -foodle -foo 2', NS(foo='2', foodle=True, foonly='7')), |
| 983 |
] |
| 984 |
|
| 985 |
|
| 986 |
class TestDisallowLongAbbreviationAllowsShortGrouping(ParserTestCase): |
| 987 |
"""Do not allow abbreviations of long options at all""" |
| 988 |
|
| 989 |
parser_signature = Sig(allow_abbrev=False) |
| 990 |
argument_signatures = [ |
| 991 |
Sig('-r'), |
| 992 |
Sig('-c', action='count'), |
| 993 |
] |
| 994 |
failures = ['-r', '-c -r'] |
| 995 |
successes = [ |
| 996 |
('', NS(r=None, c=None)), |
| 997 |
('-ra', NS(r='a', c=None)), |
| 998 |
('-rcc', NS(r='cc', c=None)), |
| 999 |
('-cc', NS(r=None, c=2)), |
| 1000 |
('-cc -ra', NS(r='a', c=2)), |
| 1001 |
('-ccrcc', NS(r='cc', c=2)), |
| 1002 |
] |
| 1003 |
|
| 1004 |
|
| 1005 |
class TestDisallowLongAbbreviationAllowsShortGroupingPrefix(ParserTestCase): |
| 1006 |
"""Short option grouping works with custom prefix and allow_abbrev=False""" |
| 1007 |
|
| 1008 |
parser_signature = Sig(prefix_chars='+', allow_abbrev=False) |
| 1009 |
argument_signatures = [ |
| 1010 |
Sig('+r'), |
| 1011 |
Sig('+c', action='count'), |
| 1012 |
] |
| 1013 |
failures = ['+r', '+c +r'] |
| 1014 |
successes = [ |
| 1015 |
('', NS(r=None, c=None)), |
| 1016 |
('+ra', NS(r='a', c=None)), |
| 1017 |
('+rcc', NS(r='cc', c=None)), |
| 1018 |
('+cc', NS(r=None, c=2)), |
| 1019 |
('+cc +ra', NS(r='a', c=2)), |
| 1020 |
('+ccrcc', NS(r='cc', c=2)), |
| 1021 |
] |
| 1022 |
|
| 1023 |
|
| 1024 |
class TestStrEnumChoices(TestCase): |
| 1025 |
class Color(StrEnum): |
| 1026 |
RED = "red" |
| 1027 |
GREEN = "green" |
| 1028 |
BLUE = "blue" |
| 1029 |
|
| 1030 |
def test_parse_enum_value(self): |
| 1031 |
parser = argparse.ArgumentParser() |
| 1032 |
parser.add_argument('--color', choices=self.Color) |
| 1033 |
args = parser.parse_args(['--color', 'red']) |
| 1034 |
self.assertEqual(args.color, self.Color.RED) |
| 1035 |
|
| 1036 |
@force_not_colorized |
| 1037 |
def test_help_message_contains_enum_choices(self): |
| 1038 |
parser = argparse.ArgumentParser() |
| 1039 |
parser.add_argument('--color', choices=self.Color, help='Choose a color') |
| 1040 |
self.assertIn('[--color {red,green,blue}]', parser.format_usage()) |
| 1041 |
self.assertIn(' --color {red,green,blue}', parser.format_help()) |
| 1042 |
|
| 1043 |
def test_invalid_enum_value_raises_error(self): |
| 1044 |
parser = argparse.ArgumentParser(exit_on_error=False) |
| 1045 |
parser.add_argument('--color', choices=self.Color) |
| 1046 |
self.assertRaisesRegex( |
| 1047 |
argparse.ArgumentError, |
| 1048 |
r"invalid choice: 'yellow' \(choose from 'red', 'green', 'blue'\)", |
| 1049 |
parser.parse_args, |
| 1050 |
['--color', 'yellow'], |
| 1051 |
) |
| 1052 |
|
| 1053 |
# ================ |
| 1054 |
# Positional tests |
| 1055 |
# ================ |
| 1056 |
|
| 1057 |
class TestPositionalsNargsNone(ParserTestCase): |
| 1058 |
"""Test a Positional that doesn't specify nargs""" |
| 1059 |
|
| 1060 |
argument_signatures = [Sig('foo')] |
| 1061 |
failures = ['', '-x', 'a b'] |
| 1062 |
successes = [ |
| 1063 |
('a', NS(foo='a')), |
| 1064 |
] |
| 1065 |
|
| 1066 |
|
| 1067 |
class TestPositionalsNargs1(ParserTestCase): |
| 1068 |
"""Test a Positional that specifies an nargs of 1""" |
| 1069 |
|
| 1070 |
argument_signatures = [Sig('foo', nargs=1)] |
| 1071 |
failures = ['', '-x', 'a b'] |
| 1072 |
successes = [ |
| 1073 |
('a', NS(foo=['a'])), |
| 1074 |
] |
| 1075 |
|
| 1076 |
|
| 1077 |
class TestPositionalsNargs2(ParserTestCase): |
| 1078 |
"""Test a Positional that specifies an nargs of 2""" |
| 1079 |
|
| 1080 |
argument_signatures = [Sig('foo', nargs=2)] |
| 1081 |
failures = ['', 'a', '-x', 'a b c'] |
| 1082 |
successes = [ |
| 1083 |
('a b', NS(foo=['a', 'b'])), |
| 1084 |
] |
| 1085 |
|
| 1086 |
|
| 1087 |
class TestPositionalsNargsZeroOrMore(ParserTestCase): |
| 1088 |
"""Test a Positional that specifies unlimited nargs""" |
| 1089 |
|
| 1090 |
argument_signatures = [Sig('foo', nargs='*')] |
| 1091 |
failures = ['-x'] |
| 1092 |
successes = [ |
| 1093 |
('', NS(foo=[])), |
| 1094 |
('a', NS(foo=['a'])), |
| 1095 |
('a b', NS(foo=['a', 'b'])), |
| 1096 |
] |
| 1097 |
|
| 1098 |
|
| 1099 |
class TestPositionalsNargsZeroOrMoreDefault(ParserTestCase): |
| 1100 |
"""Test a Positional that specifies unlimited nargs and a default""" |
| 1101 |
|
| 1102 |
argument_signatures = [Sig('foo', nargs='*', default='bar', choices=['a', 'b'])] |
| 1103 |
failures = ['-x', 'bar', 'a c'] |
| 1104 |
successes = [ |
| 1105 |
('', NS(foo='bar')), |
| 1106 |
('a', NS(foo=['a'])), |
| 1107 |
('a b', NS(foo=['a', 'b'])), |
| 1108 |
] |
| 1109 |
|
| 1110 |
|
| 1111 |
class TestPositionalsNargsOneOrMore(ParserTestCase): |
| 1112 |
"""Test a Positional that specifies one or more nargs""" |
| 1113 |
|
| 1114 |
argument_signatures = [Sig('foo', nargs='+')] |
| 1115 |
failures = ['', '-x'] |
| 1116 |
successes = [ |
| 1117 |
('a', NS(foo=['a'])), |
| 1118 |
('a b', NS(foo=['a', 'b'])), |
| 1119 |
] |
| 1120 |
|
| 1121 |
|
| 1122 |
class TestPositionalsNargsOptional(ParserTestCase): |
| 1123 |
"""Tests an Optional Positional""" |
| 1124 |
|
| 1125 |
argument_signatures = [Sig('foo', nargs='?')] |
| 1126 |
failures = ['-x', 'a b'] |
| 1127 |
successes = [ |
| 1128 |
('', NS(foo=None)), |
| 1129 |
('a', NS(foo='a')), |
| 1130 |
] |
| 1131 |
|
| 1132 |
|
| 1133 |
class TestPositionalsNargsOptionalDefault(ParserTestCase): |
| 1134 |
"""Tests an Optional Positional with a default value""" |
| 1135 |
|
| 1136 |
argument_signatures = [Sig('foo', nargs='?', default=42, choices=['a', 'b'])] |
| 1137 |
failures = ['-x', 'a b', '42'] |
| 1138 |
successes = [ |
| 1139 |
('', NS(foo=42)), |
| 1140 |
('a', NS(foo='a')), |
| 1141 |
] |
| 1142 |
|
| 1143 |
|
| 1144 |
class TestPositionalsNargsOptionalConvertedDefault(ParserTestCase): |
| 1145 |
"""Tests an Optional Positional with a default value |
| 1146 |
that needs to be converted to the appropriate type. |
| 1147 |
""" |
| 1148 |
|
| 1149 |
argument_signatures = [ |
| 1150 |
Sig('foo', nargs='?', type=int, default='42', choices=[1, 2]), |
| 1151 |
] |
| 1152 |
failures = ['-x', 'a b', '1 2', '42'] |
| 1153 |
successes = [ |
| 1154 |
('', NS(foo=42)), |
| 1155 |
('1', NS(foo=1)), |
| 1156 |
] |
| 1157 |
|
| 1158 |
|
| 1159 |
class TestPositionalsNargsNoneNone(ParserTestCase): |
| 1160 |
"""Test two Positionals that don't specify nargs""" |
| 1161 |
|
| 1162 |
argument_signatures = [Sig('foo'), Sig('bar')] |
| 1163 |
failures = ['', '-x', 'a', 'a b c'] |
| 1164 |
successes = [ |
| 1165 |
('a b', NS(foo='a', bar='b')), |
| 1166 |
] |
| 1167 |
|
| 1168 |
|
| 1169 |
class TestPositionalsNargsNone1(ParserTestCase): |
| 1170 |
"""Test a Positional with no nargs followed by one with 1""" |
| 1171 |
|
| 1172 |
argument_signatures = [Sig('foo'), Sig('bar', nargs=1)] |
| 1173 |
failures = ['', '--foo', 'a', 'a b c'] |
| 1174 |
successes = [ |
| 1175 |
('a b', NS(foo='a', bar=['b'])), |
| 1176 |
] |
| 1177 |
|
| 1178 |
|
| 1179 |
class TestPositionalsNargs2None(ParserTestCase): |
| 1180 |
"""Test a Positional with 2 nargs followed by one with none""" |
| 1181 |
|
| 1182 |
argument_signatures = [Sig('foo', nargs=2), Sig('bar')] |
| 1183 |
failures = ['', '--foo', 'a', 'a b', 'a b c d'] |
| 1184 |
successes = [ |
| 1185 |
('a b c', NS(foo=['a', 'b'], bar='c')), |
| 1186 |
] |
| 1187 |
|
| 1188 |
|
| 1189 |
class TestPositionalsNargsNoneZeroOrMore(ParserTestCase): |
| 1190 |
"""Test a Positional with no nargs followed by one with unlimited""" |
| 1191 |
|
| 1192 |
argument_signatures = [Sig('-x'), Sig('foo'), Sig('bar', nargs='*')] |
| 1193 |
failures = ['', '--foo', 'a b -x X c'] |
| 1194 |
successes = [ |
| 1195 |
('a', NS(x=None, foo='a', bar=[])), |
| 1196 |
('a b', NS(x=None, foo='a', bar=['b'])), |
| 1197 |
('a b c', NS(x=None, foo='a', bar=['b', 'c'])), |
| 1198 |
('-x X a', NS(x='X', foo='a', bar=[])), |
| 1199 |
('a -x X', NS(x='X', foo='a', bar=[])), |
| 1200 |
('-x X a b', NS(x='X', foo='a', bar=['b'])), |
| 1201 |
('a -x X b', NS(x='X', foo='a', bar=['b'])), |
| 1202 |
('a b -x X', NS(x='X', foo='a', bar=['b'])), |
| 1203 |
('-x X a b c', NS(x='X', foo='a', bar=['b', 'c'])), |
| 1204 |
('a -x X b c', NS(x='X', foo='a', bar=['b', 'c'])), |
| 1205 |
('a b c -x X', NS(x='X', foo='a', bar=['b', 'c'])), |
| 1206 |
] |
| 1207 |
|
| 1208 |
|
| 1209 |
class TestPositionalsNargsNoneOneOrMore(ParserTestCase): |
| 1210 |
"""Test a Positional with no nargs followed by one with one or more""" |
| 1211 |
|
| 1212 |
argument_signatures = [Sig('-x'), Sig('foo'), Sig('bar', nargs='+')] |
| 1213 |
failures = ['', '--foo', 'a', 'a b -x X c'] |
| 1214 |
successes = [ |
| 1215 |
('a b', NS(x=None, foo='a', bar=['b'])), |
| 1216 |
('a b c', NS(x=None, foo='a', bar=['b', 'c'])), |
| 1217 |
('-x X a b', NS(x='X', foo='a', bar=['b'])), |
| 1218 |
('a -x X b', NS(x='X', foo='a', bar=['b'])), |
| 1219 |
('a b -x X', NS(x='X', foo='a', bar=['b'])), |
| 1220 |
('-x X a b c', NS(x='X', foo='a', bar=['b', 'c'])), |
| 1221 |
('a -x X b c', NS(x='X', foo='a', bar=['b', 'c'])), |
| 1222 |
('a b c -x X', NS(x='X', foo='a', bar=['b', 'c'])), |
| 1223 |
] |
| 1224 |
|
| 1225 |
|
| 1226 |
class TestPositionalsNargsNoneOptional(ParserTestCase): |
| 1227 |
"""Test a Positional with no nargs followed by one with an Optional""" |
| 1228 |
|
| 1229 |
argument_signatures = [Sig('-x'), Sig('foo'), Sig('bar', nargs='?')] |
| 1230 |
failures = ['', '--foo', 'a b c'] |
| 1231 |
successes = [ |
| 1232 |
('a', NS(x=None, foo='a', bar=None)), |
| 1233 |
('a b', NS(x=None, foo='a', bar='b')), |
| 1234 |
('-x X a', NS(x='X', foo='a', bar=None)), |
| 1235 |
('a -x X', NS(x='X', foo='a', bar=None)), |
| 1236 |
('-x X a b', NS(x='X', foo='a', bar='b')), |
| 1237 |
('a -x X b', NS(x='X', foo='a', bar='b')), |
| 1238 |
('a b -x X', NS(x='X', foo='a', bar='b')), |
| 1239 |
] |
| 1240 |
|
| 1241 |
|
| 1242 |
class TestPositionalsNargsZeroOrMoreNone(ParserTestCase): |
| 1243 |
"""Test a Positional with unlimited nargs followed by one with none""" |
| 1244 |
|
| 1245 |
argument_signatures = [Sig('-x'), Sig('foo', nargs='*'), Sig('bar')] |
| 1246 |
failures = ['', '--foo', 'a -x X b', 'a -x X b c', 'a b -x X c'] |
| 1247 |
successes = [ |
| 1248 |
('a', NS(x=None, foo=[], bar='a')), |
| 1249 |
('a b', NS(x=None, foo=['a'], bar='b')), |
| 1250 |
('a b c', NS(x=None, foo=['a', 'b'], bar='c')), |
| 1251 |
('-x X a', NS(x='X', foo=[], bar='a')), |
| 1252 |
('a -x X', NS(x='X', foo=[], bar='a')), |
| 1253 |
('-x X a b', NS(x='X', foo=['a'], bar='b')), |
| 1254 |
('a b -x X', NS(x='X', foo=['a'], bar='b')), |
| 1255 |
('-x X a b c', NS(x='X', foo=['a', 'b'], bar='c')), |
| 1256 |
('a b c -x X', NS(x='X', foo=['a', 'b'], bar='c')), |
| 1257 |
] |
| 1258 |
|
| 1259 |
|
| 1260 |
class TestPositionalsNargsOneOrMoreNone(ParserTestCase): |
| 1261 |
"""Test a Positional with one or more nargs followed by one with none""" |
| 1262 |
|
| 1263 |
argument_signatures = [Sig('-x'), Sig('foo', nargs='+'), Sig('bar')] |
| 1264 |
failures = ['', '--foo', 'a', 'a -x X b c', 'a b -x X c'] |
| 1265 |
successes = [ |
| 1266 |
('a b', NS(x=None, foo=['a'], bar='b')), |
| 1267 |
('a b c', NS(x=None, foo=['a', 'b'], bar='c')), |
| 1268 |
('-x X a b', NS(x='X', foo=['a'], bar='b')), |
| 1269 |
('a -x X b', NS(x='X', foo=['a'], bar='b')), |
| 1270 |
('a b -x X', NS(x='X', foo=['a'], bar='b')), |
| 1271 |
('-x X a b c', NS(x='X', foo=['a', 'b'], bar='c')), |
| 1272 |
('a b c -x X', NS(x='X', foo=['a', 'b'], bar='c')), |
| 1273 |
] |
| 1274 |
|
| 1275 |
|
| 1276 |
class TestPositionalsNargsOptionalNone(ParserTestCase): |
| 1277 |
"""Test a Positional with an Optional nargs followed by one with none""" |
| 1278 |
|
| 1279 |
argument_signatures = [Sig('foo', nargs='?', default=42), Sig('bar')] |
| 1280 |
failures = ['', '--foo', 'a b c'] |
| 1281 |
successes = [ |
| 1282 |
('a', NS(foo=42, bar='a')), |
| 1283 |
('a b', NS(foo='a', bar='b')), |
| 1284 |
] |
| 1285 |
|
| 1286 |
|
| 1287 |
class TestPositionalsNargs2ZeroOrMore(ParserTestCase): |
| 1288 |
"""Test a Positional with 2 nargs followed by one with unlimited""" |
| 1289 |
|
| 1290 |
argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='*')] |
| 1291 |
failures = ['', '--foo', 'a'] |
| 1292 |
successes = [ |
| 1293 |
('a b', NS(foo=['a', 'b'], bar=[])), |
| 1294 |
('a b c', NS(foo=['a', 'b'], bar=['c'])), |
| 1295 |
] |
| 1296 |
|
| 1297 |
|
| 1298 |
class TestPositionalsNargs2OneOrMore(ParserTestCase): |
| 1299 |
"""Test a Positional with 2 nargs followed by one with one or more""" |
| 1300 |
|
| 1301 |
argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='+')] |
| 1302 |
failures = ['', '--foo', 'a', 'a b'] |
| 1303 |
successes = [ |
| 1304 |
('a b c', NS(foo=['a', 'b'], bar=['c'])), |
| 1305 |
] |
| 1306 |
|
| 1307 |
|
| 1308 |
class TestPositionalsNargs2Optional(ParserTestCase): |
| 1309 |
"""Test a Positional with 2 nargs followed by one optional""" |
| 1310 |
|
| 1311 |
argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='?')] |
| 1312 |
failures = ['', '--foo', 'a', 'a b c d'] |
| 1313 |
successes = [ |
| 1314 |
('a b', NS(foo=['a', 'b'], bar=None)), |
| 1315 |
('a b c', NS(foo=['a', 'b'], bar='c')), |
| 1316 |
] |
| 1317 |
|
| 1318 |
|
| 1319 |
class TestPositionalsNargsZeroOrMore1(ParserTestCase): |
| 1320 |
"""Test a Positional with unlimited nargs followed by one with 1""" |
| 1321 |
|
| 1322 |
argument_signatures = [Sig('foo', nargs='*'), Sig('bar', nargs=1)] |
| 1323 |
failures = ['', '--foo', ] |
| 1324 |
successes = [ |
| 1325 |
('a', NS(foo=[], bar=['a'])), |
| 1326 |
('a b', NS(foo=['a'], bar=['b'])), |
| 1327 |
('a b c', NS(foo=['a', 'b'], bar=['c'])), |
| 1328 |
] |
| 1329 |
|
| 1330 |
|
| 1331 |
class TestPositionalsNargsOneOrMore1(ParserTestCase): |
| 1332 |
"""Test a Positional with one or more nargs followed by one with 1""" |
| 1333 |
|
| 1334 |
argument_signatures = [Sig('foo', nargs='+'), Sig('bar', nargs=1)] |
| 1335 |
failures = ['', '--foo', 'a'] |
| 1336 |
successes = [ |
| 1337 |
('a b', NS(foo=['a'], bar=['b'])), |
| 1338 |
('a b c', NS(foo=['a', 'b'], bar=['c'])), |
| 1339 |
] |
| 1340 |
|
| 1341 |
|
| 1342 |
class TestPositionalsNargsOptional1(ParserTestCase): |
| 1343 |
"""Test a Positional with an Optional nargs followed by one with 1""" |
| 1344 |
|
| 1345 |
argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs=1)] |
| 1346 |
failures = ['', '--foo', 'a b c'] |
| 1347 |
successes = [ |
| 1348 |
('a', NS(foo=None, bar=['a'])), |
| 1349 |
('a b', NS(foo='a', bar=['b'])), |
| 1350 |
] |
| 1351 |
|
| 1352 |
|
| 1353 |
class TestPositionalsNargsNoneZeroOrMore1(ParserTestCase): |
| 1354 |
"""Test three Positionals: no nargs, unlimited nargs and 1 nargs""" |
| 1355 |
|
| 1356 |
argument_signatures = [ |
| 1357 |
Sig('-x'), |
| 1358 |
Sig('foo'), |
| 1359 |
Sig('bar', nargs='*'), |
| 1360 |
Sig('baz', nargs=1), |
| 1361 |
] |
| 1362 |
failures = ['', '--foo', 'a', 'a b -x X c'] |
| 1363 |
successes = [ |
| 1364 |
('a b', NS(x=None, foo='a', bar=[], baz=['b'])), |
| 1365 |
('a b c', NS(x=None, foo='a', bar=['b'], baz=['c'])), |
| 1366 |
('-x X a b', NS(x='X', foo='a', bar=[], baz=['b'])), |
| 1367 |
('a -x X b', NS(x='X', foo='a', bar=[], baz=['b'])), |
| 1368 |
('a b -x X', NS(x='X', foo='a', bar=[], baz=['b'])), |
| 1369 |
('-x X a b c', NS(x='X', foo='a', bar=['b'], baz=['c'])), |
| 1370 |
('a -x X b c', NS(x='X', foo='a', bar=['b'], baz=['c'])), |
| 1371 |
('a b c -x X', NS(x='X', foo='a', bar=['b'], baz=['c'])), |
| 1372 |
] |
| 1373 |
|
| 1374 |
|
| 1375 |
class TestPositionalsNargsNoneOneOrMore1(ParserTestCase): |
| 1376 |
"""Test three Positionals: no nargs, one or more nargs and 1 nargs""" |
| 1377 |
|
| 1378 |
argument_signatures = [ |
| 1379 |
Sig('-x'), |
| 1380 |
Sig('foo'), |
| 1381 |
Sig('bar', nargs='+'), |
| 1382 |
Sig('baz', nargs=1), |
| 1383 |
] |
| 1384 |
failures = ['', '--foo', 'a', 'b', 'a b -x X c d', 'a b c -x X d'] |
| 1385 |
successes = [ |
| 1386 |
('a b c', NS(x=None, foo='a', bar=['b'], baz=['c'])), |
| 1387 |
('a b c d', NS(x=None, foo='a', bar=['b', 'c'], baz=['d'])), |
| 1388 |
('-x X a b c', NS(x='X', foo='a', bar=['b'], baz=['c'])), |
| 1389 |
('a -x X b c', NS(x='X', foo='a', bar=['b'], baz=['c'])), |
| 1390 |
('a b -x X c', NS(x='X', foo='a', bar=['b'], baz=['c'])), |
| 1391 |
('a b c -x X', NS(x='X', foo='a', bar=['b'], baz=['c'])), |
| 1392 |
('-x X a b c d', NS(x='X', foo='a', bar=['b', 'c'], baz=['d'])), |
| 1393 |
('a -x X b c d', NS(x='X', foo='a', bar=['b', 'c'], baz=['d'])), |
| 1394 |
('a b c d -x X', NS(x='X', foo='a', bar=['b', 'c'], baz=['d'])), |
| 1395 |
] |
| 1396 |
|
| 1397 |
|
| 1398 |
class TestPositionalsNargsNoneOptional1(ParserTestCase): |
| 1399 |
"""Test three Positionals: no nargs, optional narg and 1 nargs""" |
| 1400 |
|
| 1401 |
argument_signatures = [ |
| 1402 |
Sig('-x'), |
| 1403 |
Sig('foo'), |
| 1404 |
Sig('bar', nargs='?', default=0.625), |
| 1405 |
Sig('baz', nargs=1), |
| 1406 |
] |
| 1407 |
failures = ['', '--foo', 'a', 'a b -x X c'] |
| 1408 |
successes = [ |
| 1409 |
('a b', NS(x=None, foo='a', bar=0.625, baz=['b'])), |
| 1410 |
('a b c', NS(x=None, foo='a', bar='b', baz=['c'])), |
| 1411 |
('-x X a b', NS(x='X', foo='a', bar=0.625, baz=['b'])), |
| 1412 |
('a -x X b', NS(x='X', foo='a', bar=0.625, baz=['b'])), |
| 1413 |
('a b -x X', NS(x='X', foo='a', bar=0.625, baz=['b'])), |
| 1414 |
('-x X a b c', NS(x='X', foo='a', bar='b', baz=['c'])), |
| 1415 |
('a -x X b c', NS(x='X', foo='a', bar='b', baz=['c'])), |
| 1416 |
('a b c -x X', NS(x='X', foo='a', bar='b', baz=['c'])), |
| 1417 |
] |
| 1418 |
|
| 1419 |
|
| 1420 |
class TestPositionalsNargsOptionalOptional(ParserTestCase): |
| 1421 |
"""Test two optional nargs""" |
| 1422 |
|
| 1423 |
argument_signatures = [ |
| 1424 |
Sig('foo', nargs='?'), |
| 1425 |
Sig('bar', nargs='?', default=42), |
| 1426 |
] |
| 1427 |
failures = ['--foo', 'a b c'] |
| 1428 |
successes = [ |
| 1429 |
('', NS(foo=None, bar=42)), |
| 1430 |
('a', NS(foo='a', bar=42)), |
| 1431 |
('a b', NS(foo='a', bar='b')), |
| 1432 |
] |
| 1433 |
|
| 1434 |
|
| 1435 |
class TestPositionalsNargsOptionalZeroOrMore(ParserTestCase): |
| 1436 |
"""Test an Optional narg followed by unlimited nargs""" |
| 1437 |
|
| 1438 |
argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs='*')] |
| 1439 |
failures = ['--foo'] |
| 1440 |
successes = [ |
| 1441 |
('', NS(foo=None, bar=[])), |
| 1442 |
('a', NS(foo='a', bar=[])), |
| 1443 |
('a b', NS(foo='a', bar=['b'])), |
| 1444 |
('a b c', NS(foo='a', bar=['b', 'c'])), |
| 1445 |
] |
| 1446 |
|
| 1447 |
|
| 1448 |
class TestPositionalsNargsOptionalOneOrMore(ParserTestCase): |
| 1449 |
"""Test an Optional narg followed by one or more nargs""" |
| 1450 |
|
| 1451 |
argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs='+')] |
| 1452 |
failures = ['', '--foo'] |
| 1453 |
successes = [ |
| 1454 |
('a', NS(foo=None, bar=['a'])), |
| 1455 |
('a b', NS(foo='a', bar=['b'])), |
| 1456 |
('a b c', NS(foo='a', bar=['b', 'c'])), |
| 1457 |
] |
| 1458 |
|
| 1459 |
|
| 1460 |
class TestPositionalsChoicesString(ParserTestCase): |
| 1461 |
"""Test a set of single-character choices""" |
| 1462 |
|
| 1463 |
argument_signatures = [Sig('spam', choices=set('abcdefg'))] |
| 1464 |
failures = ['', '--foo', 'h', '42', 'ef'] |
| 1465 |
successes = [ |
| 1466 |
('a', NS(spam='a')), |
| 1467 |
('g', NS(spam='g')), |
| 1468 |
] |
| 1469 |
|
| 1470 |
|
| 1471 |
class TestPositionalsChoicesInt(ParserTestCase): |
| 1472 |
"""Test a set of integer choices""" |
| 1473 |
|
| 1474 |
argument_signatures = [Sig('spam', type=int, choices=range(20))] |
| 1475 |
failures = ['', '--foo', 'h', '42', 'ef'] |
| 1476 |
successes = [ |
| 1477 |
('4', NS(spam=4)), |
| 1478 |
('15', NS(spam=15)), |
| 1479 |
] |
| 1480 |
|
| 1481 |
|
| 1482 |
class TestPositionalsActionAppend(ParserTestCase): |
| 1483 |
"""Test the 'append' action""" |
| 1484 |
|
| 1485 |
argument_signatures = [ |
| 1486 |
Sig('spam', action='append'), |
| 1487 |
Sig('spam', action='append', nargs=2), |
| 1488 |
] |
| 1489 |
failures = ['', '--foo', 'a', 'a b', 'a b c d'] |
| 1490 |
successes = [ |
| 1491 |
('a b c', NS(spam=['a', ['b', 'c']])), |
| 1492 |
] |
| 1493 |
|
| 1494 |
|
| 1495 |
class TestPositionalsActionExtend(ParserTestCase): |
| 1496 |
"""Test the 'extend' action""" |
| 1497 |
|
| 1498 |
argument_signatures = [ |
| 1499 |
Sig('spam', action='extend'), |
| 1500 |
Sig('spam', action='extend', nargs=2), |
| 1501 |
] |
| 1502 |
failures = ['', '--foo', 'a', 'a b', 'a b c d'] |
| 1503 |
successes = [ |
| 1504 |
('a b c', NS(spam=['a', 'b', 'c'])), |
| 1505 |
] |
| 1506 |
|
| 1507 |
# ======================================== |
| 1508 |
# Combined optionals and positionals tests |
| 1509 |
# ======================================== |
| 1510 |
|
| 1511 |
class TestOptionalsNumericAndPositionals(ParserTestCase): |
| 1512 |
"""Tests negative number args when numeric options are present""" |
| 1513 |
|
| 1514 |
argument_signatures = [ |
| 1515 |
Sig('x', nargs='?'), |
| 1516 |
Sig('-4', dest='y', action='store_true'), |
| 1517 |
] |
| 1518 |
failures = ['-2', '-315'] |
| 1519 |
successes = [ |
| 1520 |
('', NS(x=None, y=False)), |
| 1521 |
('a', NS(x='a', y=False)), |
| 1522 |
('-4', NS(x=None, y=True)), |
| 1523 |
('-4 a', NS(x='a', y=True)), |
| 1524 |
] |
| 1525 |
|
| 1526 |
|
| 1527 |
class TestOptionalsAlmostNumericAndPositionals(ParserTestCase): |
| 1528 |
"""Tests negative number args when almost numeric options are present""" |
| 1529 |
|
| 1530 |
argument_signatures = [ |
| 1531 |
Sig('x', nargs='?'), |
| 1532 |
Sig('-k4', dest='y', action='store_true'), |
| 1533 |
] |
| 1534 |
failures = ['-k3'] |
| 1535 |
successes = [ |
| 1536 |
('', NS(x=None, y=False)), |
| 1537 |
('-2', NS(x='-2', y=False)), |
| 1538 |
('a', NS(x='a', y=False)), |
| 1539 |
('-k4', NS(x=None, y=True)), |
| 1540 |
('-k4 a', NS(x='a', y=True)), |
| 1541 |
] |
| 1542 |
|
| 1543 |
|
| 1544 |
class TestOptionalsAndPositionalsAppend(ParserTestCase): |
| 1545 |
argument_signatures = [ |
| 1546 |
Sig('foo', nargs='*', action='append'), |
| 1547 |
Sig('--bar'), |
| 1548 |
] |
| 1549 |
failures = ['-foo'] |
| 1550 |
successes = [ |
| 1551 |
('a b', NS(foo=[['a', 'b']], bar=None)), |
| 1552 |
('--bar a b', NS(foo=[['b']], bar='a')), |
| 1553 |
('a b --bar c', NS(foo=[['a', 'b']], bar='c')), |
| 1554 |
] |
| 1555 |
|
| 1556 |
|
| 1557 |
class TestOptionalsAndPositionalsExtend(ParserTestCase): |
| 1558 |
argument_signatures = [ |
| 1559 |
Sig('foo', nargs='*', action='extend'), |
| 1560 |
Sig('--bar'), |
| 1561 |
] |
| 1562 |
failures = ['-foo'] |
| 1563 |
successes = [ |
| 1564 |
('a b', NS(foo=['a', 'b'], bar=None)), |
| 1565 |
('--bar a b', NS(foo=['b'], bar='a')), |
| 1566 |
('a b --bar c', NS(foo=['a', 'b'], bar='c')), |
| 1567 |
] |
| 1568 |
|
| 1569 |
|
| 1570 |
class TestEmptyAndSpaceContainingArguments(ParserTestCase): |
| 1571 |
|
| 1572 |
argument_signatures = [ |
| 1573 |
Sig('x', nargs='?'), |
| 1574 |
Sig('-y', '--yyy', dest='y'), |
| 1575 |
] |
| 1576 |
failures = ['-y'] |
| 1577 |
successes = [ |
| 1578 |
([''], NS(x='', y=None)), |
| 1579 |
(['a badger'], NS(x='a badger', y=None)), |
| 1580 |
(['-a badger'], NS(x='-a badger', y=None)), |
| 1581 |
(['-y', ''], NS(x=None, y='')), |
| 1582 |
(['-y', 'a badger'], NS(x=None, y='a badger')), |
| 1583 |
(['-y', '-a badger'], NS(x=None, y='-a badger')), |
| 1584 |
(['--yyy=a badger'], NS(x=None, y='a badger')), |
| 1585 |
(['--yyy=-a badger'], NS(x=None, y='-a badger')), |
| 1586 |
] |
| 1587 |
|
| 1588 |
|
| 1589 |
class TestPrefixCharacterOnlyArguments(ParserTestCase): |
| 1590 |
|
| 1591 |
parser_signature = Sig(prefix_chars='-+') |
| 1592 |
argument_signatures = [ |
| 1593 |
Sig('-', dest='x', nargs='?', const='badger'), |
| 1594 |
Sig('+', dest='y', type=int, default=42), |
| 1595 |
Sig('-+-', dest='z', action='store_true'), |
| 1596 |
] |
| 1597 |
failures = ['-y', '+ -'] |
| 1598 |
successes = [ |
| 1599 |
('', NS(x=None, y=42, z=False)), |
| 1600 |
('-', NS(x='badger', y=42, z=False)), |
| 1601 |
('- X', NS(x='X', y=42, z=False)), |
| 1602 |
('+ -3', NS(x=None, y=-3, z=False)), |
| 1603 |
('-+-', NS(x=None, y=42, z=True)), |
| 1604 |
('- ===', NS(x='===', y=42, z=False)), |
| 1605 |
] |
| 1606 |
|
| 1607 |
|
| 1608 |
class TestNargsZeroOrMore(ParserTestCase): |
| 1609 |
"""Tests specifying args for an Optional that accepts zero or more""" |
| 1610 |
|
| 1611 |
argument_signatures = [Sig('-x', nargs='*'), Sig('y', nargs='*')] |
| 1612 |
failures = [] |
| 1613 |
successes = [ |
| 1614 |
('', NS(x=None, y=[])), |
| 1615 |
('-x', NS(x=[], y=[])), |
| 1616 |
('-x a', NS(x=['a'], y=[])), |
| 1617 |
('-x a -- b', NS(x=['a'], y=['b'])), |
| 1618 |
('a', NS(x=None, y=['a'])), |
| 1619 |
('a -x', NS(x=[], y=['a'])), |
| 1620 |
('a -x b', NS(x=['b'], y=['a'])), |
| 1621 |
] |
| 1622 |
|
| 1623 |
|
| 1624 |
class TestNargsRemainder(ParserTestCase): |
| 1625 |
"""Tests specifying a positional with nargs=REMAINDER""" |
| 1626 |
|
| 1627 |
argument_signatures = [Sig('x'), Sig('y', nargs='...'), Sig('-z')] |
| 1628 |
failures = ['', '-z', '-z Z'] |
| 1629 |
successes = [ |
| 1630 |
('X', NS(x='X', y=[], z=None)), |
| 1631 |
('-z Z X', NS(x='X', y=[], z='Z')), |
| 1632 |
('-z Z X A B', NS(x='X', y=['A', 'B'], z='Z')), |
| 1633 |
('X -z Z A B', NS(x='X', y=['-z', 'Z', 'A', 'B'], z=None)), |
| 1634 |
('X A -z Z B', NS(x='X', y=['A', '-z', 'Z', 'B'], z=None)), |
| 1635 |
('X A B -z Z', NS(x='X', y=['A', 'B', '-z', 'Z'], z=None)), |
| 1636 |
('X Y --foo', NS(x='X', y=['Y', '--foo'], z=None)), |
| 1637 |
] |
| 1638 |
|
| 1639 |
|
| 1640 |
class TestOptionLike(ParserTestCase): |
| 1641 |
"""Tests options that may or may not be arguments""" |
| 1642 |
|
| 1643 |
argument_signatures = [ |
| 1644 |
Sig('-x', type=float), |
| 1645 |
Sig('-3', type=float, dest='y'), |
| 1646 |
Sig('z', nargs='*'), |
| 1647 |
] |
| 1648 |
failures = ['-x', '-y2.5', '-xa', '-x -a', |
| 1649 |
'-x -3', '-x -3.5', '-3 -3.5', |
| 1650 |
'-x -2.5', '-x -2.5 a', '-3 -.5', |
| 1651 |
'a x -1', '-x -1 a', '-3 -1 a'] |
| 1652 |
successes = [ |
| 1653 |
('', NS(x=None, y=None, z=[])), |
| 1654 |
('-x 2.5', NS(x=2.5, y=None, z=[])), |
| 1655 |
('-x 2.5 a', NS(x=2.5, y=None, z=['a'])), |
| 1656 |
('-3.5', NS(x=None, y=0.5, z=[])), |
| 1657 |
('-3-.5', NS(x=None, y=-0.5, z=[])), |
| 1658 |
('-3 .5', NS(x=None, y=0.5, z=[])), |
| 1659 |
('a -3.5', NS(x=None, y=0.5, z=['a'])), |
| 1660 |
('a', NS(x=None, y=None, z=['a'])), |
| 1661 |
('a -x 1', NS(x=1.0, y=None, z=['a'])), |
| 1662 |
('-x 1 a', NS(x=1.0, y=None, z=['a'])), |
| 1663 |
('-3 1 a', NS(x=None, y=1.0, z=['a'])), |
| 1664 |
] |
| 1665 |
|
| 1666 |
|
| 1667 |
class TestDefaultSuppress(ParserTestCase): |
| 1668 |
"""Test actions with suppressed defaults""" |
| 1669 |
|
| 1670 |
argument_signatures = [ |
| 1671 |
Sig('foo', nargs='?', type=int, default=argparse.SUPPRESS), |
| 1672 |
Sig('bar', nargs='*', type=int, default=argparse.SUPPRESS), |
| 1673 |
Sig('--baz', action='store_true', default=argparse.SUPPRESS), |
| 1674 |
Sig('--qux', nargs='?', type=int, default=argparse.SUPPRESS), |
| 1675 |
Sig('--quux', nargs='*', type=int, default=argparse.SUPPRESS), |
| 1676 |
] |
| 1677 |
failures = ['-x', 'a', '1 a'] |
| 1678 |
successes = [ |
| 1679 |
('', NS()), |
| 1680 |
('1', NS(foo=1)), |
| 1681 |
('1 2', NS(foo=1, bar=[2])), |
| 1682 |
('--baz', NS(baz=True)), |
| 1683 |
('1 --baz', NS(foo=1, baz=True)), |
| 1684 |
('--baz 1 2', NS(foo=1, bar=[2], baz=True)), |
| 1685 |
('--qux', NS(qux=None)), |
| 1686 |
('--qux 1', NS(qux=1)), |
| 1687 |
('--quux', NS(quux=[])), |
| 1688 |
('--quux 1 2', NS(quux=[1, 2])), |
| 1689 |
] |
| 1690 |
|
| 1691 |
|
| 1692 |
class TestParserDefaultSuppress(ParserTestCase): |
| 1693 |
"""Test actions with a parser-level default of SUPPRESS""" |
| 1694 |
|
| 1695 |
parser_signature = Sig(argument_default=argparse.SUPPRESS) |
| 1696 |
argument_signatures = [ |
| 1697 |
Sig('foo', nargs='?'), |
| 1698 |
Sig('bar', nargs='*'), |
| 1699 |
Sig('--baz', action='store_true'), |
| 1700 |
] |
| 1701 |
failures = ['-x'] |
| 1702 |
successes = [ |
| 1703 |
('', NS()), |
| 1704 |
('a', NS(foo='a')), |
| 1705 |
('a b', NS(foo='a', bar=['b'])), |
| 1706 |
('--baz', NS(baz=True)), |
| 1707 |
('a --baz', NS(foo='a', baz=True)), |
| 1708 |
('--baz a b', NS(foo='a', bar=['b'], baz=True)), |
| 1709 |
] |
| 1710 |
|
| 1711 |
|
| 1712 |
class TestParserDefault42(ParserTestCase): |
| 1713 |
"""Test actions with a parser-level default of 42""" |
| 1714 |
|
| 1715 |
parser_signature = Sig(argument_default=42) |
| 1716 |
argument_signatures = [ |
| 1717 |
Sig('--version', action='version', version='1.0'), |
| 1718 |
Sig('foo', nargs='?'), |
| 1719 |
Sig('bar', nargs='*'), |
| 1720 |
Sig('--baz', action='store_true'), |
| 1721 |
] |
| 1722 |
failures = ['-x'] |
| 1723 |
successes = [ |
| 1724 |
('', NS(foo=42, bar=42, baz=42, version=42)), |
| 1725 |
('a', NS(foo='a', bar=42, baz=42, version=42)), |
| 1726 |
('a b', NS(foo='a', bar=['b'], baz=42, version=42)), |
| 1727 |
('--baz', NS(foo=42, bar=42, baz=True, version=42)), |
| 1728 |
('a --baz', NS(foo='a', bar=42, baz=True, version=42)), |
| 1729 |
('--baz a b', NS(foo='a', bar=['b'], baz=True, version=42)), |
| 1730 |
] |
| 1731 |
|
| 1732 |
|
| 1733 |
class TestArgumentsFromFile(TempDirMixin, ParserTestCase): |
| 1734 |
"""Test reading arguments from a file""" |
| 1735 |
|
| 1736 |
def setUp(self): |
| 1737 |
super(TestArgumentsFromFile, self).setUp() |
| 1738 |
file_texts = [ |
| 1739 |
('hello', os.fsencode(self.hello) + b'\n'), |
| 1740 |
('recursive', b'-a\n' |
| 1741 |
b'A\n' |
| 1742 |
b'@hello'), |
| 1743 |
('invalid', b'@no-such-path\n'), |
| 1744 |
('undecodable', self.undecodable + b'\n'), |
| 1745 |
] |
| 1746 |
for path, text in file_texts: |
| 1747 |
with open(path, 'wb') as file: |
| 1748 |
file.write(text) |
| 1749 |
|
| 1750 |
parser_signature = Sig(fromfile_prefix_chars='@') |
| 1751 |
argument_signatures = [ |
| 1752 |
Sig('-a'), |
| 1753 |
Sig('x'), |
| 1754 |
Sig('y', nargs='+'), |
| 1755 |
] |
| 1756 |
failures = ['', '-b', 'X', '@invalid', '@missing'] |
| 1757 |
hello = 'hello world!' + os_helper.FS_NONASCII |
| 1758 |
successes = [ |
| 1759 |
('X Y', NS(a=None, x='X', y=['Y'])), |
| 1760 |
('X -a A Y Z', NS(a='A', x='X', y=['Y', 'Z'])), |
| 1761 |
('@hello X', NS(a=None, x=hello, y=['X'])), |
| 1762 |
('X @hello', NS(a=None, x='X', y=[hello])), |
| 1763 |
('-a B @recursive Y Z', NS(a='A', x=hello, y=['Y', 'Z'])), |
| 1764 |
('X @recursive Z -a B', NS(a='B', x='X', y=[hello, 'Z'])), |
| 1765 |
(["-a", "", "X", "Y"], NS(a='', x='X', y=['Y'])), |
| 1766 |
] |
| 1767 |
if os_helper.TESTFN_UNDECODABLE: |
| 1768 |
undecodable = os_helper.TESTFN_UNDECODABLE.lstrip(b'@') |
| 1769 |
decoded_undecodable = os.fsdecode(undecodable) |
| 1770 |
successes += [ |
| 1771 |
('@undecodable X', NS(a=None, x=decoded_undecodable, y=['X'])), |
| 1772 |
('X @undecodable', NS(a=None, x='X', y=[decoded_undecodable])), |
| 1773 |
] |
| 1774 |
else: |
| 1775 |
undecodable = b'' |
| 1776 |
|
| 1777 |
|
| 1778 |
class TestArgumentsFromFileConverter(TempDirMixin, ParserTestCase): |
| 1779 |
"""Test reading arguments from a file""" |
| 1780 |
|
| 1781 |
def setUp(self): |
| 1782 |
super(TestArgumentsFromFileConverter, self).setUp() |
| 1783 |
file_texts = [ |
| 1784 |
('hello', b'hello world!\n'), |
| 1785 |
] |
| 1786 |
for path, text in file_texts: |
| 1787 |
with open(path, 'wb') as file: |
| 1788 |
file.write(text) |
| 1789 |
|
| 1790 |
class FromFileConverterArgumentParser(ErrorRaisingArgumentParser): |
| 1791 |
|
| 1792 |
def convert_arg_line_to_args(self, arg_line): |
| 1793 |
for arg in arg_line.split(): |
| 1794 |
if not arg.strip(): |
| 1795 |
continue |
| 1796 |
yield arg |
| 1797 |
parser_class = FromFileConverterArgumentParser |
| 1798 |
parser_signature = Sig(fromfile_prefix_chars='@') |
| 1799 |
argument_signatures = [ |
| 1800 |
Sig('y', nargs='+'), |
| 1801 |
] |
| 1802 |
failures = [] |
| 1803 |
successes = [ |
| 1804 |
('@hello X', NS(y=['hello', 'world!', 'X'])), |
| 1805 |
] |
| 1806 |
|
| 1807 |
|
| 1808 |
# ===================== |
| 1809 |
# Type conversion tests |
| 1810 |
# ===================== |
| 1811 |
|
| 1812 |
def FileType(*args, **kwargs): |
| 1813 |
with warnings.catch_warnings(): |
| 1814 |
warnings.filterwarnings('ignore', 'FileType is deprecated', |
| 1815 |
PendingDeprecationWarning, __name__) |
| 1816 |
return argparse.FileType(*args, **kwargs) |
| 1817 |
|
| 1818 |
|
| 1819 |
class TestFileTypeDeprecation(TestCase): |
| 1820 |
|
| 1821 |
def test(self): |
| 1822 |
with self.assertWarns(PendingDeprecationWarning) as cm: |
| 1823 |
argparse.FileType() |
| 1824 |
self.assertIn('FileType is deprecated', str(cm.warning)) |
| 1825 |
self.assertEqual(cm.filename, __file__) |
| 1826 |
|
| 1827 |
|
| 1828 |
class TestFileTypeRepr(TestCase): |
| 1829 |
|
| 1830 |
def test_r(self): |
| 1831 |
type = FileType('r') |
| 1832 |
self.assertEqual("FileType('r')", repr(type)) |
| 1833 |
|
| 1834 |
def test_wb_1(self): |
| 1835 |
type = FileType('wb', 1) |
| 1836 |
self.assertEqual("FileType('wb', 1)", repr(type)) |
| 1837 |
|
| 1838 |
def test_r_latin(self): |
| 1839 |
type = FileType('r', encoding='latin_1') |
| 1840 |
self.assertEqual("FileType('r', encoding='latin_1')", repr(type)) |
| 1841 |
|
| 1842 |
def test_w_big5_ignore(self): |
| 1843 |
type = FileType('w', encoding='big5', errors='ignore') |
| 1844 |
self.assertEqual("FileType('w', encoding='big5', errors='ignore')", |
| 1845 |
repr(type)) |
| 1846 |
|
| 1847 |
def test_r_1_replace(self): |
| 1848 |
type = FileType('r', 1, errors='replace') |
| 1849 |
self.assertEqual("FileType('r', 1, errors='replace')", repr(type)) |
| 1850 |
|
| 1851 |
|
| 1852 |
BIN_STDOUT_SENTINEL = object() |
| 1853 |
BIN_STDERR_SENTINEL = object() |
| 1854 |
|
| 1855 |
|
| 1856 |
class StdStreamComparer: |
| 1857 |
def __init__(self, attr): |
| 1858 |
# We try to use the actual stdXXX.buffer attribute as our |
| 1859 |
# marker, but but under some test environments, |
| 1860 |
# sys.stdout/err are replaced by io.StringIO which won't have .buffer, |
| 1861 |
# so we use a sentinel simply to show that the tests do the right thing |
| 1862 |
# for any buffer supporting object |
| 1863 |
self.getattr = operator.attrgetter(attr) |
| 1864 |
if attr == 'stdout.buffer': |
| 1865 |
self.backupattr = BIN_STDOUT_SENTINEL |
| 1866 |
elif attr == 'stderr.buffer': |
| 1867 |
self.backupattr = BIN_STDERR_SENTINEL |
| 1868 |
else: |
| 1869 |
self.backupattr = object() # Not equal to anything |
| 1870 |
|
| 1871 |
def __eq__(self, other): |
| 1872 |
try: |
| 1873 |
return other == self.getattr(sys) |
| 1874 |
except AttributeError: |
| 1875 |
return other == self.backupattr |
| 1876 |
|
| 1877 |
|
| 1878 |
eq_stdin = StdStreamComparer('stdin') |
| 1879 |
eq_stdout = StdStreamComparer('stdout') |
| 1880 |
eq_stderr = StdStreamComparer('stderr') |
| 1881 |
eq_bstdin = StdStreamComparer('stdin.buffer') |
| 1882 |
eq_bstdout = StdStreamComparer('stdout.buffer') |
| 1883 |
eq_bstderr = StdStreamComparer('stderr.buffer') |
| 1884 |
|
| 1885 |
|
| 1886 |
class RFile(object): |
| 1887 |
seen = {} |
| 1888 |
|
| 1889 |
def __init__(self, name): |
| 1890 |
self.name = name |
| 1891 |
|
| 1892 |
def __eq__(self, other): |
| 1893 |
if other in self.seen: |
| 1894 |
text = self.seen[other] |
| 1895 |
else: |
| 1896 |
text = self.seen[other] = other.read() |
| 1897 |
other.close() |
| 1898 |
if not isinstance(text, str): |
| 1899 |
text = text.decode('ascii') |
| 1900 |
return self.name == other.name == text |
| 1901 |
|
| 1902 |
class TestFileTypeR(TempDirMixin, ParserTestCase): |
| 1903 |
"""Test the FileType option/argument type for reading files""" |
| 1904 |
|
| 1905 |
def setUp(self): |
| 1906 |
super(TestFileTypeR, self).setUp() |
| 1907 |
for file_name in ['foo', 'bar']: |
| 1908 |
with open(os.path.join(self.temp_dir, file_name), |
| 1909 |
'w', encoding="utf-8") as file: |
| 1910 |
file.write(file_name) |
| 1911 |
self.create_readonly_file('readonly') |
| 1912 |
|
| 1913 |
argument_signatures = [ |
| 1914 |
Sig('-x', type=FileType()), |
| 1915 |
Sig('spam', type=FileType('r')), |
| 1916 |
] |
| 1917 |
failures = ['-x', '', 'non-existent-file.txt'] |
| 1918 |
successes = [ |
| 1919 |
('foo', NS(x=None, spam=RFile('foo'))), |
| 1920 |
('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))), |
| 1921 |
('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))), |
| 1922 |
('-x - -', NS(x=eq_stdin, spam=eq_stdin)), |
| 1923 |
('readonly', NS(x=None, spam=RFile('readonly'))), |
| 1924 |
] |
| 1925 |
|
| 1926 |
class TestFileTypeDefaults(TempDirMixin, ParserTestCase): |
| 1927 |
"""Test that a file is not created unless the default is needed""" |
| 1928 |
def setUp(self): |
| 1929 |
super(TestFileTypeDefaults, self).setUp() |
| 1930 |
file = open(os.path.join(self.temp_dir, 'good'), 'w', encoding="utf-8") |
| 1931 |
file.write('good') |
| 1932 |
file.close() |
| 1933 |
|
| 1934 |
argument_signatures = [ |
| 1935 |
Sig('-c', type=FileType('r'), default='no-file.txt'), |
| 1936 |
] |
| 1937 |
# should provoke no such file error |
| 1938 |
failures = [''] |
| 1939 |
# should not provoke error because default file is created |
| 1940 |
successes = [('-c good', NS(c=RFile('good')))] |
| 1941 |
|
| 1942 |
|
| 1943 |
class TestFileTypeRB(TempDirMixin, ParserTestCase): |
| 1944 |
"""Test the FileType option/argument type for reading files""" |
| 1945 |
|
| 1946 |
def setUp(self): |
| 1947 |
super(TestFileTypeRB, self).setUp() |
| 1948 |
for file_name in ['foo', 'bar']: |
| 1949 |
with open(os.path.join(self.temp_dir, file_name), |
| 1950 |
'w', encoding="utf-8") as file: |
| 1951 |
file.write(file_name) |
| 1952 |
|
| 1953 |
argument_signatures = [ |
| 1954 |
Sig('-x', type=FileType('rb')), |
| 1955 |
Sig('spam', type=FileType('rb')), |
| 1956 |
] |
| 1957 |
failures = ['-x', ''] |
| 1958 |
successes = [ |
| 1959 |
('foo', NS(x=None, spam=RFile('foo'))), |
| 1960 |
('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))), |
| 1961 |
('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))), |
| 1962 |
('-x - -', NS(x=eq_bstdin, spam=eq_bstdin)), |
| 1963 |
] |
| 1964 |
|
| 1965 |
|
| 1966 |
class WFile(object): |
| 1967 |
seen = set() |
| 1968 |
|
| 1969 |
def __init__(self, name): |
| 1970 |
self.name = name |
| 1971 |
|
| 1972 |
def __eq__(self, other): |
| 1973 |
if other not in self.seen: |
| 1974 |
text = 'Check that file is writable.' |
| 1975 |
if 'b' in other.mode: |
| 1976 |
text = text.encode('ascii') |
| 1977 |
other.write(text) |
| 1978 |
other.close() |
| 1979 |
self.seen.add(other) |
| 1980 |
return self.name == other.name |
| 1981 |
|
| 1982 |
|
| 1983 |
@os_helper.skip_if_dac_override |
| 1984 |
class TestFileTypeW(TempDirMixin, ParserTestCase): |
| 1985 |
"""Test the FileType option/argument type for writing files""" |
| 1986 |
|
| 1987 |
def setUp(self): |
| 1988 |
super().setUp() |
| 1989 |
self.create_readonly_file('readonly') |
| 1990 |
self.create_writable_file('writable') |
| 1991 |
|
| 1992 |
argument_signatures = [ |
| 1993 |
Sig('-x', type=FileType('w')), |
| 1994 |
Sig('spam', type=FileType('w')), |
| 1995 |
] |
| 1996 |
failures = ['-x', '', 'readonly'] |
| 1997 |
successes = [ |
| 1998 |
('foo', NS(x=None, spam=WFile('foo'))), |
| 1999 |
('writable', NS(x=None, spam=WFile('writable'))), |
| 2000 |
('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))), |
| 2001 |
('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))), |
| 2002 |
('-x - -', NS(x=eq_stdout, spam=eq_stdout)), |
| 2003 |
] |
| 2004 |
|
| 2005 |
|
| 2006 |
@os_helper.skip_if_dac_override |
| 2007 |
class TestFileTypeX(TempDirMixin, ParserTestCase): |
| 2008 |
"""Test the FileType option/argument type for writing new files only""" |
| 2009 |
|
| 2010 |
def setUp(self): |
| 2011 |
super().setUp() |
| 2012 |
self.create_readonly_file('readonly') |
| 2013 |
self.create_writable_file('writable') |
| 2014 |
|
| 2015 |
argument_signatures = [ |
| 2016 |
Sig('-x', type=FileType('x')), |
| 2017 |
Sig('spam', type=FileType('x')), |
| 2018 |
] |
| 2019 |
failures = ['-x', '', 'readonly', 'writable'] |
| 2020 |
successes = [ |
| 2021 |
('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))), |
| 2022 |
('-x - -', NS(x=eq_stdout, spam=eq_stdout)), |
| 2023 |
] |
| 2024 |
|
| 2025 |
|
| 2026 |
@os_helper.skip_if_dac_override |
| 2027 |
class TestFileTypeWB(TempDirMixin, ParserTestCase): |
| 2028 |
"""Test the FileType option/argument type for writing binary files""" |
| 2029 |
|
| 2030 |
argument_signatures = [ |
| 2031 |
Sig('-x', type=FileType('wb')), |
| 2032 |
Sig('spam', type=FileType('wb')), |
| 2033 |
] |
| 2034 |
failures = ['-x', ''] |
| 2035 |
successes = [ |
| 2036 |
('foo', NS(x=None, spam=WFile('foo'))), |
| 2037 |
('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))), |
| 2038 |
('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))), |
| 2039 |
('-x - -', NS(x=eq_bstdout, spam=eq_bstdout)), |
| 2040 |
] |
| 2041 |
|
| 2042 |
|
| 2043 |
@os_helper.skip_if_dac_override |
| 2044 |
class TestFileTypeXB(TestFileTypeX): |
| 2045 |
"Test the FileType option/argument type for writing new binary files only" |
| 2046 |
|
| 2047 |
argument_signatures = [ |
| 2048 |
Sig('-x', type=FileType('xb')), |
| 2049 |
Sig('spam', type=FileType('xb')), |
| 2050 |
] |
| 2051 |
successes = [ |
| 2052 |
('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))), |
| 2053 |
('-x - -', NS(x=eq_bstdout, spam=eq_bstdout)), |
| 2054 |
] |
| 2055 |
|
| 2056 |
|
| 2057 |
class TestFileTypeOpenArgs(TestCase): |
| 2058 |
"""Test that open (the builtin) is correctly called""" |
| 2059 |
|
| 2060 |
def test_open_args(self): |
| 2061 |
FT = FileType |
| 2062 |
cases = [ |
| 2063 |
(FT('rb'), ('rb', -1, None, None)), |
| 2064 |
(FT('w', 1), ('w', 1, None, None)), |
| 2065 |
(FT('w', errors='replace'), ('w', -1, None, 'replace')), |
| 2066 |
(FT('wb', encoding='big5'), ('wb', -1, 'big5', None)), |
| 2067 |
(FT('w', 0, 'l1', 'strict'), ('w', 0, 'l1', 'strict')), |
| 2068 |
] |
| 2069 |
with mock.patch('builtins.open') as m: |
| 2070 |
for type, args in cases: |
| 2071 |
type('foo') |
| 2072 |
m.assert_called_with('foo', *args) |
| 2073 |
|
| 2074 |
def test_invalid_file_type(self): |
| 2075 |
with self.assertRaises(ValueError): |
| 2076 |
FileType('b')('-test') |
| 2077 |
|
| 2078 |
|
| 2079 |
class TestFileTypeMissingInitialization(TestCase): |
| 2080 |
""" |
| 2081 |
Test that add_argument throws an error if FileType class |
| 2082 |
object was passed instead of instance of FileType |
| 2083 |
""" |
| 2084 |
|
| 2085 |
def test(self): |
| 2086 |
parser = argparse.ArgumentParser() |
| 2087 |
with self.assertRaises(TypeError) as cm: |
| 2088 |
parser.add_argument('-x', type=argparse.FileType) |
| 2089 |
|
| 2090 |
self.assertEqual( |
| 2091 |
'%r is a FileType class object, instance of it must be passed' |
| 2092 |
% (argparse.FileType,), |
| 2093 |
str(cm.exception) |
| 2094 |
) |
| 2095 |
|
| 2096 |
|
| 2097 |
class TestTypeCallable(ParserTestCase): |
| 2098 |
"""Test some callables as option/argument types""" |
| 2099 |
|
| 2100 |
argument_signatures = [ |
| 2101 |
Sig('--eggs', type=complex), |
| 2102 |
Sig('spam', type=float), |
| 2103 |
] |
| 2104 |
failures = ['a', '42j', '--eggs a', '--eggs 2i'] |
| 2105 |
successes = [ |
| 2106 |
('--eggs=42 42', NS(eggs=42, spam=42.0)), |
| 2107 |
('--eggs 2j -- -1.5', NS(eggs=2j, spam=-1.5)), |
| 2108 |
('1024.675', NS(eggs=None, spam=1024.675)), |
| 2109 |
] |
| 2110 |
|
| 2111 |
|
| 2112 |
class TestTypeUserDefined(ParserTestCase): |
| 2113 |
"""Test a user-defined option/argument type""" |
| 2114 |
|
| 2115 |
class MyType(TestCase): |
| 2116 |
|
| 2117 |
def __init__(self, value): |
| 2118 |
self.value = value |
| 2119 |
|
| 2120 |
def __eq__(self, other): |
| 2121 |
return (type(self), self.value) == (type(other), other.value) |
| 2122 |
|
| 2123 |
argument_signatures = [ |
| 2124 |
Sig('-x', type=MyType), |
| 2125 |
Sig('spam', type=MyType), |
| 2126 |
] |
| 2127 |
failures = [] |
| 2128 |
successes = [ |
| 2129 |
('a -x b', NS(x=MyType('b'), spam=MyType('a'))), |
| 2130 |
('-xf g', NS(x=MyType('f'), spam=MyType('g'))), |
| 2131 |
] |
| 2132 |
|
| 2133 |
|
| 2134 |
class TestTypeClassicClass(ParserTestCase): |
| 2135 |
"""Test a classic class type""" |
| 2136 |
|
| 2137 |
class C: |
| 2138 |
|
| 2139 |
def __init__(self, value): |
| 2140 |
self.value = value |
| 2141 |
|
| 2142 |
def __eq__(self, other): |
| 2143 |
return (type(self), self.value) == (type(other), other.value) |
| 2144 |
|
| 2145 |
argument_signatures = [ |
| 2146 |
Sig('-x', type=C), |
| 2147 |
Sig('spam', type=C), |
| 2148 |
] |
| 2149 |
failures = [] |
| 2150 |
successes = [ |
| 2151 |
('a -x b', NS(x=C('b'), spam=C('a'))), |
| 2152 |
('-xf g', NS(x=C('f'), spam=C('g'))), |
| 2153 |
] |
| 2154 |
|
| 2155 |
|
| 2156 |
class TestTypeRegistration(TestCase): |
| 2157 |
"""Test a user-defined type by registering it""" |
| 2158 |
|
| 2159 |
def test(self): |
| 2160 |
|
| 2161 |
def get_my_type(string): |
| 2162 |
return 'my_type{%s}' % string |
| 2163 |
|
| 2164 |
parser = argparse.ArgumentParser() |
| 2165 |
parser.register('type', 'my_type', get_my_type) |
| 2166 |
parser.add_argument('-x', type='my_type') |
| 2167 |
parser.add_argument('y', type='my_type') |
| 2168 |
|
| 2169 |
self.assertEqual(parser.parse_args('1'.split()), |
| 2170 |
NS(x=None, y='my_type{1}')) |
| 2171 |
self.assertEqual(parser.parse_args('-x 1 42'.split()), |
| 2172 |
NS(x='my_type{1}', y='my_type{42}')) |
| 2173 |
|
| 2174 |
|
| 2175 |
# ============ |
| 2176 |
# Action tests |
| 2177 |
# ============ |
| 2178 |
|
| 2179 |
class TestActionUserDefined(ParserTestCase): |
| 2180 |
"""Test a user-defined option/argument action""" |
| 2181 |
|
| 2182 |
class OptionalAction(argparse.Action): |
| 2183 |
|
| 2184 |
def __call__(self, parser, namespace, value, option_string=None): |
| 2185 |
try: |
| 2186 |
# check destination and option string |
| 2187 |
assert self.dest == 'spam', 'dest: %s' % self.dest |
| 2188 |
assert option_string == '-s', 'flag: %s' % option_string |
| 2189 |
# when option is before argument, badger=2, and when |
| 2190 |
# option is after argument, badger=<whatever was set> |
| 2191 |
expected_ns = NS(spam=0.25) |
| 2192 |
if value in [0.125, 0.625]: |
| 2193 |
expected_ns.badger = 2 |
| 2194 |
elif value in [2.0]: |
| 2195 |
expected_ns.badger = 84 |
| 2196 |
else: |
| 2197 |
raise AssertionError('value: %s' % value) |
| 2198 |
assert expected_ns == namespace, ('expected %s, got %s' % |
| 2199 |
(expected_ns, namespace)) |
| 2200 |
except AssertionError as e: |
| 2201 |
raise ArgumentParserError('opt_action failed: %s' % e) |
| 2202 |
setattr(namespace, 'spam', value) |
| 2203 |
|
| 2204 |
class PositionalAction(argparse.Action): |
| 2205 |
|
| 2206 |
def __call__(self, parser, namespace, value, option_string=None): |
| 2207 |
try: |
| 2208 |
assert option_string is None, ('option_string: %s' % |
| 2209 |
option_string) |
| 2210 |
# check destination |
| 2211 |
assert self.dest == 'badger', 'dest: %s' % self.dest |
| 2212 |
# when argument is before option, spam=0.25, and when |
| 2213 |
# option is after argument, spam=<whatever was set> |
| 2214 |
expected_ns = NS(badger=2) |
| 2215 |
if value in [42, 84]: |
| 2216 |
expected_ns.spam = 0.25 |
| 2217 |
elif value in [1]: |
| 2218 |
expected_ns.spam = 0.625 |
| 2219 |
elif value in [2]: |
| 2220 |
expected_ns.spam = 0.125 |
| 2221 |
else: |
| 2222 |
raise AssertionError('value: %s' % value) |
| 2223 |
assert expected_ns == namespace, ('expected %s, got %s' % |
| 2224 |
(expected_ns, namespace)) |
| 2225 |
except AssertionError as e: |
| 2226 |
raise ArgumentParserError('arg_action failed: %s' % e) |
| 2227 |
setattr(namespace, 'badger', value) |
| 2228 |
|
| 2229 |
argument_signatures = [ |
| 2230 |
Sig('-s', dest='spam', action=OptionalAction, |
| 2231 |
type=float, default=0.25), |
| 2232 |
Sig('badger', action=PositionalAction, |
| 2233 |
type=int, nargs='?', default=2), |
| 2234 |
] |
| 2235 |
failures = [] |
| 2236 |
successes = [ |
| 2237 |
('-s0.125', NS(spam=0.125, badger=2)), |
| 2238 |
('42', NS(spam=0.25, badger=42)), |
| 2239 |
('-s 0.625 1', NS(spam=0.625, badger=1)), |
| 2240 |
('84 -s2', NS(spam=2.0, badger=84)), |
| 2241 |
] |
| 2242 |
|
| 2243 |
|
| 2244 |
class TestActionRegistration(TestCase): |
| 2245 |
"""Test a user-defined action supplied by registering it""" |
| 2246 |
|
| 2247 |
class MyAction(argparse.Action): |
| 2248 |
|
| 2249 |
def __call__(self, parser, namespace, values, option_string=None): |
| 2250 |
setattr(namespace, self.dest, 'foo[%s]' % values) |
| 2251 |
|
| 2252 |
def test(self): |
| 2253 |
|
| 2254 |
parser = argparse.ArgumentParser() |
| 2255 |
parser.register('action', 'my_action', self.MyAction) |
| 2256 |
parser.add_argument('badger', action='my_action') |
| 2257 |
|
| 2258 |
self.assertEqual(parser.parse_args(['1']), NS(badger='foo[1]')) |
| 2259 |
self.assertEqual(parser.parse_args(['42']), NS(badger='foo[42]')) |
| 2260 |
|
| 2261 |
|
| 2262 |
class TestActionExtend(ParserTestCase): |
| 2263 |
argument_signatures = [ |
| 2264 |
Sig('--foo', action="extend", nargs="+", type=str), |
| 2265 |
] |
| 2266 |
failures = () |
| 2267 |
successes = [ |
| 2268 |
('--foo f1 --foo f2 f3 f4', NS(foo=['f1', 'f2', 'f3', 'f4'])), |
| 2269 |
] |
| 2270 |
|
| 2271 |
|
| 2272 |
class TestNegativeNumber(ParserTestCase): |
| 2273 |
"""Test parsing negative numbers""" |
| 2274 |
|
| 2275 |
argument_signatures = [ |
| 2276 |
Sig('--int', type=int), |
| 2277 |
Sig('--float', type=float), |
| 2278 |
Sig('--complex', type=complex), |
| 2279 |
] |
| 2280 |
failures = [ |
| 2281 |
'--float -_.45', |
| 2282 |
'--float -1__000.0', |
| 2283 |
'--float -1.0.0', |
| 2284 |
'--int -1__000', |
| 2285 |
'--int -1.0', |
| 2286 |
'--complex -1__000.0j', |
| 2287 |
'--complex -1.0jj', |
| 2288 |
'--complex -_.45j', |
| 2289 |
] |
| 2290 |
successes = [ |
| 2291 |
('--int -1000 --float -1000.0', NS(int=-1000, float=-1000.0, complex=None)), |
| 2292 |
('--int -1_000 --float -1_000.0', NS(int=-1000, float=-1000.0, complex=None)), |
| 2293 |
('--int -1_000_000 --float -1_000_000.0', NS(int=-1000000, float=-1000000.0, complex=None)), |
| 2294 |
('--float -1_000.0', NS(int=None, float=-1000.0, complex=None)), |
| 2295 |
('--float -1_000_000.0_0', NS(int=None, float=-1000000.0, complex=None)), |
| 2296 |
('--float -.5', NS(int=None, float=-0.5, complex=None)), |
| 2297 |
('--float -.5_000', NS(int=None, float=-0.5, complex=None)), |
| 2298 |
('--float -1e3', NS(int=None, float=-1000, complex=None)), |
| 2299 |
('--float -1e-3', NS(int=None, float=-0.001, complex=None)), |
| 2300 |
('--complex -1j', NS(int=None, float=None, complex=-1j)), |
| 2301 |
('--complex -1_000j', NS(int=None, float=None, complex=-1000j)), |
| 2302 |
('--complex -1_000.0j', NS(int=None, float=None, complex=-1000.0j)), |
| 2303 |
('--complex -1e3j', NS(int=None, float=None, complex=-1000j)), |
| 2304 |
('--complex -1e-3j', NS(int=None, float=None, complex=-0.001j)), |
| 2305 |
] |
| 2306 |
|
| 2307 |
class TestArgumentAndSubparserSuggestions(TestCase): |
| 2308 |
"""Test error handling and suggestion when a user makes a typo""" |
| 2309 |
|
| 2310 |
def test_wrong_argument_error_with_suggestions(self): |
| 2311 |
parser = ErrorRaisingArgumentParser(suggest_on_error=True) |
| 2312 |
parser.add_argument('foo', choices=['bar', 'baz']) |
| 2313 |
with self.assertRaises(ArgumentParserError) as excinfo: |
| 2314 |
parser.parse_args(('bazz',)) |
| 2315 |
self.assertIn( |
| 2316 |
"error: argument foo: invalid choice: 'bazz', maybe you meant 'baz'? (choose from 'bar', 'baz')", |
| 2317 |
excinfo.exception.stderr |
| 2318 |
) |
| 2319 |
|
| 2320 |
def test_wrong_argument_error_no_suggestions(self): |
| 2321 |
parser = ErrorRaisingArgumentParser(suggest_on_error=False) |
| 2322 |
parser.add_argument('foo', choices=['bar', 'baz']) |
| 2323 |
with self.assertRaises(ArgumentParserError) as excinfo: |
| 2324 |
parser.parse_args(('bazz',)) |
| 2325 |
self.assertIn( |
| 2326 |
"error: argument foo: invalid choice: 'bazz' (choose from 'bar', 'baz')", |
| 2327 |
excinfo.exception.stderr, |
| 2328 |
) |
| 2329 |
|
| 2330 |
def test_wrong_argument_subparsers_with_suggestions(self): |
| 2331 |
parser = ErrorRaisingArgumentParser(suggest_on_error=True) |
| 2332 |
subparsers = parser.add_subparsers(required=True) |
| 2333 |
subparsers.add_parser('foo') |
| 2334 |
subparsers.add_parser('bar') |
| 2335 |
with self.assertRaises(ArgumentParserError) as excinfo: |
| 2336 |
parser.parse_args(('baz',)) |
| 2337 |
self.assertIn( |
| 2338 |
"error: argument {foo,bar}: invalid choice: 'baz', maybe you meant" |
| 2339 |
" 'bar'? (choose from 'foo', 'bar')", |
| 2340 |
excinfo.exception.stderr, |
| 2341 |
) |
| 2342 |
|
| 2343 |
def test_wrong_argument_subparsers_no_suggestions(self): |
| 2344 |
parser = ErrorRaisingArgumentParser(suggest_on_error=False) |
| 2345 |
subparsers = parser.add_subparsers(required=True) |
| 2346 |
subparsers.add_parser('foo') |
| 2347 |
subparsers.add_parser('bar') |
| 2348 |
with self.assertRaises(ArgumentParserError) as excinfo: |
| 2349 |
parser.parse_args(('baz',)) |
| 2350 |
self.assertIn( |
| 2351 |
"error: argument {foo,bar}: invalid choice: 'baz' (choose from 'foo', 'bar')", |
| 2352 |
excinfo.exception.stderr, |
| 2353 |
) |
| 2354 |
|
| 2355 |
def test_wrong_argument_no_suggestion_implicit(self): |
| 2356 |
parser = ErrorRaisingArgumentParser() |
| 2357 |
parser.add_argument('foo', choices=['bar', 'baz']) |
| 2358 |
with self.assertRaises(ArgumentParserError) as excinfo: |
| 2359 |
parser.parse_args(('bazz',)) |
| 2360 |
self.assertIn( |
| 2361 |
"error: argument foo: invalid choice: 'bazz' (choose from 'bar', 'baz')", |
| 2362 |
excinfo.exception.stderr, |
| 2363 |
) |
| 2364 |
|
| 2365 |
def test_suggestions_choices_empty(self): |
| 2366 |
parser = ErrorRaisingArgumentParser(suggest_on_error=True) |
| 2367 |
parser.add_argument('foo', choices=[]) |
| 2368 |
with self.assertRaises(ArgumentParserError) as excinfo: |
| 2369 |
parser.parse_args(('bazz',)) |
| 2370 |
self.assertIn( |
| 2371 |
"error: argument foo: invalid choice: 'bazz' (choose from )", |
| 2372 |
excinfo.exception.stderr, |
| 2373 |
) |
| 2374 |
|
| 2375 |
def test_suggestions_choices_int(self): |
| 2376 |
parser = ErrorRaisingArgumentParser(suggest_on_error=True) |
| 2377 |
parser.add_argument('foo', choices=[1, 2]) |
| 2378 |
with self.assertRaises(ArgumentParserError) as excinfo: |
| 2379 |
parser.parse_args(('3',)) |
| 2380 |
self.assertIn( |
| 2381 |
"error: argument foo: invalid choice: '3' (choose from '1', '2')", |
| 2382 |
excinfo.exception.stderr, |
| 2383 |
) |
| 2384 |
|
| 2385 |
def test_suggestions_choices_mixed_types(self): |
| 2386 |
parser = ErrorRaisingArgumentParser(suggest_on_error=True) |
| 2387 |
parser.add_argument('foo', choices=[1, '2']) |
| 2388 |
with self.assertRaises(ArgumentParserError) as excinfo: |
| 2389 |
parser.parse_args(('3',)) |
| 2390 |
self.assertIn( |
| 2391 |
"error: argument foo: invalid choice: '3' (choose from '1', '2')", |
| 2392 |
excinfo.exception.stderr, |
| 2393 |
) |
| 2394 |
|
| 2395 |
|
| 2396 |
class TestInvalidAction(TestCase): |
| 2397 |
"""Test invalid user defined Action""" |
| 2398 |
|
| 2399 |
class ActionWithoutCall(argparse.Action): |
| 2400 |
pass |
| 2401 |
|
| 2402 |
def test_invalid_type(self): |
| 2403 |
parser = argparse.ArgumentParser() |
| 2404 |
|
| 2405 |
parser.add_argument('--foo', action=self.ActionWithoutCall) |
| 2406 |
self.assertRaises(NotImplementedError, parser.parse_args, ['--foo', 'bar']) |
| 2407 |
|
| 2408 |
def test_modified_invalid_action(self): |
| 2409 |
parser = argparse.ArgumentParser(exit_on_error=False) |
| 2410 |
action = parser.add_argument('--foo') |
| 2411 |
# Someone got crazy and did this |
| 2412 |
action.type = 1 |
| 2413 |
self.assertRaisesRegex(TypeError, '1 is not callable', |
| 2414 |
parser.parse_args, ['--foo', 'bar']) |
| 2415 |
action.type = () |
| 2416 |
self.assertRaisesRegex(TypeError, r'\(\) is not callable', |
| 2417 |
parser.parse_args, ['--foo', 'bar']) |
| 2418 |
# It is impossible to distinguish a TypeError raised due to a mismatch |
| 2419 |
# of the required function arguments from a TypeError raised for an incorrect |
| 2420 |
# argument value, and using the heavy inspection machinery is not worthwhile |
| 2421 |
# as it does not reliably work in all cases. |
| 2422 |
# Therefore, a generic ArgumentError is raised to handle this logical error. |
| 2423 |
action.type = pow |
| 2424 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 2425 |
"argument --foo: invalid pow value: 'bar'", |
| 2426 |
parser.parse_args, ['--foo', 'bar']) |
| 2427 |
|
| 2428 |
|
| 2429 |
# ================ |
| 2430 |
# Subparsers tests |
| 2431 |
# ================ |
| 2432 |
|
| 2433 |
@force_not_colorized_test_class |
| 2434 |
class TestAddSubparsers(TestCase): |
| 2435 |
"""Test the add_subparsers method""" |
| 2436 |
|
| 2437 |
def assertArgumentParserError(self, *args, **kwargs): |
| 2438 |
self.assertRaises(ArgumentParserError, *args, **kwargs) |
| 2439 |
|
| 2440 |
def _get_parser(self, subparser_help=False, prefix_chars=None, |
| 2441 |
aliases=False, usage=None): |
| 2442 |
# create a parser with a subparsers argument |
| 2443 |
if prefix_chars: |
| 2444 |
parser = ErrorRaisingArgumentParser( |
| 2445 |
prog='PROG', description='main description', usage=usage, |
| 2446 |
prefix_chars=prefix_chars) |
| 2447 |
parser.add_argument( |
| 2448 |
prefix_chars[0] * 2 + 'foo', action='store_true', help='foo help') |
| 2449 |
else: |
| 2450 |
parser = ErrorRaisingArgumentParser( |
| 2451 |
prog='PROG', description='main description', usage=usage) |
| 2452 |
parser.add_argument( |
| 2453 |
'--foo', action='store_true', help='foo help') |
| 2454 |
parser.add_argument( |
| 2455 |
'bar', type=float, help='bar help') |
| 2456 |
|
| 2457 |
# check that only one subparsers argument can be added |
| 2458 |
subparsers_kwargs = {'required': False} |
| 2459 |
if aliases: |
| 2460 |
subparsers_kwargs['metavar'] = 'COMMAND' |
| 2461 |
subparsers_kwargs['title'] = 'commands' |
| 2462 |
else: |
| 2463 |
subparsers_kwargs['help'] = 'command help' |
| 2464 |
subparsers = parser.add_subparsers(**subparsers_kwargs) |
| 2465 |
self.assertRaisesRegex(ValueError, |
| 2466 |
'cannot have multiple subparser arguments', |
| 2467 |
parser.add_subparsers) |
| 2468 |
|
| 2469 |
# add first sub-parser |
| 2470 |
parser1_kwargs = dict(description='1 description') |
| 2471 |
if subparser_help: |
| 2472 |
parser1_kwargs['help'] = '1 help' |
| 2473 |
if aliases: |
| 2474 |
parser1_kwargs['aliases'] = ['1alias1', '1alias2'] |
| 2475 |
parser1 = subparsers.add_parser('1', **parser1_kwargs) |
| 2476 |
parser1.add_argument('-w', type=int, help='w help') |
| 2477 |
parser1.add_argument('x', choices=['a', 'b', 'c'], help='x help') |
| 2478 |
|
| 2479 |
# add second sub-parser |
| 2480 |
parser2_kwargs = dict(description='2 description') |
| 2481 |
if subparser_help: |
| 2482 |
parser2_kwargs['help'] = '2 help' |
| 2483 |
parser2 = subparsers.add_parser('2', **parser2_kwargs) |
| 2484 |
parser2.add_argument('-y', choices=['1', '2', '3'], help='y help') |
| 2485 |
parser2.add_argument('z', type=complex, nargs='*', help='z help') |
| 2486 |
|
| 2487 |
# add third sub-parser |
| 2488 |
parser3_kwargs = dict(description='3 description', |
| 2489 |
usage='PROG --foo bar 3 t ...') |
| 2490 |
if subparser_help: |
| 2491 |
parser3_kwargs['help'] = '3 help' |
| 2492 |
parser3 = subparsers.add_parser('3', **parser3_kwargs) |
| 2493 |
parser3.add_argument('t', type=int, help='t help') |
| 2494 |
parser3.add_argument('u', nargs='...', help='u help') |
| 2495 |
|
| 2496 |
# return the main parser |
| 2497 |
return parser |
| 2498 |
|
| 2499 |
def setUp(self): |
| 2500 |
super().setUp() |
| 2501 |
self.parser = self._get_parser() |
| 2502 |
self.command_help_parser = self._get_parser(subparser_help=True) |
| 2503 |
|
| 2504 |
def test_parse_args_failures(self): |
| 2505 |
# check some failure cases: |
| 2506 |
for args_str in ['', 'a', 'a a', '0.5 a', '0.5 1', |
| 2507 |
'0.5 1 -y', '0.5 2 -w']: |
| 2508 |
args = args_str.split() |
| 2509 |
self.assertArgumentParserError(self.parser.parse_args, args) |
| 2510 |
|
| 2511 |
def test_parse_args_failures_details(self): |
| 2512 |
for args_str, usage_str, error_str in [ |
| 2513 |
('', |
| 2514 |
'usage: PROG [-h] [--foo] bar {1,2,3} ...', |
| 2515 |
'PROG: error: the following arguments are required: bar'), |
| 2516 |
('0.5 1 -y', |
| 2517 |
'usage: PROG bar 1 [-h] [-w W] {a,b,c}', |
| 2518 |
'PROG bar 1: error: the following arguments are required: x'), |
| 2519 |
('0.5 3', |
| 2520 |
'usage: PROG --foo bar 3 t ...', |
| 2521 |
'PROG bar 3: error: the following arguments are required: t'), |
| 2522 |
]: |
| 2523 |
with self.subTest(args_str): |
| 2524 |
args = args_str.split() |
| 2525 |
with self.assertRaises(ArgumentParserError) as cm: |
| 2526 |
self.parser.parse_args(args) |
| 2527 |
self.assertEqual(cm.exception.args[0], 'SystemExit') |
| 2528 |
self.assertEqual(cm.exception.args[2], f'{usage_str}\n{error_str}\n') |
| 2529 |
|
| 2530 |
def test_parse_args_failures_details_custom_usage(self): |
| 2531 |
parser = self._get_parser(usage='PROG [--foo] bar 1 [-w W] {a,b,c}\n' |
| 2532 |
' PROG --foo bar 3 t ...') |
| 2533 |
for args_str, usage_str, error_str in [ |
| 2534 |
('', |
| 2535 |
'usage: PROG [--foo] bar 1 [-w W] {a,b,c}\n' |
| 2536 |
' PROG --foo bar 3 t ...', |
| 2537 |
'PROG: error: the following arguments are required: bar'), |
| 2538 |
('0.5 1 -y', |
| 2539 |
'usage: PROG bar 1 [-h] [-w W] {a,b,c}', |
| 2540 |
'PROG bar 1: error: the following arguments are required: x'), |
| 2541 |
('0.5 3', |
| 2542 |
'usage: PROG --foo bar 3 t ...', |
| 2543 |
'PROG bar 3: error: the following arguments are required: t'), |
| 2544 |
]: |
| 2545 |
with self.subTest(args_str): |
| 2546 |
args = args_str.split() |
| 2547 |
with self.assertRaises(ArgumentParserError) as cm: |
| 2548 |
parser.parse_args(args) |
| 2549 |
self.assertEqual(cm.exception.args[0], 'SystemExit') |
| 2550 |
self.assertEqual(cm.exception.args[2], f'{usage_str}\n{error_str}\n') |
| 2551 |
|
| 2552 |
def test_parse_args(self): |
| 2553 |
# check some non-failure cases: |
| 2554 |
self.assertEqual( |
| 2555 |
self.parser.parse_args('0.5 1 b -w 7'.split()), |
| 2556 |
NS(foo=False, bar=0.5, w=7, x='b'), |
| 2557 |
) |
| 2558 |
self.assertEqual( |
| 2559 |
self.parser.parse_args('0.25 --foo 2 -y 2 3j -- -1j'.split()), |
| 2560 |
NS(foo=True, bar=0.25, y='2', z=[3j, -1j]), |
| 2561 |
) |
| 2562 |
self.assertEqual( |
| 2563 |
self.parser.parse_args('--foo 0.125 1 c'.split()), |
| 2564 |
NS(foo=True, bar=0.125, w=None, x='c'), |
| 2565 |
) |
| 2566 |
self.assertEqual( |
| 2567 |
self.parser.parse_args('-1.5 3 11 -- a --foo 7 -- b'.split()), |
| 2568 |
NS(foo=False, bar=-1.5, t=11, u=['a', '--foo', '7', '--', 'b']), |
| 2569 |
) |
| 2570 |
|
| 2571 |
def test_parse_known_args(self): |
| 2572 |
self.assertEqual( |
| 2573 |
self.parser.parse_known_args('0.5 1 b -w 7'.split()), |
| 2574 |
(NS(foo=False, bar=0.5, w=7, x='b'), []), |
| 2575 |
) |
| 2576 |
self.assertEqual( |
| 2577 |
self.parser.parse_known_args('0.5 -p 1 b -w 7'.split()), |
| 2578 |
(NS(foo=False, bar=0.5, w=7, x='b'), ['-p']), |
| 2579 |
) |
| 2580 |
self.assertEqual( |
| 2581 |
self.parser.parse_known_args('0.5 1 b -w 7 -p'.split()), |
| 2582 |
(NS(foo=False, bar=0.5, w=7, x='b'), ['-p']), |
| 2583 |
) |
| 2584 |
self.assertEqual( |
| 2585 |
self.parser.parse_known_args('0.5 1 b -q -rs -w 7'.split()), |
| 2586 |
(NS(foo=False, bar=0.5, w=7, x='b'), ['-q', '-rs']), |
| 2587 |
) |
| 2588 |
self.assertEqual( |
| 2589 |
self.parser.parse_known_args('0.5 -W 1 b -X Y -w 7 Z'.split()), |
| 2590 |
(NS(foo=False, bar=0.5, w=7, x='b'), ['-W', '-X', 'Y', 'Z']), |
| 2591 |
) |
| 2592 |
|
| 2593 |
def test_parse_known_args_to_class_namespace(self): |
| 2594 |
class C: |
| 2595 |
pass |
| 2596 |
self.assertEqual( |
| 2597 |
self.parser.parse_known_args('0.5 1 b -w 7 -p'.split(), namespace=C), |
| 2598 |
(C, ['-p']), |
| 2599 |
) |
| 2600 |
self.assertIs(C.foo, False) |
| 2601 |
self.assertEqual(C.bar, 0.5) |
| 2602 |
self.assertEqual(C.w, 7) |
| 2603 |
self.assertEqual(C.x, 'b') |
| 2604 |
|
| 2605 |
def test_abbreviation(self): |
| 2606 |
parser = ErrorRaisingArgumentParser() |
| 2607 |
parser.add_argument('--foodle') |
| 2608 |
parser.add_argument('--foonly') |
| 2609 |
subparsers = parser.add_subparsers() |
| 2610 |
parser1 = subparsers.add_parser('bar') |
| 2611 |
parser1.add_argument('--fo') |
| 2612 |
parser1.add_argument('--foonew') |
| 2613 |
|
| 2614 |
self.assertEqual(parser.parse_args(['--food', 'baz', 'bar']), |
| 2615 |
NS(foodle='baz', foonly=None, fo=None, foonew=None)) |
| 2616 |
self.assertEqual(parser.parse_args(['--foon', 'baz', 'bar']), |
| 2617 |
NS(foodle=None, foonly='baz', fo=None, foonew=None)) |
| 2618 |
self.assertArgumentParserError(parser.parse_args, ['--fo', 'baz', 'bar']) |
| 2619 |
self.assertEqual(parser.parse_args(['bar', '--fo', 'baz']), |
| 2620 |
NS(foodle=None, foonly=None, fo='baz', foonew=None)) |
| 2621 |
self.assertEqual(parser.parse_args(['bar', '--foo', 'baz']), |
| 2622 |
NS(foodle=None, foonly=None, fo=None, foonew='baz')) |
| 2623 |
self.assertEqual(parser.parse_args(['bar', '--foon', 'baz']), |
| 2624 |
NS(foodle=None, foonly=None, fo=None, foonew='baz')) |
| 2625 |
self.assertArgumentParserError(parser.parse_args, ['bar', '--food', 'baz']) |
| 2626 |
|
| 2627 |
def test_parse_known_args_with_single_dash_option(self): |
| 2628 |
parser = ErrorRaisingArgumentParser() |
| 2629 |
parser.add_argument('-k', '--known', action='count', default=0) |
| 2630 |
parser.add_argument('-n', '--new', action='count', default=0) |
| 2631 |
self.assertEqual(parser.parse_known_args(['-k', '-u']), |
| 2632 |
(NS(known=1, new=0), ['-u'])) |
| 2633 |
self.assertEqual(parser.parse_known_args(['-u', '-k']), |
| 2634 |
(NS(known=1, new=0), ['-u'])) |
| 2635 |
self.assertEqual(parser.parse_known_args(['-ku']), |
| 2636 |
(NS(known=1, new=0), ['-u'])) |
| 2637 |
self.assertArgumentParserError(parser.parse_known_args, ['-k=u']) |
| 2638 |
self.assertEqual(parser.parse_known_args(['-uk']), |
| 2639 |
(NS(known=0, new=0), ['-uk'])) |
| 2640 |
self.assertEqual(parser.parse_known_args(['-u=k']), |
| 2641 |
(NS(known=0, new=0), ['-u=k'])) |
| 2642 |
self.assertEqual(parser.parse_known_args(['-kunknown']), |
| 2643 |
(NS(known=1, new=0), ['-unknown'])) |
| 2644 |
self.assertArgumentParserError(parser.parse_known_args, ['-k=unknown']) |
| 2645 |
self.assertEqual(parser.parse_known_args(['-ku=nknown']), |
| 2646 |
(NS(known=1, new=0), ['-u=nknown'])) |
| 2647 |
self.assertEqual(parser.parse_known_args(['-knew']), |
| 2648 |
(NS(known=1, new=1), ['-ew'])) |
| 2649 |
self.assertArgumentParserError(parser.parse_known_args, ['-kn=ew']) |
| 2650 |
self.assertArgumentParserError(parser.parse_known_args, ['-k-new']) |
| 2651 |
self.assertArgumentParserError(parser.parse_known_args, ['-kn-ew']) |
| 2652 |
self.assertEqual(parser.parse_known_args(['-kne-w']), |
| 2653 |
(NS(known=1, new=1), ['-e-w'])) |
| 2654 |
|
| 2655 |
def test_dest(self): |
| 2656 |
parser = ErrorRaisingArgumentParser() |
| 2657 |
parser.add_argument('--foo', action='store_true') |
| 2658 |
subparsers = parser.add_subparsers(dest='bar') |
| 2659 |
parser1 = subparsers.add_parser('1') |
| 2660 |
parser1.add_argument('baz') |
| 2661 |
self.assertEqual(NS(foo=False, bar='1', baz='2'), |
| 2662 |
parser.parse_args('1 2'.split())) |
| 2663 |
|
| 2664 |
def _test_required_subparsers(self, parser): |
| 2665 |
# Should parse the sub command |
| 2666 |
ret = parser.parse_args(['run']) |
| 2667 |
self.assertEqual(ret.command, 'run') |
| 2668 |
|
| 2669 |
# Error when the command is missing |
| 2670 |
self.assertArgumentParserError(parser.parse_args, ()) |
| 2671 |
|
| 2672 |
def test_required_subparsers_via_attribute(self): |
| 2673 |
parser = ErrorRaisingArgumentParser() |
| 2674 |
subparsers = parser.add_subparsers(dest='command') |
| 2675 |
subparsers.required = True |
| 2676 |
subparsers.add_parser('run') |
| 2677 |
self._test_required_subparsers(parser) |
| 2678 |
|
| 2679 |
def test_required_subparsers_via_kwarg(self): |
| 2680 |
parser = ErrorRaisingArgumentParser() |
| 2681 |
subparsers = parser.add_subparsers(dest='command', required=True) |
| 2682 |
subparsers.add_parser('run') |
| 2683 |
self._test_required_subparsers(parser) |
| 2684 |
|
| 2685 |
def test_required_subparsers_default(self): |
| 2686 |
parser = ErrorRaisingArgumentParser() |
| 2687 |
subparsers = parser.add_subparsers(dest='command') |
| 2688 |
subparsers.add_parser('run') |
| 2689 |
# No error here |
| 2690 |
ret = parser.parse_args(()) |
| 2691 |
self.assertIsNone(ret.command) |
| 2692 |
|
| 2693 |
def test_required_subparsers_no_destination_error(self): |
| 2694 |
parser = ErrorRaisingArgumentParser() |
| 2695 |
subparsers = parser.add_subparsers(required=True) |
| 2696 |
subparsers.add_parser('foo') |
| 2697 |
subparsers.add_parser('bar') |
| 2698 |
with self.assertRaises(ArgumentParserError) as excinfo: |
| 2699 |
parser.parse_args(()) |
| 2700 |
self.assertRegex( |
| 2701 |
excinfo.exception.stderr, |
| 2702 |
'error: the following arguments are required: {foo,bar}\n$' |
| 2703 |
) |
| 2704 |
|
| 2705 |
def test_optional_subparsers(self): |
| 2706 |
parser = ErrorRaisingArgumentParser() |
| 2707 |
subparsers = parser.add_subparsers(dest='command', required=False) |
| 2708 |
subparsers.add_parser('run') |
| 2709 |
# No error here |
| 2710 |
ret = parser.parse_args(()) |
| 2711 |
self.assertIsNone(ret.command) |
| 2712 |
|
| 2713 |
def test_help(self): |
| 2714 |
self.assertEqual(self.parser.format_usage(), |
| 2715 |
'usage: PROG [-h] [--foo] bar {1,2,3} ...\n') |
| 2716 |
self.assertEqual(self.parser.format_help(), textwrap.dedent('''\ |
| 2717 |
usage: PROG [-h] [--foo] bar {1,2,3} ... |
| 2718 |
|
| 2719 |
main description |
| 2720 |
|
| 2721 |
positional arguments: |
| 2722 |
bar bar help |
| 2723 |
{1,2,3} command help |
| 2724 |
|
| 2725 |
options: |
| 2726 |
-h, --help show this help message and exit |
| 2727 |
--foo foo help |
| 2728 |
''')) |
| 2729 |
|
| 2730 |
def test_help_extra_prefix_chars(self): |
| 2731 |
# Make sure - is still used for help if it is a non-first prefix char |
| 2732 |
parser = self._get_parser(prefix_chars='+:-') |
| 2733 |
self.assertEqual(parser.format_usage(), |
| 2734 |
'usage: PROG [-h] [++foo] bar {1,2,3} ...\n') |
| 2735 |
self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
| 2736 |
usage: PROG [-h] [++foo] bar {1,2,3} ... |
| 2737 |
|
| 2738 |
main description |
| 2739 |
|
| 2740 |
positional arguments: |
| 2741 |
bar bar help |
| 2742 |
{1,2,3} command help |
| 2743 |
|
| 2744 |
options: |
| 2745 |
-h, --help show this help message and exit |
| 2746 |
++foo foo help |
| 2747 |
''')) |
| 2748 |
|
| 2749 |
def test_help_non_breaking_spaces(self): |
| 2750 |
parser = ErrorRaisingArgumentParser( |
| 2751 |
prog='PROG', description='main description') |
| 2752 |
parser.add_argument( |
| 2753 |
"--non-breaking", action='store_false', |
| 2754 |
help='help message containing non-breaking spaces shall not ' |
| 2755 |
'wrap\N{NO-BREAK SPACE}at non-breaking spaces') |
| 2756 |
self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
| 2757 |
usage: PROG [-h] [--non-breaking] |
| 2758 |
|
| 2759 |
main description |
| 2760 |
|
| 2761 |
options: |
| 2762 |
-h, --help show this help message and exit |
| 2763 |
--non-breaking help message containing non-breaking spaces shall not |
| 2764 |
wrap\N{NO-BREAK SPACE}at non-breaking spaces |
| 2765 |
''')) |
| 2766 |
|
| 2767 |
def test_help_blank(self): |
| 2768 |
# Issue 24444 |
| 2769 |
parser = ErrorRaisingArgumentParser( |
| 2770 |
prog='PROG', description='main description') |
| 2771 |
parser.add_argument( |
| 2772 |
'foo', |
| 2773 |
help=' ') |
| 2774 |
self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
| 2775 |
usage: PROG [-h] foo |
| 2776 |
|
| 2777 |
main description |
| 2778 |
|
| 2779 |
positional arguments: |
| 2780 |
foo \n |
| 2781 |
options: |
| 2782 |
-h, --help show this help message and exit |
| 2783 |
''')) |
| 2784 |
|
| 2785 |
parser = ErrorRaisingArgumentParser( |
| 2786 |
prog='PROG', description='main description') |
| 2787 |
parser.add_argument( |
| 2788 |
'foo', choices=[], |
| 2789 |
help='%(choices)s') |
| 2790 |
self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
| 2791 |
usage: PROG [-h] {} |
| 2792 |
|
| 2793 |
main description |
| 2794 |
|
| 2795 |
positional arguments: |
| 2796 |
{} \n |
| 2797 |
options: |
| 2798 |
-h, --help show this help message and exit |
| 2799 |
''')) |
| 2800 |
|
| 2801 |
def test_help_alternate_prefix_chars(self): |
| 2802 |
parser = self._get_parser(prefix_chars='+:/') |
| 2803 |
self.assertEqual(parser.format_usage(), |
| 2804 |
'usage: PROG [+h] [++foo] bar {1,2,3} ...\n') |
| 2805 |
self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
| 2806 |
usage: PROG [+h] [++foo] bar {1,2,3} ... |
| 2807 |
|
| 2808 |
main description |
| 2809 |
|
| 2810 |
positional arguments: |
| 2811 |
bar bar help |
| 2812 |
{1,2,3} command help |
| 2813 |
|
| 2814 |
options: |
| 2815 |
+h, ++help show this help message and exit |
| 2816 |
++foo foo help |
| 2817 |
''')) |
| 2818 |
|
| 2819 |
def test_parser_command_help(self): |
| 2820 |
self.assertEqual(self.command_help_parser.format_usage(), |
| 2821 |
'usage: PROG [-h] [--foo] bar {1,2,3} ...\n') |
| 2822 |
self.assertEqual(self.command_help_parser.format_help(), |
| 2823 |
textwrap.dedent('''\ |
| 2824 |
usage: PROG [-h] [--foo] bar {1,2,3} ... |
| 2825 |
|
| 2826 |
main description |
| 2827 |
|
| 2828 |
positional arguments: |
| 2829 |
bar bar help |
| 2830 |
{1,2,3} command help |
| 2831 |
1 1 help |
| 2832 |
2 2 help |
| 2833 |
3 3 help |
| 2834 |
|
| 2835 |
options: |
| 2836 |
-h, --help show this help message and exit |
| 2837 |
--foo foo help |
| 2838 |
''')) |
| 2839 |
|
| 2840 |
def assert_bad_help(self, context_type, func, *args, **kwargs): |
| 2841 |
with self.assertRaisesRegex(ValueError, 'badly formed help string') as cm: |
| 2842 |
func(*args, **kwargs) |
| 2843 |
self.assertIsInstance(cm.exception.__context__, context_type) |
| 2844 |
|
| 2845 |
def test_invalid_subparsers_help(self): |
| 2846 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2847 |
self.assert_bad_help(ValueError, parser.add_subparsers, help='%Y-%m-%d') |
| 2848 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2849 |
self.assert_bad_help(KeyError, parser.add_subparsers, help='%(spam)s') |
| 2850 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2851 |
self.assert_bad_help(TypeError, parser.add_subparsers, help='%(prog)d') |
| 2852 |
|
| 2853 |
def test_invalid_subparser_help(self): |
| 2854 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 2855 |
subparsers = parser.add_subparsers() |
| 2856 |
self.assert_bad_help(ValueError, subparsers.add_parser, '1', |
| 2857 |
help='%Y-%m-%d') |
| 2858 |
self.assert_bad_help(KeyError, subparsers.add_parser, '1', |
| 2859 |
help='%(spam)s') |
| 2860 |
self.assert_bad_help(TypeError, subparsers.add_parser, '1', |
| 2861 |
help='%(prog)d') |
| 2862 |
|
| 2863 |
def test_subparser_title_help(self): |
| 2864 |
parser = ErrorRaisingArgumentParser(prog='PROG', |
| 2865 |
description='main description') |
| 2866 |
parser.add_argument('--foo', action='store_true', help='foo help') |
| 2867 |
parser.add_argument('bar', help='bar help') |
| 2868 |
subparsers = parser.add_subparsers(title='subcommands', |
| 2869 |
description='command help', |
| 2870 |
help='additional text') |
| 2871 |
parser1 = subparsers.add_parser('1') |
| 2872 |
parser2 = subparsers.add_parser('2') |
| 2873 |
self.assertEqual(parser.format_usage(), |
| 2874 |
'usage: PROG [-h] [--foo] bar {1,2} ...\n') |
| 2875 |
self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
| 2876 |
usage: PROG [-h] [--foo] bar {1,2} ... |
| 2877 |
|
| 2878 |
main description |
| 2879 |
|
| 2880 |
positional arguments: |
| 2881 |
bar bar help |
| 2882 |
|
| 2883 |
options: |
| 2884 |
-h, --help show this help message and exit |
| 2885 |
--foo foo help |
| 2886 |
|
| 2887 |
subcommands: |
| 2888 |
command help |
| 2889 |
|
| 2890 |
{1,2} additional text |
| 2891 |
''')) |
| 2892 |
|
| 2893 |
def _test_subparser_help(self, args_str, expected_help): |
| 2894 |
with self.assertRaises(ArgumentParserError) as cm: |
| 2895 |
self.parser.parse_args(args_str.split()) |
| 2896 |
self.assertEqual(expected_help, cm.exception.stdout) |
| 2897 |
|
| 2898 |
def test_subparser1_help(self): |
| 2899 |
self._test_subparser_help('5.0 1 -h', textwrap.dedent('''\ |
| 2900 |
usage: PROG bar 1 [-h] [-w W] {a,b,c} |
| 2901 |
|
| 2902 |
1 description |
| 2903 |
|
| 2904 |
positional arguments: |
| 2905 |
{a,b,c} x help |
| 2906 |
|
| 2907 |
options: |
| 2908 |
-h, --help show this help message and exit |
| 2909 |
-w W w help |
| 2910 |
''')) |
| 2911 |
|
| 2912 |
def test_subparser2_help(self): |
| 2913 |
self._test_subparser_help('5.0 2 -h', textwrap.dedent('''\ |
| 2914 |
usage: PROG bar 2 [-h] [-y {1,2,3}] [z ...] |
| 2915 |
|
| 2916 |
2 description |
| 2917 |
|
| 2918 |
positional arguments: |
| 2919 |
z z help |
| 2920 |
|
| 2921 |
options: |
| 2922 |
-h, --help show this help message and exit |
| 2923 |
-y {1,2,3} y help |
| 2924 |
''')) |
| 2925 |
|
| 2926 |
def test_alias_invocation(self): |
| 2927 |
parser = self._get_parser(aliases=True) |
| 2928 |
self.assertEqual( |
| 2929 |
parser.parse_known_args('0.5 1alias1 b'.split()), |
| 2930 |
(NS(foo=False, bar=0.5, w=None, x='b'), []), |
| 2931 |
) |
| 2932 |
self.assertEqual( |
| 2933 |
parser.parse_known_args('0.5 1alias2 b'.split()), |
| 2934 |
(NS(foo=False, bar=0.5, w=None, x='b'), []), |
| 2935 |
) |
| 2936 |
|
| 2937 |
def test_error_alias_invocation(self): |
| 2938 |
parser = self._get_parser(aliases=True) |
| 2939 |
self.assertArgumentParserError(parser.parse_args, |
| 2940 |
'0.5 1alias3 b'.split()) |
| 2941 |
|
| 2942 |
def test_alias_help(self): |
| 2943 |
parser = self._get_parser(aliases=True, subparser_help=True) |
| 2944 |
self.maxDiff = None |
| 2945 |
self.assertEqual(parser.format_help(), textwrap.dedent("""\ |
| 2946 |
usage: PROG [-h] [--foo] bar COMMAND ... |
| 2947 |
|
| 2948 |
main description |
| 2949 |
|
| 2950 |
positional arguments: |
| 2951 |
bar bar help |
| 2952 |
|
| 2953 |
options: |
| 2954 |
-h, --help show this help message and exit |
| 2955 |
--foo foo help |
| 2956 |
|
| 2957 |
commands: |
| 2958 |
COMMAND |
| 2959 |
1 (1alias1, 1alias2) |
| 2960 |
1 help |
| 2961 |
2 2 help |
| 2962 |
3 3 help |
| 2963 |
""")) |
| 2964 |
|
| 2965 |
# ============ |
| 2966 |
# Groups tests |
| 2967 |
# ============ |
| 2968 |
|
| 2969 |
class TestPositionalsGroups(TestCase): |
| 2970 |
"""Tests that order of group positionals matches construction order""" |
| 2971 |
|
| 2972 |
def test_nongroup_first(self): |
| 2973 |
parser = ErrorRaisingArgumentParser() |
| 2974 |
parser.add_argument('foo') |
| 2975 |
group = parser.add_argument_group('g') |
| 2976 |
group.add_argument('bar') |
| 2977 |
parser.add_argument('baz') |
| 2978 |
expected = NS(foo='1', bar='2', baz='3') |
| 2979 |
result = parser.parse_args('1 2 3'.split()) |
| 2980 |
self.assertEqual(expected, result) |
| 2981 |
|
| 2982 |
def test_group_first(self): |
| 2983 |
parser = ErrorRaisingArgumentParser() |
| 2984 |
group = parser.add_argument_group('xxx') |
| 2985 |
group.add_argument('foo') |
| 2986 |
parser.add_argument('bar') |
| 2987 |
parser.add_argument('baz') |
| 2988 |
expected = NS(foo='1', bar='2', baz='3') |
| 2989 |
result = parser.parse_args('1 2 3'.split()) |
| 2990 |
self.assertEqual(expected, result) |
| 2991 |
|
| 2992 |
def test_interleaved_groups(self): |
| 2993 |
parser = ErrorRaisingArgumentParser() |
| 2994 |
group = parser.add_argument_group('xxx') |
| 2995 |
parser.add_argument('foo') |
| 2996 |
group.add_argument('bar') |
| 2997 |
parser.add_argument('baz') |
| 2998 |
group = parser.add_argument_group('yyy') |
| 2999 |
group.add_argument('frell') |
| 3000 |
expected = NS(foo='1', bar='2', baz='3', frell='4') |
| 3001 |
result = parser.parse_args('1 2 3 4'.split()) |
| 3002 |
self.assertEqual(expected, result) |
| 3003 |
|
| 3004 |
class TestGroupConstructor(TestCase): |
| 3005 |
def test_group_prefix_chars(self): |
| 3006 |
parser = ErrorRaisingArgumentParser() |
| 3007 |
msg = ( |
| 3008 |
"The use of the undocumented 'prefix_chars' parameter in " |
| 3009 |
"ArgumentParser.add_argument_group() is deprecated." |
| 3010 |
) |
| 3011 |
with self.assertWarns(DeprecationWarning) as cm: |
| 3012 |
parser.add_argument_group(prefix_chars='-+') |
| 3013 |
self.assertEqual(msg, str(cm.warning)) |
| 3014 |
self.assertEqual(cm.filename, __file__) |
| 3015 |
|
| 3016 |
def test_group_prefix_chars_default(self): |
| 3017 |
# "default" isn't quite the right word here, but it's the same as |
| 3018 |
# the parser's default prefix so it's a good test |
| 3019 |
parser = ErrorRaisingArgumentParser() |
| 3020 |
msg = ( |
| 3021 |
"The use of the undocumented 'prefix_chars' parameter in " |
| 3022 |
"ArgumentParser.add_argument_group() is deprecated." |
| 3023 |
) |
| 3024 |
with self.assertWarns(DeprecationWarning) as cm: |
| 3025 |
parser.add_argument_group(prefix_chars='-') |
| 3026 |
self.assertEqual(msg, str(cm.warning)) |
| 3027 |
self.assertEqual(cm.filename, __file__) |
| 3028 |
|
| 3029 |
def test_nested_argument_group(self): |
| 3030 |
parser = argparse.ArgumentParser() |
| 3031 |
g = parser.add_argument_group() |
| 3032 |
self.assertRaisesRegex(ValueError, |
| 3033 |
'argument groups cannot be nested', |
| 3034 |
g.add_argument_group) |
| 3035 |
|
| 3036 |
# =================== |
| 3037 |
# Parent parser tests |
| 3038 |
# =================== |
| 3039 |
|
| 3040 |
@force_not_colorized_test_class |
| 3041 |
class TestParentParsers(TestCase): |
| 3042 |
"""Tests that parsers can be created with parent parsers""" |
| 3043 |
|
| 3044 |
def assertArgumentParserError(self, *args, **kwargs): |
| 3045 |
self.assertRaises(ArgumentParserError, *args, **kwargs) |
| 3046 |
|
| 3047 |
def setUp(self): |
| 3048 |
super().setUp() |
| 3049 |
self.wxyz_parent = ErrorRaisingArgumentParser(add_help=False) |
| 3050 |
self.wxyz_parent.add_argument('--w') |
| 3051 |
x_group = self.wxyz_parent.add_argument_group('x') |
| 3052 |
x_group.add_argument('-y') |
| 3053 |
self.wxyz_parent.add_argument('z') |
| 3054 |
|
| 3055 |
self.abcd_parent = ErrorRaisingArgumentParser(add_help=False) |
| 3056 |
self.abcd_parent.add_argument('a') |
| 3057 |
self.abcd_parent.add_argument('-b') |
| 3058 |
c_group = self.abcd_parent.add_argument_group('c') |
| 3059 |
c_group.add_argument('--d') |
| 3060 |
|
| 3061 |
self.w_parent = ErrorRaisingArgumentParser(add_help=False) |
| 3062 |
self.w_parent.add_argument('--w') |
| 3063 |
|
| 3064 |
self.z_parent = ErrorRaisingArgumentParser(add_help=False) |
| 3065 |
self.z_parent.add_argument('z') |
| 3066 |
|
| 3067 |
# parents with mutually exclusive groups |
| 3068 |
self.ab_mutex_parent = ErrorRaisingArgumentParser(add_help=False) |
| 3069 |
group = self.ab_mutex_parent.add_mutually_exclusive_group() |
| 3070 |
group.add_argument('-a', action='store_true') |
| 3071 |
group.add_argument('-b', action='store_true') |
| 3072 |
|
| 3073 |
def test_single_parent(self): |
| 3074 |
parser = ErrorRaisingArgumentParser(parents=[self.wxyz_parent]) |
| 3075 |
self.assertEqual(parser.parse_args('-y 1 2 --w 3'.split()), |
| 3076 |
NS(w='3', y='1', z='2')) |
| 3077 |
|
| 3078 |
def test_single_parent_mutex(self): |
| 3079 |
self._test_mutex_ab(self.ab_mutex_parent.parse_args) |
| 3080 |
parser = ErrorRaisingArgumentParser(parents=[self.ab_mutex_parent]) |
| 3081 |
self._test_mutex_ab(parser.parse_args) |
| 3082 |
|
| 3083 |
def test_single_grandparent_mutex(self): |
| 3084 |
parents = [self.ab_mutex_parent] |
| 3085 |
parser = ErrorRaisingArgumentParser(add_help=False, parents=parents) |
| 3086 |
parser = ErrorRaisingArgumentParser(parents=[parser]) |
| 3087 |
self._test_mutex_ab(parser.parse_args) |
| 3088 |
|
| 3089 |
def _test_mutex_ab(self, parse_args): |
| 3090 |
self.assertEqual(parse_args([]), NS(a=False, b=False)) |
| 3091 |
self.assertEqual(parse_args(['-a']), NS(a=True, b=False)) |
| 3092 |
self.assertEqual(parse_args(['-b']), NS(a=False, b=True)) |
| 3093 |
self.assertArgumentParserError(parse_args, ['-a', '-b']) |
| 3094 |
self.assertArgumentParserError(parse_args, ['-b', '-a']) |
| 3095 |
self.assertArgumentParserError(parse_args, ['-c']) |
| 3096 |
self.assertArgumentParserError(parse_args, ['-a', '-c']) |
| 3097 |
self.assertArgumentParserError(parse_args, ['-b', '-c']) |
| 3098 |
|
| 3099 |
def test_multiple_parents(self): |
| 3100 |
parents = [self.abcd_parent, self.wxyz_parent] |
| 3101 |
parser = ErrorRaisingArgumentParser(parents=parents) |
| 3102 |
self.assertEqual(parser.parse_args('--d 1 --w 2 3 4'.split()), |
| 3103 |
NS(a='3', b=None, d='1', w='2', y=None, z='4')) |
| 3104 |
|
| 3105 |
def test_multiple_parents_mutex(self): |
| 3106 |
parents = [self.ab_mutex_parent, self.wxyz_parent] |
| 3107 |
parser = ErrorRaisingArgumentParser(parents=parents) |
| 3108 |
self.assertEqual(parser.parse_args('-a --w 2 3'.split()), |
| 3109 |
NS(a=True, b=False, w='2', y=None, z='3')) |
| 3110 |
self.assertArgumentParserError( |
| 3111 |
parser.parse_args, '-a --w 2 3 -b'.split()) |
| 3112 |
self.assertArgumentParserError( |
| 3113 |
parser.parse_args, '-a -b --w 2 3'.split()) |
| 3114 |
|
| 3115 |
def test_conflicting_parents(self): |
| 3116 |
self.assertRaises( |
| 3117 |
argparse.ArgumentError, |
| 3118 |
argparse.ArgumentParser, |
| 3119 |
parents=[self.w_parent, self.wxyz_parent]) |
| 3120 |
|
| 3121 |
def test_conflicting_parents_mutex(self): |
| 3122 |
self.assertRaises( |
| 3123 |
argparse.ArgumentError, |
| 3124 |
argparse.ArgumentParser, |
| 3125 |
parents=[self.abcd_parent, self.ab_mutex_parent]) |
| 3126 |
|
| 3127 |
def test_same_argument_name_parents(self): |
| 3128 |
parents = [self.wxyz_parent, self.z_parent] |
| 3129 |
parser = ErrorRaisingArgumentParser(parents=parents) |
| 3130 |
self.assertEqual(parser.parse_args('1 2'.split()), |
| 3131 |
NS(w=None, y=None, z='2')) |
| 3132 |
|
| 3133 |
def test_subparser_parents(self): |
| 3134 |
parser = ErrorRaisingArgumentParser() |
| 3135 |
subparsers = parser.add_subparsers() |
| 3136 |
abcde_parser = subparsers.add_parser('bar', parents=[self.abcd_parent]) |
| 3137 |
abcde_parser.add_argument('e') |
| 3138 |
self.assertEqual(parser.parse_args('bar -b 1 --d 2 3 4'.split()), |
| 3139 |
NS(a='3', b='1', d='2', e='4')) |
| 3140 |
|
| 3141 |
def test_subparser_parents_mutex(self): |
| 3142 |
parser = ErrorRaisingArgumentParser() |
| 3143 |
subparsers = parser.add_subparsers() |
| 3144 |
parents = [self.ab_mutex_parent] |
| 3145 |
abc_parser = subparsers.add_parser('foo', parents=parents) |
| 3146 |
c_group = abc_parser.add_argument_group('c_group') |
| 3147 |
c_group.add_argument('c') |
| 3148 |
parents = [self.wxyz_parent, self.ab_mutex_parent] |
| 3149 |
wxyzabe_parser = subparsers.add_parser('bar', parents=parents) |
| 3150 |
wxyzabe_parser.add_argument('e') |
| 3151 |
self.assertEqual(parser.parse_args('foo -a 4'.split()), |
| 3152 |
NS(a=True, b=False, c='4')) |
| 3153 |
self.assertEqual(parser.parse_args('bar -b --w 2 3 4'.split()), |
| 3154 |
NS(a=False, b=True, w='2', y=None, z='3', e='4')) |
| 3155 |
self.assertArgumentParserError( |
| 3156 |
parser.parse_args, 'foo -a -b 4'.split()) |
| 3157 |
self.assertArgumentParserError( |
| 3158 |
parser.parse_args, 'bar -b -a 4'.split()) |
| 3159 |
|
| 3160 |
def test_parent_help(self): |
| 3161 |
parents = [self.abcd_parent, self.wxyz_parent] |
| 3162 |
parser = ErrorRaisingArgumentParser(prog='PROG', parents=parents) |
| 3163 |
parser_help = parser.format_help() |
| 3164 |
self.assertEqual(parser_help, textwrap.dedent('''\ |
| 3165 |
usage: PROG [-h] [-b B] [--d D] [--w W] [-y Y] a z |
| 3166 |
|
| 3167 |
positional arguments: |
| 3168 |
a |
| 3169 |
z |
| 3170 |
|
| 3171 |
options: |
| 3172 |
-h, --help show this help message and exit |
| 3173 |
-b B |
| 3174 |
--w W |
| 3175 |
|
| 3176 |
c: |
| 3177 |
--d D |
| 3178 |
|
| 3179 |
x: |
| 3180 |
-y Y |
| 3181 |
''')) |
| 3182 |
|
| 3183 |
def test_groups_parents(self): |
| 3184 |
parent = ErrorRaisingArgumentParser(add_help=False) |
| 3185 |
g = parent.add_argument_group(title='g', description='gd') |
| 3186 |
g.add_argument('-w') |
| 3187 |
g.add_argument('-x') |
| 3188 |
m = parent.add_mutually_exclusive_group() |
| 3189 |
m.add_argument('-y') |
| 3190 |
m.add_argument('-z') |
| 3191 |
parser = ErrorRaisingArgumentParser(prog='PROG', parents=[parent]) |
| 3192 |
|
| 3193 |
self.assertRaises(ArgumentParserError, parser.parse_args, |
| 3194 |
['-y', 'Y', '-z', 'Z']) |
| 3195 |
|
| 3196 |
parser_help = parser.format_help() |
| 3197 |
self.assertEqual(parser_help, textwrap.dedent('''\ |
| 3198 |
usage: PROG [-h] [-w W] [-x X] [-y Y | -z Z] |
| 3199 |
|
| 3200 |
options: |
| 3201 |
-h, --help show this help message and exit |
| 3202 |
-y Y |
| 3203 |
-z Z |
| 3204 |
|
| 3205 |
g: |
| 3206 |
gd |
| 3207 |
|
| 3208 |
-w W |
| 3209 |
-x X |
| 3210 |
''')) |
| 3211 |
|
| 3212 |
def test_wrong_type_parents(self): |
| 3213 |
self.assertRaises(TypeError, ErrorRaisingArgumentParser, parents=[1]) |
| 3214 |
|
| 3215 |
def test_mutex_groups_parents(self): |
| 3216 |
parent = ErrorRaisingArgumentParser(add_help=False) |
| 3217 |
g = parent.add_argument_group(title='g', description='gd') |
| 3218 |
g.add_argument('-w') |
| 3219 |
g.add_argument('-x') |
| 3220 |
m = g.add_mutually_exclusive_group() |
| 3221 |
m.add_argument('-y') |
| 3222 |
m.add_argument('-z') |
| 3223 |
parser = ErrorRaisingArgumentParser(prog='PROG', parents=[parent]) |
| 3224 |
|
| 3225 |
self.assertRaises(ArgumentParserError, parser.parse_args, |
| 3226 |
['-y', 'Y', '-z', 'Z']) |
| 3227 |
|
| 3228 |
parser_help = parser.format_help() |
| 3229 |
self.assertEqual(parser_help, textwrap.dedent('''\ |
| 3230 |
usage: PROG [-h] [-w W] [-x X] [-y Y | -z Z] |
| 3231 |
|
| 3232 |
options: |
| 3233 |
-h, --help show this help message and exit |
| 3234 |
|
| 3235 |
g: |
| 3236 |
gd |
| 3237 |
|
| 3238 |
-w W |
| 3239 |
-x X |
| 3240 |
-y Y |
| 3241 |
-z Z |
| 3242 |
''')) |
| 3243 |
|
| 3244 |
# ============================== |
| 3245 |
# Mutually exclusive group tests |
| 3246 |
# ============================== |
| 3247 |
|
| 3248 |
@force_not_colorized_test_class |
| 3249 |
class TestMutuallyExclusiveGroupErrors(TestCase): |
| 3250 |
|
| 3251 |
def test_invalid_add_argument_group(self): |
| 3252 |
parser = ErrorRaisingArgumentParser() |
| 3253 |
raises = self.assertRaises |
| 3254 |
raises(TypeError, parser.add_mutually_exclusive_group, title='foo') |
| 3255 |
|
| 3256 |
def test_invalid_add_argument(self): |
| 3257 |
parser = ErrorRaisingArgumentParser() |
| 3258 |
group = parser.add_mutually_exclusive_group() |
| 3259 |
add_argument = group.add_argument |
| 3260 |
raises = self.assertRaises |
| 3261 |
raises(ValueError, add_argument, '--foo', required=True) |
| 3262 |
raises(ValueError, add_argument, 'bar') |
| 3263 |
raises(ValueError, add_argument, 'bar', nargs='+') |
| 3264 |
raises(ValueError, add_argument, 'bar', nargs=1) |
| 3265 |
raises(ValueError, add_argument, 'bar', nargs=argparse.PARSER) |
| 3266 |
|
| 3267 |
def test_help(self): |
| 3268 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3269 |
group1 = parser.add_mutually_exclusive_group() |
| 3270 |
group1.add_argument('--foo', action='store_true') |
| 3271 |
group1.add_argument('--bar', action='store_false') |
| 3272 |
group2 = parser.add_mutually_exclusive_group() |
| 3273 |
group2.add_argument('--soup', action='store_true') |
| 3274 |
group2.add_argument('--nuts', action='store_false') |
| 3275 |
expected = '''\ |
| 3276 |
usage: PROG [-h] [--foo | --bar] [--soup | --nuts] |
| 3277 |
|
| 3278 |
options: |
| 3279 |
-h, --help show this help message and exit |
| 3280 |
--foo |
| 3281 |
--bar |
| 3282 |
--soup |
| 3283 |
--nuts |
| 3284 |
''' |
| 3285 |
self.assertEqual(parser.format_help(), textwrap.dedent(expected)) |
| 3286 |
|
| 3287 |
def test_optional_order(self): |
| 3288 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3289 |
group = parser.add_mutually_exclusive_group(required=True) |
| 3290 |
group.add_argument('--foo') |
| 3291 |
group.add_argument('bar', nargs='?') |
| 3292 |
expected = '''\ |
| 3293 |
usage: PROG [-h] (--foo FOO | bar) |
| 3294 |
|
| 3295 |
positional arguments: |
| 3296 |
bar |
| 3297 |
|
| 3298 |
options: |
| 3299 |
-h, --help show this help message and exit |
| 3300 |
--foo FOO |
| 3301 |
''' |
| 3302 |
self.assertEqual(parser.format_help(), textwrap.dedent(expected)) |
| 3303 |
|
| 3304 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3305 |
group = parser.add_mutually_exclusive_group(required=True) |
| 3306 |
group.add_argument('bar', nargs='?') |
| 3307 |
group.add_argument('--foo') |
| 3308 |
self.assertEqual(parser.format_help(), textwrap.dedent(expected)) |
| 3309 |
|
| 3310 |
def test_help_subparser_all_mutually_exclusive_group_members_suppressed(self): |
| 3311 |
self.maxDiff = None |
| 3312 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3313 |
commands = parser.add_subparsers(title="commands", dest="command") |
| 3314 |
cmd_foo = commands.add_parser("foo") |
| 3315 |
group = cmd_foo.add_mutually_exclusive_group() |
| 3316 |
group.add_argument('--verbose', action='store_true', help=argparse.SUPPRESS) |
| 3317 |
group.add_argument('--quiet', action='store_true', help=argparse.SUPPRESS) |
| 3318 |
longopt = '--' + 'long'*32 |
| 3319 |
longmeta = 'LONG'*32 |
| 3320 |
cmd_foo.add_argument(longopt) |
| 3321 |
expected = f'''\ |
| 3322 |
usage: PROG foo [-h] |
| 3323 |
[{longopt} {longmeta}] |
| 3324 |
|
| 3325 |
options: |
| 3326 |
-h, --help show this help message and exit |
| 3327 |
{longopt} {longmeta} |
| 3328 |
''' |
| 3329 |
self.assertEqual(cmd_foo.format_help(), textwrap.dedent(expected)) |
| 3330 |
|
| 3331 |
def test_usage_empty_group(self): |
| 3332 |
# See issue 26952 |
| 3333 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3334 |
group = parser.add_mutually_exclusive_group() |
| 3335 |
self.assertEqual(parser.format_usage(), 'usage: PROG [-h]\n') |
| 3336 |
|
| 3337 |
def test_nested_mutex_groups(self): |
| 3338 |
parser = argparse.ArgumentParser(prog='PROG') |
| 3339 |
g = parser.add_mutually_exclusive_group() |
| 3340 |
g.add_argument("--spam") |
| 3341 |
self.assertRaisesRegex(ValueError, |
| 3342 |
'mutually exclusive groups cannot be nested', |
| 3343 |
g.add_mutually_exclusive_group) |
| 3344 |
|
| 3345 |
class MEMixin(object): |
| 3346 |
|
| 3347 |
def test_failures_when_not_required(self): |
| 3348 |
parse_args = self.get_parser(required=False).parse_args |
| 3349 |
error = ArgumentParserError |
| 3350 |
for args_string in self.failures: |
| 3351 |
with self.subTest(args=args_string): |
| 3352 |
self.assertRaises(error, parse_args, args_string.split()) |
| 3353 |
|
| 3354 |
def test_failures_when_required(self): |
| 3355 |
parse_args = self.get_parser(required=True).parse_args |
| 3356 |
error = ArgumentParserError |
| 3357 |
for args_string in self.failures + ['']: |
| 3358 |
with self.subTest(args=args_string): |
| 3359 |
self.assertRaises(error, parse_args, args_string.split()) |
| 3360 |
|
| 3361 |
def test_successes_when_not_required(self): |
| 3362 |
parse_args = self.get_parser(required=False).parse_args |
| 3363 |
successes = self.successes + self.successes_when_not_required |
| 3364 |
for args_string, expected_ns in successes: |
| 3365 |
with self.subTest(args=args_string): |
| 3366 |
actual_ns = parse_args(args_string.split()) |
| 3367 |
self.assertEqual(actual_ns, expected_ns) |
| 3368 |
|
| 3369 |
def test_successes_when_required(self): |
| 3370 |
parse_args = self.get_parser(required=True).parse_args |
| 3371 |
for args_string, expected_ns in self.successes: |
| 3372 |
with self.subTest(args=args_string): |
| 3373 |
actual_ns = parse_args(args_string.split()) |
| 3374 |
self.assertEqual(actual_ns, expected_ns) |
| 3375 |
|
| 3376 |
@force_not_colorized |
| 3377 |
def test_usage_when_not_required(self): |
| 3378 |
format_usage = self.get_parser(required=False).format_usage |
| 3379 |
expected_usage = self.usage_when_not_required |
| 3380 |
self.assertEqual(format_usage(), textwrap.dedent(expected_usage)) |
| 3381 |
|
| 3382 |
@force_not_colorized |
| 3383 |
def test_usage_when_required(self): |
| 3384 |
format_usage = self.get_parser(required=True).format_usage |
| 3385 |
expected_usage = self.usage_when_required |
| 3386 |
self.assertEqual(format_usage(), textwrap.dedent(expected_usage)) |
| 3387 |
|
| 3388 |
@force_not_colorized |
| 3389 |
def test_help_when_not_required(self): |
| 3390 |
format_help = self.get_parser(required=False).format_help |
| 3391 |
help = self.usage_when_not_required + self.help |
| 3392 |
self.assertEqual(format_help(), textwrap.dedent(help)) |
| 3393 |
|
| 3394 |
@force_not_colorized |
| 3395 |
def test_help_when_required(self): |
| 3396 |
format_help = self.get_parser(required=True).format_help |
| 3397 |
help = self.usage_when_required + self.help |
| 3398 |
self.assertEqual(format_help(), textwrap.dedent(help)) |
| 3399 |
|
| 3400 |
|
| 3401 |
class TestMutuallyExclusiveSimple(MEMixin, TestCase): |
| 3402 |
|
| 3403 |
def get_parser(self, required=None): |
| 3404 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3405 |
group = parser.add_mutually_exclusive_group(required=required) |
| 3406 |
group.add_argument('--bar', help='bar help') |
| 3407 |
group.add_argument('--baz', nargs='?', const='Z', help='baz help') |
| 3408 |
return parser |
| 3409 |
|
| 3410 |
failures = ['--bar X --baz Y', '--bar X --baz'] |
| 3411 |
successes = [ |
| 3412 |
('--bar X', NS(bar='X', baz=None)), |
| 3413 |
('--bar X --bar Z', NS(bar='Z', baz=None)), |
| 3414 |
('--baz Y', NS(bar=None, baz='Y')), |
| 3415 |
('--baz', NS(bar=None, baz='Z')), |
| 3416 |
] |
| 3417 |
successes_when_not_required = [ |
| 3418 |
('', NS(bar=None, baz=None)), |
| 3419 |
] |
| 3420 |
|
| 3421 |
usage_when_not_required = '''\ |
| 3422 |
usage: PROG [-h] [--bar BAR | --baz [BAZ]] |
| 3423 |
''' |
| 3424 |
usage_when_required = '''\ |
| 3425 |
usage: PROG [-h] (--bar BAR | --baz [BAZ]) |
| 3426 |
''' |
| 3427 |
help = '''\ |
| 3428 |
|
| 3429 |
options: |
| 3430 |
-h, --help show this help message and exit |
| 3431 |
--bar BAR bar help |
| 3432 |
--baz [BAZ] baz help |
| 3433 |
''' |
| 3434 |
|
| 3435 |
|
| 3436 |
class TestMutuallyExclusiveLong(MEMixin, TestCase): |
| 3437 |
|
| 3438 |
def get_parser(self, required=None): |
| 3439 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3440 |
parser.add_argument('--abcde', help='abcde help') |
| 3441 |
parser.add_argument('--fghij', help='fghij help') |
| 3442 |
group = parser.add_mutually_exclusive_group(required=required) |
| 3443 |
group.add_argument('--klmno', help='klmno help') |
| 3444 |
group.add_argument('--pqrst', help='pqrst help') |
| 3445 |
return parser |
| 3446 |
|
| 3447 |
failures = ['--klmno X --pqrst Y'] |
| 3448 |
successes = [ |
| 3449 |
('--klmno X', NS(abcde=None, fghij=None, klmno='X', pqrst=None)), |
| 3450 |
('--abcde Y --klmno X', |
| 3451 |
NS(abcde='Y', fghij=None, klmno='X', pqrst=None)), |
| 3452 |
('--pqrst X', NS(abcde=None, fghij=None, klmno=None, pqrst='X')), |
| 3453 |
('--pqrst X --fghij Y', |
| 3454 |
NS(abcde=None, fghij='Y', klmno=None, pqrst='X')), |
| 3455 |
] |
| 3456 |
successes_when_not_required = [ |
| 3457 |
('', NS(abcde=None, fghij=None, klmno=None, pqrst=None)), |
| 3458 |
] |
| 3459 |
|
| 3460 |
usage_when_not_required = '''\ |
| 3461 |
usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ] [--klmno KLMNO | |
| 3462 |
--pqrst PQRST] |
| 3463 |
''' |
| 3464 |
usage_when_required = '''\ |
| 3465 |
usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ] (--klmno KLMNO | |
| 3466 |
--pqrst PQRST) |
| 3467 |
''' |
| 3468 |
help = '''\ |
| 3469 |
|
| 3470 |
options: |
| 3471 |
-h, --help show this help message and exit |
| 3472 |
--abcde ABCDE abcde help |
| 3473 |
--fghij FGHIJ fghij help |
| 3474 |
--klmno KLMNO klmno help |
| 3475 |
--pqrst PQRST pqrst help |
| 3476 |
''' |
| 3477 |
|
| 3478 |
|
| 3479 |
class TestMutuallyExclusiveFirstSuppressed(MEMixin, TestCase): |
| 3480 |
|
| 3481 |
def get_parser(self, required): |
| 3482 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3483 |
group = parser.add_mutually_exclusive_group(required=required) |
| 3484 |
group.add_argument('-x', help=argparse.SUPPRESS) |
| 3485 |
group.add_argument('-y', action='store_false', help='y help') |
| 3486 |
return parser |
| 3487 |
|
| 3488 |
failures = ['-x X -y'] |
| 3489 |
successes = [ |
| 3490 |
('-x X', NS(x='X', y=True)), |
| 3491 |
('-x X -x Y', NS(x='Y', y=True)), |
| 3492 |
('-y', NS(x=None, y=False)), |
| 3493 |
] |
| 3494 |
successes_when_not_required = [ |
| 3495 |
('', NS(x=None, y=True)), |
| 3496 |
] |
| 3497 |
|
| 3498 |
usage_when_not_required = '''\ |
| 3499 |
usage: PROG [-h] [-y] |
| 3500 |
''' |
| 3501 |
usage_when_required = '''\ |
| 3502 |
usage: PROG [-h] -y |
| 3503 |
''' |
| 3504 |
help = '''\ |
| 3505 |
|
| 3506 |
options: |
| 3507 |
-h, --help show this help message and exit |
| 3508 |
-y y help |
| 3509 |
''' |
| 3510 |
|
| 3511 |
|
| 3512 |
class TestMutuallyExclusiveManySuppressed(MEMixin, TestCase): |
| 3513 |
|
| 3514 |
def get_parser(self, required): |
| 3515 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3516 |
group = parser.add_mutually_exclusive_group(required=required) |
| 3517 |
add = group.add_argument |
| 3518 |
add('--spam', action='store_true', help=argparse.SUPPRESS) |
| 3519 |
add('--badger', action='store_false', help=argparse.SUPPRESS) |
| 3520 |
add('--bladder', help=argparse.SUPPRESS) |
| 3521 |
return parser |
| 3522 |
|
| 3523 |
failures = [ |
| 3524 |
'--spam --badger', |
| 3525 |
'--badger --bladder B', |
| 3526 |
'--bladder B --spam', |
| 3527 |
] |
| 3528 |
successes = [ |
| 3529 |
('--spam', NS(spam=True, badger=True, bladder=None)), |
| 3530 |
('--badger', NS(spam=False, badger=False, bladder=None)), |
| 3531 |
('--bladder B', NS(spam=False, badger=True, bladder='B')), |
| 3532 |
('--spam --spam', NS(spam=True, badger=True, bladder=None)), |
| 3533 |
] |
| 3534 |
successes_when_not_required = [ |
| 3535 |
('', NS(spam=False, badger=True, bladder=None)), |
| 3536 |
] |
| 3537 |
|
| 3538 |
usage_when_required = usage_when_not_required = '''\ |
| 3539 |
usage: PROG [-h] |
| 3540 |
''' |
| 3541 |
help = '''\ |
| 3542 |
|
| 3543 |
options: |
| 3544 |
-h, --help show this help message and exit |
| 3545 |
''' |
| 3546 |
|
| 3547 |
|
| 3548 |
class TestMutuallyExclusiveOptionalAndPositional(MEMixin, TestCase): |
| 3549 |
|
| 3550 |
def get_parser(self, required): |
| 3551 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3552 |
group = parser.add_mutually_exclusive_group(required=required) |
| 3553 |
group.add_argument('--foo', action='store_true', help='FOO') |
| 3554 |
group.add_argument('--spam', help='SPAM') |
| 3555 |
group.add_argument('badger', nargs='*', help='BADGER') |
| 3556 |
return parser |
| 3557 |
|
| 3558 |
failures = [ |
| 3559 |
'--foo --spam S', |
| 3560 |
'--spam S X', |
| 3561 |
'X --foo', |
| 3562 |
'X Y Z --spam S', |
| 3563 |
'--foo X Y', |
| 3564 |
] |
| 3565 |
successes = [ |
| 3566 |
('--foo', NS(foo=True, spam=None, badger=[])), |
| 3567 |
('--spam S', NS(foo=False, spam='S', badger=[])), |
| 3568 |
('X', NS(foo=False, spam=None, badger=['X'])), |
| 3569 |
('X Y Z', NS(foo=False, spam=None, badger=['X', 'Y', 'Z'])), |
| 3570 |
] |
| 3571 |
successes_when_not_required = [ |
| 3572 |
('', NS(foo=False, spam=None, badger=[])), |
| 3573 |
] |
| 3574 |
|
| 3575 |
usage_when_not_required = '''\ |
| 3576 |
usage: PROG [-h] [--foo | --spam SPAM | badger ...] |
| 3577 |
''' |
| 3578 |
usage_when_required = '''\ |
| 3579 |
usage: PROG [-h] (--foo | --spam SPAM | badger ...) |
| 3580 |
''' |
| 3581 |
help = '''\ |
| 3582 |
|
| 3583 |
positional arguments: |
| 3584 |
badger BADGER |
| 3585 |
|
| 3586 |
options: |
| 3587 |
-h, --help show this help message and exit |
| 3588 |
--foo FOO |
| 3589 |
--spam SPAM SPAM |
| 3590 |
''' |
| 3591 |
|
| 3592 |
|
| 3593 |
class TestMutuallyExclusiveOptionalsMixed(MEMixin, TestCase): |
| 3594 |
|
| 3595 |
def get_parser(self, required): |
| 3596 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3597 |
parser.add_argument('-x', action='store_true', help='x help') |
| 3598 |
group = parser.add_mutually_exclusive_group(required=required) |
| 3599 |
group.add_argument('-a', action='store_true', help='a help') |
| 3600 |
group.add_argument('-b', action='store_true', help='b help') |
| 3601 |
parser.add_argument('-y', action='store_true', help='y help') |
| 3602 |
group.add_argument('-c', action='store_true', help='c help') |
| 3603 |
parser.add_argument('-z', action='store_true', help='z help') |
| 3604 |
return parser |
| 3605 |
|
| 3606 |
failures = ['-a -b', '-b -c', '-a -c', '-a -b -c'] |
| 3607 |
successes = [ |
| 3608 |
('-a', NS(a=True, b=False, c=False, x=False, y=False, z=False)), |
| 3609 |
('-b', NS(a=False, b=True, c=False, x=False, y=False, z=False)), |
| 3610 |
('-c', NS(a=False, b=False, c=True, x=False, y=False, z=False)), |
| 3611 |
('-a -x', NS(a=True, b=False, c=False, x=True, y=False, z=False)), |
| 3612 |
('-y -b', NS(a=False, b=True, c=False, x=False, y=True, z=False)), |
| 3613 |
('-x -y -c', NS(a=False, b=False, c=True, x=True, y=True, z=False)), |
| 3614 |
] |
| 3615 |
successes_when_not_required = [ |
| 3616 |
('', NS(a=False, b=False, c=False, x=False, y=False, z=False)), |
| 3617 |
('-x', NS(a=False, b=False, c=False, x=True, y=False, z=False)), |
| 3618 |
('-y', NS(a=False, b=False, c=False, x=False, y=True, z=False)), |
| 3619 |
] |
| 3620 |
|
| 3621 |
usage_when_not_required = '''\ |
| 3622 |
usage: PROG [-h] [-x] [-a | -b | -c] [-y] [-z] |
| 3623 |
''' |
| 3624 |
usage_when_required = '''\ |
| 3625 |
usage: PROG [-h] [-x] (-a | -b | -c) [-y] [-z] |
| 3626 |
''' |
| 3627 |
help = '''\ |
| 3628 |
|
| 3629 |
options: |
| 3630 |
-h, --help show this help message and exit |
| 3631 |
-x x help |
| 3632 |
-a a help |
| 3633 |
-b b help |
| 3634 |
-y y help |
| 3635 |
-c c help |
| 3636 |
-z z help |
| 3637 |
''' |
| 3638 |
|
| 3639 |
|
| 3640 |
class TestMutuallyExclusiveInGroup(MEMixin, TestCase): |
| 3641 |
|
| 3642 |
def get_parser(self, required=None): |
| 3643 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3644 |
titled_group = parser.add_argument_group( |
| 3645 |
title='Titled group', description='Group description') |
| 3646 |
mutex_group = \ |
| 3647 |
titled_group.add_mutually_exclusive_group(required=required) |
| 3648 |
mutex_group.add_argument('--bar', help='bar help') |
| 3649 |
mutex_group.add_argument('--baz', help='baz help') |
| 3650 |
return parser |
| 3651 |
|
| 3652 |
failures = ['--bar X --baz Y', '--baz X --bar Y'] |
| 3653 |
successes = [ |
| 3654 |
('--bar X', NS(bar='X', baz=None)), |
| 3655 |
('--baz Y', NS(bar=None, baz='Y')), |
| 3656 |
] |
| 3657 |
successes_when_not_required = [ |
| 3658 |
('', NS(bar=None, baz=None)), |
| 3659 |
] |
| 3660 |
|
| 3661 |
usage_when_not_required = '''\ |
| 3662 |
usage: PROG [-h] [--bar BAR | --baz BAZ] |
| 3663 |
''' |
| 3664 |
usage_when_required = '''\ |
| 3665 |
usage: PROG [-h] (--bar BAR | --baz BAZ) |
| 3666 |
''' |
| 3667 |
help = '''\ |
| 3668 |
|
| 3669 |
options: |
| 3670 |
-h, --help show this help message and exit |
| 3671 |
|
| 3672 |
Titled group: |
| 3673 |
Group description |
| 3674 |
|
| 3675 |
--bar BAR bar help |
| 3676 |
--baz BAZ baz help |
| 3677 |
''' |
| 3678 |
|
| 3679 |
|
| 3680 |
class TestMutuallyExclusiveOptionalsAndPositionalsMixed(MEMixin, TestCase): |
| 3681 |
|
| 3682 |
def get_parser(self, required): |
| 3683 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3684 |
parser.add_argument('x', help='x help') |
| 3685 |
parser.add_argument('-y', action='store_true', help='y help') |
| 3686 |
group = parser.add_mutually_exclusive_group(required=required) |
| 3687 |
group.add_argument('a', nargs='?', help='a help') |
| 3688 |
group.add_argument('-b', action='store_true', help='b help') |
| 3689 |
group.add_argument('-c', action='store_true', help='c help') |
| 3690 |
parser.add_argument('-z', action='store_true', help='z help') |
| 3691 |
return parser |
| 3692 |
|
| 3693 |
failures = ['X A -b', '-b -c', '-c X A'] |
| 3694 |
successes = [ |
| 3695 |
('X A', NS(a='A', b=False, c=False, x='X', y=False, z=False)), |
| 3696 |
('X -b', NS(a=None, b=True, c=False, x='X', y=False, z=False)), |
| 3697 |
('X -c', NS(a=None, b=False, c=True, x='X', y=False, z=False)), |
| 3698 |
('X A -y', NS(a='A', b=False, c=False, x='X', y=True, z=False)), |
| 3699 |
('X -y -b', NS(a=None, b=True, c=False, x='X', y=True, z=False)), |
| 3700 |
] |
| 3701 |
successes_when_not_required = [ |
| 3702 |
('X', NS(a=None, b=False, c=False, x='X', y=False, z=False)), |
| 3703 |
('X -y', NS(a=None, b=False, c=False, x='X', y=True, z=False)), |
| 3704 |
] |
| 3705 |
|
| 3706 |
usage_when_not_required = '''\ |
| 3707 |
usage: PROG [-h] [-y] [-z] x [-b | -c | a] |
| 3708 |
''' |
| 3709 |
usage_when_required = '''\ |
| 3710 |
usage: PROG [-h] [-y] [-z] x (-b | -c | a) |
| 3711 |
''' |
| 3712 |
help = '''\ |
| 3713 |
|
| 3714 |
positional arguments: |
| 3715 |
x x help |
| 3716 |
a a help |
| 3717 |
|
| 3718 |
options: |
| 3719 |
-h, --help show this help message and exit |
| 3720 |
-y y help |
| 3721 |
-b b help |
| 3722 |
-c c help |
| 3723 |
-z z help |
| 3724 |
''' |
| 3725 |
|
| 3726 |
|
| 3727 |
class TestMutuallyExclusiveOptionalOptional(MEMixin, TestCase): |
| 3728 |
def get_parser(self, required=None): |
| 3729 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3730 |
group = parser.add_mutually_exclusive_group(required=required) |
| 3731 |
group.add_argument('--foo') |
| 3732 |
group.add_argument('--bar', nargs='?') |
| 3733 |
return parser |
| 3734 |
|
| 3735 |
failures = [ |
| 3736 |
'--foo X --bar Y', |
| 3737 |
'--foo X --bar', |
| 3738 |
] |
| 3739 |
successes = [ |
| 3740 |
('--foo X', NS(foo='X', bar=None)), |
| 3741 |
('--bar X', NS(foo=None, bar='X')), |
| 3742 |
('--bar', NS(foo=None, bar=None)), |
| 3743 |
] |
| 3744 |
successes_when_not_required = [ |
| 3745 |
('', NS(foo=None, bar=None)), |
| 3746 |
] |
| 3747 |
usage_when_required = '''\ |
| 3748 |
usage: PROG [-h] (--foo FOO | --bar [BAR]) |
| 3749 |
''' |
| 3750 |
usage_when_not_required = '''\ |
| 3751 |
usage: PROG [-h] [--foo FOO | --bar [BAR]] |
| 3752 |
''' |
| 3753 |
help = '''\ |
| 3754 |
|
| 3755 |
options: |
| 3756 |
-h, --help show this help message and exit |
| 3757 |
--foo FOO |
| 3758 |
--bar [BAR] |
| 3759 |
''' |
| 3760 |
|
| 3761 |
|
| 3762 |
class TestMutuallyExclusiveOptionalWithDefault(MEMixin, TestCase): |
| 3763 |
def get_parser(self, required=None): |
| 3764 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3765 |
group = parser.add_mutually_exclusive_group(required=required) |
| 3766 |
group.add_argument('--foo') |
| 3767 |
group.add_argument('--bar', type=bool, default=True) |
| 3768 |
return parser |
| 3769 |
|
| 3770 |
failures = [ |
| 3771 |
'--foo X --bar Y', |
| 3772 |
'--foo X --bar=', |
| 3773 |
] |
| 3774 |
successes = [ |
| 3775 |
('--foo X', NS(foo='X', bar=True)), |
| 3776 |
('--bar X', NS(foo=None, bar=True)), |
| 3777 |
('--bar=', NS(foo=None, bar=False)), |
| 3778 |
] |
| 3779 |
successes_when_not_required = [ |
| 3780 |
('', NS(foo=None, bar=True)), |
| 3781 |
] |
| 3782 |
usage_when_required = '''\ |
| 3783 |
usage: PROG [-h] (--foo FOO | --bar BAR) |
| 3784 |
''' |
| 3785 |
usage_when_not_required = '''\ |
| 3786 |
usage: PROG [-h] [--foo FOO | --bar BAR] |
| 3787 |
''' |
| 3788 |
help = '''\ |
| 3789 |
|
| 3790 |
options: |
| 3791 |
-h, --help show this help message and exit |
| 3792 |
--foo FOO |
| 3793 |
--bar BAR |
| 3794 |
''' |
| 3795 |
|
| 3796 |
|
| 3797 |
class TestMutuallyExclusivePositionalWithDefault(MEMixin, TestCase): |
| 3798 |
def get_parser(self, required=None): |
| 3799 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 3800 |
group = parser.add_mutually_exclusive_group(required=required) |
| 3801 |
group.add_argument('--foo') |
| 3802 |
group.add_argument('bar', nargs='?', type=bool, default=True) |
| 3803 |
return parser |
| 3804 |
|
| 3805 |
failures = [ |
| 3806 |
'--foo X Y', |
| 3807 |
] |
| 3808 |
successes = [ |
| 3809 |
('--foo X', NS(foo='X', bar=True)), |
| 3810 |
('X', NS(foo=None, bar=True)), |
| 3811 |
] |
| 3812 |
successes_when_not_required = [ |
| 3813 |
('', NS(foo=None, bar=True)), |
| 3814 |
] |
| 3815 |
usage_when_required = '''\ |
| 3816 |
usage: PROG [-h] (--foo FOO | bar) |
| 3817 |
''' |
| 3818 |
usage_when_not_required = '''\ |
| 3819 |
usage: PROG [-h] [--foo FOO | bar] |
| 3820 |
''' |
| 3821 |
help = '''\ |
| 3822 |
|
| 3823 |
positional arguments: |
| 3824 |
bar |
| 3825 |
|
| 3826 |
options: |
| 3827 |
-h, --help show this help message and exit |
| 3828 |
--foo FOO |
| 3829 |
''' |
| 3830 |
|
| 3831 |
# ================================================= |
| 3832 |
# Mutually exclusive group in parent parser tests |
| 3833 |
# ================================================= |
| 3834 |
|
| 3835 |
class MEPBase(object): |
| 3836 |
|
| 3837 |
def get_parser(self, required=None): |
| 3838 |
parent = super(MEPBase, self).get_parser(required=required) |
| 3839 |
parser = ErrorRaisingArgumentParser( |
| 3840 |
prog=parent.prog, add_help=False, parents=[parent]) |
| 3841 |
return parser |
| 3842 |
|
| 3843 |
|
| 3844 |
class TestMutuallyExclusiveGroupErrorsParent( |
| 3845 |
MEPBase, TestMutuallyExclusiveGroupErrors): |
| 3846 |
pass |
| 3847 |
|
| 3848 |
|
| 3849 |
class TestMutuallyExclusiveSimpleParent( |
| 3850 |
MEPBase, TestMutuallyExclusiveSimple): |
| 3851 |
pass |
| 3852 |
|
| 3853 |
|
| 3854 |
class TestMutuallyExclusiveLongParent( |
| 3855 |
MEPBase, TestMutuallyExclusiveLong): |
| 3856 |
pass |
| 3857 |
|
| 3858 |
|
| 3859 |
class TestMutuallyExclusiveFirstSuppressedParent( |
| 3860 |
MEPBase, TestMutuallyExclusiveFirstSuppressed): |
| 3861 |
pass |
| 3862 |
|
| 3863 |
|
| 3864 |
class TestMutuallyExclusiveManySuppressedParent( |
| 3865 |
MEPBase, TestMutuallyExclusiveManySuppressed): |
| 3866 |
pass |
| 3867 |
|
| 3868 |
|
| 3869 |
class TestMutuallyExclusiveOptionalAndPositionalParent( |
| 3870 |
MEPBase, TestMutuallyExclusiveOptionalAndPositional): |
| 3871 |
pass |
| 3872 |
|
| 3873 |
|
| 3874 |
class TestMutuallyExclusiveOptionalsMixedParent( |
| 3875 |
MEPBase, TestMutuallyExclusiveOptionalsMixed): |
| 3876 |
pass |
| 3877 |
|
| 3878 |
|
| 3879 |
class TestMutuallyExclusiveOptionalsAndPositionalsMixedParent( |
| 3880 |
MEPBase, TestMutuallyExclusiveOptionalsAndPositionalsMixed): |
| 3881 |
pass |
| 3882 |
|
| 3883 |
# ================= |
| 3884 |
# Set default tests |
| 3885 |
# ================= |
| 3886 |
|
| 3887 |
class TestSetDefaults(TestCase): |
| 3888 |
|
| 3889 |
def test_set_defaults_no_args(self): |
| 3890 |
parser = ErrorRaisingArgumentParser() |
| 3891 |
parser.set_defaults(x='foo') |
| 3892 |
parser.set_defaults(y='bar', z=1) |
| 3893 |
self.assertEqual(NS(x='foo', y='bar', z=1), |
| 3894 |
parser.parse_args([])) |
| 3895 |
self.assertEqual(NS(x='foo', y='bar', z=1), |
| 3896 |
parser.parse_args([], NS())) |
| 3897 |
self.assertEqual(NS(x='baz', y='bar', z=1), |
| 3898 |
parser.parse_args([], NS(x='baz'))) |
| 3899 |
self.assertEqual(NS(x='baz', y='bar', z=2), |
| 3900 |
parser.parse_args([], NS(x='baz', z=2))) |
| 3901 |
|
| 3902 |
def test_set_defaults_with_args(self): |
| 3903 |
parser = ErrorRaisingArgumentParser() |
| 3904 |
parser.set_defaults(x='foo', y='bar') |
| 3905 |
parser.add_argument('-x', default='xfoox') |
| 3906 |
self.assertEqual(NS(x='xfoox', y='bar'), |
| 3907 |
parser.parse_args([])) |
| 3908 |
self.assertEqual(NS(x='xfoox', y='bar'), |
| 3909 |
parser.parse_args([], NS())) |
| 3910 |
self.assertEqual(NS(x='baz', y='bar'), |
| 3911 |
parser.parse_args([], NS(x='baz'))) |
| 3912 |
self.assertEqual(NS(x='1', y='bar'), |
| 3913 |
parser.parse_args('-x 1'.split())) |
| 3914 |
self.assertEqual(NS(x='1', y='bar'), |
| 3915 |
parser.parse_args('-x 1'.split(), NS())) |
| 3916 |
self.assertEqual(NS(x='1', y='bar'), |
| 3917 |
parser.parse_args('-x 1'.split(), NS(x='baz'))) |
| 3918 |
|
| 3919 |
def test_set_defaults_subparsers(self): |
| 3920 |
parser = ErrorRaisingArgumentParser() |
| 3921 |
parser.set_defaults(x='foo') |
| 3922 |
subparsers = parser.add_subparsers() |
| 3923 |
parser_a = subparsers.add_parser('a') |
| 3924 |
parser_a.set_defaults(y='bar') |
| 3925 |
self.assertEqual(NS(x='foo', y='bar'), |
| 3926 |
parser.parse_args('a'.split())) |
| 3927 |
|
| 3928 |
def test_set_defaults_parents(self): |
| 3929 |
parent = ErrorRaisingArgumentParser(add_help=False) |
| 3930 |
parent.set_defaults(x='foo') |
| 3931 |
parser = ErrorRaisingArgumentParser(parents=[parent]) |
| 3932 |
self.assertEqual(NS(x='foo'), parser.parse_args([])) |
| 3933 |
|
| 3934 |
def test_set_defaults_on_parent_and_subparser(self): |
| 3935 |
parser = argparse.ArgumentParser() |
| 3936 |
xparser = parser.add_subparsers().add_parser('X') |
| 3937 |
parser.set_defaults(foo=1) |
| 3938 |
xparser.set_defaults(foo=2) |
| 3939 |
self.assertEqual(NS(foo=2), parser.parse_args(['X'])) |
| 3940 |
|
| 3941 |
def test_set_defaults_same_as_add_argument(self): |
| 3942 |
parser = ErrorRaisingArgumentParser() |
| 3943 |
parser.set_defaults(w='W', x='X', y='Y', z='Z') |
| 3944 |
parser.add_argument('-w') |
| 3945 |
parser.add_argument('-x', default='XX') |
| 3946 |
parser.add_argument('y', nargs='?') |
| 3947 |
parser.add_argument('z', nargs='?', default='ZZ') |
| 3948 |
|
| 3949 |
# defaults set previously |
| 3950 |
self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'), |
| 3951 |
parser.parse_args([])) |
| 3952 |
|
| 3953 |
# reset defaults |
| 3954 |
parser.set_defaults(w='WW', x='X', y='YY', z='Z') |
| 3955 |
self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'), |
| 3956 |
parser.parse_args([])) |
| 3957 |
|
| 3958 |
def test_set_defaults_same_as_add_argument_group(self): |
| 3959 |
parser = ErrorRaisingArgumentParser() |
| 3960 |
parser.set_defaults(w='W', x='X', y='Y', z='Z') |
| 3961 |
group = parser.add_argument_group('foo') |
| 3962 |
group.add_argument('-w') |
| 3963 |
group.add_argument('-x', default='XX') |
| 3964 |
group.add_argument('y', nargs='?') |
| 3965 |
group.add_argument('z', nargs='?', default='ZZ') |
| 3966 |
|
| 3967 |
|
| 3968 |
# defaults set previously |
| 3969 |
self.assertEqual(NS(w='W', x='XX', y='Y', z='ZZ'), |
| 3970 |
parser.parse_args([])) |
| 3971 |
|
| 3972 |
# reset defaults |
| 3973 |
parser.set_defaults(w='WW', x='X', y='YY', z='Z') |
| 3974 |
self.assertEqual(NS(w='WW', x='X', y='YY', z='Z'), |
| 3975 |
parser.parse_args([])) |
| 3976 |
|
| 3977 |
# ================= |
| 3978 |
# Get default tests |
| 3979 |
# ================= |
| 3980 |
|
| 3981 |
class TestGetDefault(TestCase): |
| 3982 |
|
| 3983 |
def test_get_default(self): |
| 3984 |
parser = ErrorRaisingArgumentParser() |
| 3985 |
self.assertIsNone(parser.get_default("foo")) |
| 3986 |
self.assertIsNone(parser.get_default("bar")) |
| 3987 |
|
| 3988 |
parser.add_argument("--foo") |
| 3989 |
self.assertIsNone(parser.get_default("foo")) |
| 3990 |
self.assertIsNone(parser.get_default("bar")) |
| 3991 |
|
| 3992 |
parser.add_argument("--bar", type=int, default=42) |
| 3993 |
self.assertIsNone(parser.get_default("foo")) |
| 3994 |
self.assertEqual(42, parser.get_default("bar")) |
| 3995 |
|
| 3996 |
parser.set_defaults(foo="badger") |
| 3997 |
self.assertEqual("badger", parser.get_default("foo")) |
| 3998 |
self.assertEqual(42, parser.get_default("bar")) |
| 3999 |
|
| 4000 |
# ========================== |
| 4001 |
# Namespace 'contains' tests |
| 4002 |
# ========================== |
| 4003 |
|
| 4004 |
class TestNamespaceContainsSimple(TestCase): |
| 4005 |
|
| 4006 |
def test_empty(self): |
| 4007 |
ns = argparse.Namespace() |
| 4008 |
self.assertNotIn('', ns) |
| 4009 |
self.assertNotIn('x', ns) |
| 4010 |
|
| 4011 |
def test_non_empty(self): |
| 4012 |
ns = argparse.Namespace(x=1, y=2) |
| 4013 |
self.assertNotIn('', ns) |
| 4014 |
self.assertIn('x', ns) |
| 4015 |
self.assertIn('y', ns) |
| 4016 |
self.assertNotIn('xx', ns) |
| 4017 |
self.assertNotIn('z', ns) |
| 4018 |
|
| 4019 |
# ===================== |
| 4020 |
# Help formatting tests |
| 4021 |
# ===================== |
| 4022 |
|
| 4023 |
class TestHelpFormattingMetaclass(type): |
| 4024 |
|
| 4025 |
def __init__(cls, name, bases, bodydict): |
| 4026 |
if name == 'HelpTestCase': |
| 4027 |
return |
| 4028 |
|
| 4029 |
class AddTests(object): |
| 4030 |
|
| 4031 |
def __init__(self, test_class, func_suffix, std_name): |
| 4032 |
self.func_suffix = func_suffix |
| 4033 |
self.std_name = std_name |
| 4034 |
|
| 4035 |
for test_func in [self.test_format, |
| 4036 |
self.test_print, |
| 4037 |
self.test_print_file]: |
| 4038 |
test_name = '%s_%s' % (test_func.__name__, func_suffix) |
| 4039 |
|
| 4040 |
def test_wrapper(self, test_func=test_func): |
| 4041 |
test_func(self) |
| 4042 |
try: |
| 4043 |
test_wrapper.__name__ = test_name |
| 4044 |
except TypeError: |
| 4045 |
pass |
| 4046 |
setattr(test_class, test_name, test_wrapper) |
| 4047 |
|
| 4048 |
def _get_parser(self, tester): |
| 4049 |
parser = argparse.ArgumentParser( |
| 4050 |
*tester.parser_signature.args, |
| 4051 |
**tester.parser_signature.kwargs) |
| 4052 |
for argument_sig in getattr(tester, 'argument_signatures', []): |
| 4053 |
parser.add_argument(*argument_sig.args, |
| 4054 |
**argument_sig.kwargs) |
| 4055 |
group_sigs = getattr(tester, 'argument_group_signatures', []) |
| 4056 |
for group_sig, argument_sigs in group_sigs: |
| 4057 |
group = parser.add_argument_group(*group_sig.args, |
| 4058 |
**group_sig.kwargs) |
| 4059 |
for argument_sig in argument_sigs: |
| 4060 |
group.add_argument(*argument_sig.args, |
| 4061 |
**argument_sig.kwargs) |
| 4062 |
subparsers_sigs = getattr(tester, 'subparsers_signatures', []) |
| 4063 |
if subparsers_sigs: |
| 4064 |
subparsers = parser.add_subparsers() |
| 4065 |
for subparser_sig in subparsers_sigs: |
| 4066 |
subparsers.add_parser(*subparser_sig.args, |
| 4067 |
**subparser_sig.kwargs) |
| 4068 |
return parser |
| 4069 |
|
| 4070 |
def _test(self, tester, parser_text): |
| 4071 |
expected_text = getattr(tester, self.func_suffix) |
| 4072 |
expected_text = textwrap.dedent(expected_text) |
| 4073 |
tester.maxDiff = None |
| 4074 |
tester.assertEqual(expected_text, parser_text) |
| 4075 |
|
| 4076 |
@force_not_colorized |
| 4077 |
def test_format(self, tester): |
| 4078 |
parser = self._get_parser(tester) |
| 4079 |
format = getattr(parser, 'format_%s' % self.func_suffix) |
| 4080 |
self._test(tester, format()) |
| 4081 |
|
| 4082 |
@force_not_colorized |
| 4083 |
def test_print(self, tester): |
| 4084 |
parser = self._get_parser(tester) |
| 4085 |
print_ = getattr(parser, 'print_%s' % self.func_suffix) |
| 4086 |
old_stream = getattr(sys, self.std_name) |
| 4087 |
setattr(sys, self.std_name, StdIOBuffer()) |
| 4088 |
try: |
| 4089 |
print_() |
| 4090 |
parser_text = getattr(sys, self.std_name).getvalue() |
| 4091 |
finally: |
| 4092 |
setattr(sys, self.std_name, old_stream) |
| 4093 |
self._test(tester, parser_text) |
| 4094 |
|
| 4095 |
@force_not_colorized |
| 4096 |
def test_print_file(self, tester): |
| 4097 |
parser = self._get_parser(tester) |
| 4098 |
print_ = getattr(parser, 'print_%s' % self.func_suffix) |
| 4099 |
sfile = StdIOBuffer() |
| 4100 |
print_(sfile) |
| 4101 |
parser_text = sfile.getvalue() |
| 4102 |
self._test(tester, parser_text) |
| 4103 |
|
| 4104 |
# add tests for {format,print}_{usage,help} |
| 4105 |
for func_suffix, std_name in [('usage', 'stdout'), |
| 4106 |
('help', 'stdout')]: |
| 4107 |
AddTests(cls, func_suffix, std_name) |
| 4108 |
|
| 4109 |
bases = TestCase, |
| 4110 |
HelpTestCase = TestHelpFormattingMetaclass('HelpTestCase', bases, {}) |
| 4111 |
|
| 4112 |
|
| 4113 |
class TestHelpBiggerOptionals(HelpTestCase): |
| 4114 |
"""Make sure that argument help aligns when options are longer""" |
| 4115 |
|
| 4116 |
parser_signature = Sig(prog='PROG', description='DESCRIPTION', |
| 4117 |
epilog='EPILOG') |
| 4118 |
argument_signatures = [ |
| 4119 |
Sig('-v', '--version', action='version', version='0.1'), |
| 4120 |
Sig('-x', action='store_true', help='X HELP'), |
| 4121 |
Sig('--y', help='Y HELP'), |
| 4122 |
Sig('foo', help='FOO HELP'), |
| 4123 |
Sig('bar', help='BAR HELP'), |
| 4124 |
] |
| 4125 |
argument_group_signatures = [] |
| 4126 |
usage = '''\ |
| 4127 |
usage: PROG [-h] [-v] [-x] [--y Y] foo bar |
| 4128 |
''' |
| 4129 |
help = usage + '''\ |
| 4130 |
|
| 4131 |
DESCRIPTION |
| 4132 |
|
| 4133 |
positional arguments: |
| 4134 |
foo FOO HELP |
| 4135 |
bar BAR HELP |
| 4136 |
|
| 4137 |
options: |
| 4138 |
-h, --help show this help message and exit |
| 4139 |
-v, --version show program's version number and exit |
| 4140 |
-x X HELP |
| 4141 |
--y Y Y HELP |
| 4142 |
|
| 4143 |
EPILOG |
| 4144 |
''' |
| 4145 |
version = '''\ |
| 4146 |
0.1 |
| 4147 |
''' |
| 4148 |
|
| 4149 |
class TestShortColumns(HelpTestCase): |
| 4150 |
'''Test extremely small number of columns. |
| 4151 |
|
| 4152 |
TestCase prevents "COLUMNS" from being too small in the tests themselves, |
| 4153 |
but we don't want any exceptions thrown in such cases. Only ugly representation. |
| 4154 |
''' |
| 4155 |
def setUp(self): |
| 4156 |
env = self.enterContext(os_helper.EnvironmentVarGuard()) |
| 4157 |
env.set("COLUMNS", '15') |
| 4158 |
|
| 4159 |
parser_signature = TestHelpBiggerOptionals.parser_signature |
| 4160 |
argument_signatures = TestHelpBiggerOptionals.argument_signatures |
| 4161 |
argument_group_signatures = TestHelpBiggerOptionals.argument_group_signatures |
| 4162 |
usage = '''\ |
| 4163 |
usage: PROG |
| 4164 |
[-h] |
| 4165 |
[-v] |
| 4166 |
[-x] |
| 4167 |
[--y Y] |
| 4168 |
foo |
| 4169 |
bar |
| 4170 |
''' |
| 4171 |
help = usage + '''\ |
| 4172 |
|
| 4173 |
DESCRIPTION |
| 4174 |
|
| 4175 |
positional arguments: |
| 4176 |
foo |
| 4177 |
FOO HELP |
| 4178 |
bar |
| 4179 |
BAR HELP |
| 4180 |
|
| 4181 |
options: |
| 4182 |
-h, --help |
| 4183 |
show this |
| 4184 |
help |
| 4185 |
message and |
| 4186 |
exit |
| 4187 |
-v, --version |
| 4188 |
show |
| 4189 |
program's |
| 4190 |
version |
| 4191 |
number and |
| 4192 |
exit |
| 4193 |
-x |
| 4194 |
X HELP |
| 4195 |
--y Y |
| 4196 |
Y HELP |
| 4197 |
|
| 4198 |
EPILOG |
| 4199 |
''' |
| 4200 |
version = TestHelpBiggerOptionals.version |
| 4201 |
|
| 4202 |
|
| 4203 |
class TestHelpBiggerOptionalGroups(HelpTestCase): |
| 4204 |
"""Make sure that argument help aligns when options are longer""" |
| 4205 |
|
| 4206 |
parser_signature = Sig(prog='PROG', description='DESCRIPTION', |
| 4207 |
epilog='EPILOG') |
| 4208 |
argument_signatures = [ |
| 4209 |
Sig('-v', '--version', action='version', version='0.1'), |
| 4210 |
Sig('-x', action='store_true', help='X HELP'), |
| 4211 |
Sig('--y', help='Y HELP'), |
| 4212 |
Sig('foo', help='FOO HELP'), |
| 4213 |
Sig('bar', help='BAR HELP'), |
| 4214 |
] |
| 4215 |
argument_group_signatures = [ |
| 4216 |
(Sig('GROUP TITLE', description='GROUP DESCRIPTION'), [ |
| 4217 |
Sig('baz', help='BAZ HELP'), |
| 4218 |
Sig('-z', nargs='+', help='Z HELP')]), |
| 4219 |
] |
| 4220 |
usage = '''\ |
| 4221 |
usage: PROG [-h] [-v] [-x] [--y Y] [-z Z [Z ...]] foo bar baz |
| 4222 |
''' |
| 4223 |
help = usage + '''\ |
| 4224 |
|
| 4225 |
DESCRIPTION |
| 4226 |
|
| 4227 |
positional arguments: |
| 4228 |
foo FOO HELP |
| 4229 |
bar BAR HELP |
| 4230 |
|
| 4231 |
options: |
| 4232 |
-h, --help show this help message and exit |
| 4233 |
-v, --version show program's version number and exit |
| 4234 |
-x X HELP |
| 4235 |
--y Y Y HELP |
| 4236 |
|
| 4237 |
GROUP TITLE: |
| 4238 |
GROUP DESCRIPTION |
| 4239 |
|
| 4240 |
baz BAZ HELP |
| 4241 |
-z Z [Z ...] Z HELP |
| 4242 |
|
| 4243 |
EPILOG |
| 4244 |
''' |
| 4245 |
version = '''\ |
| 4246 |
0.1 |
| 4247 |
''' |
| 4248 |
|
| 4249 |
|
| 4250 |
class TestHelpBiggerPositionals(HelpTestCase): |
| 4251 |
"""Make sure that help aligns when arguments are longer""" |
| 4252 |
|
| 4253 |
parser_signature = Sig(usage='USAGE', description='DESCRIPTION') |
| 4254 |
argument_signatures = [ |
| 4255 |
Sig('-x', action='store_true', help='X HELP'), |
| 4256 |
Sig('--y', help='Y HELP'), |
| 4257 |
Sig('ekiekiekifekang', help='EKI HELP'), |
| 4258 |
Sig('bar', help='BAR HELP'), |
| 4259 |
] |
| 4260 |
argument_group_signatures = [] |
| 4261 |
usage = '''\ |
| 4262 |
usage: USAGE |
| 4263 |
''' |
| 4264 |
help = usage + '''\ |
| 4265 |
|
| 4266 |
DESCRIPTION |
| 4267 |
|
| 4268 |
positional arguments: |
| 4269 |
ekiekiekifekang EKI HELP |
| 4270 |
bar BAR HELP |
| 4271 |
|
| 4272 |
options: |
| 4273 |
-h, --help show this help message and exit |
| 4274 |
-x X HELP |
| 4275 |
--y Y Y HELP |
| 4276 |
''' |
| 4277 |
|
| 4278 |
version = '' |
| 4279 |
|
| 4280 |
|
| 4281 |
class TestHelpReformatting(HelpTestCase): |
| 4282 |
"""Make sure that text after short names starts on the first line""" |
| 4283 |
|
| 4284 |
parser_signature = Sig( |
| 4285 |
prog='PROG', |
| 4286 |
description=' oddly formatted\n' |
| 4287 |
'description\n' |
| 4288 |
'\n' |
| 4289 |
'that is so long that it should go onto multiple ' |
| 4290 |
'lines when wrapped') |
| 4291 |
argument_signatures = [ |
| 4292 |
Sig('-x', metavar='XX', help='oddly\n' |
| 4293 |
' formatted -x help'), |
| 4294 |
Sig('y', metavar='yyy', help='normal y help'), |
| 4295 |
] |
| 4296 |
argument_group_signatures = [ |
| 4297 |
(Sig('title', description='\n' |
| 4298 |
' oddly formatted group\n' |
| 4299 |
'\n' |
| 4300 |
'description'), |
| 4301 |
[Sig('-a', action='store_true', |
| 4302 |
help=' oddly \n' |
| 4303 |
'formatted -a help \n' |
| 4304 |
' again, so long that it should be wrapped over ' |
| 4305 |
'multiple lines')]), |
| 4306 |
] |
| 4307 |
usage = '''\ |
| 4308 |
usage: PROG [-h] [-x XX] [-a] yyy |
| 4309 |
''' |
| 4310 |
help = usage + '''\ |
| 4311 |
|
| 4312 |
oddly formatted description that is so long that it should go onto \ |
| 4313 |
multiple |
| 4314 |
lines when wrapped |
| 4315 |
|
| 4316 |
positional arguments: |
| 4317 |
yyy normal y help |
| 4318 |
|
| 4319 |
options: |
| 4320 |
-h, --help show this help message and exit |
| 4321 |
-x XX oddly formatted -x help |
| 4322 |
|
| 4323 |
title: |
| 4324 |
oddly formatted group description |
| 4325 |
|
| 4326 |
-a oddly formatted -a help again, so long that it should \ |
| 4327 |
be wrapped |
| 4328 |
over multiple lines |
| 4329 |
''' |
| 4330 |
version = '' |
| 4331 |
|
| 4332 |
|
| 4333 |
class TestHelpWrappingShortNames(HelpTestCase): |
| 4334 |
"""Make sure that text after short names starts on the first line""" |
| 4335 |
|
| 4336 |
parser_signature = Sig(prog='PROG', description= 'D\nD' * 30) |
| 4337 |
argument_signatures = [ |
| 4338 |
Sig('-x', metavar='XX', help='XHH HX' * 20), |
| 4339 |
Sig('y', metavar='yyy', help='YH YH' * 20), |
| 4340 |
] |
| 4341 |
argument_group_signatures = [ |
| 4342 |
(Sig('ALPHAS'), [ |
| 4343 |
Sig('-a', action='store_true', help='AHHH HHA' * 10)]), |
| 4344 |
] |
| 4345 |
usage = '''\ |
| 4346 |
usage: PROG [-h] [-x XX] [-a] yyy |
| 4347 |
''' |
| 4348 |
help = usage + '''\ |
| 4349 |
|
| 4350 |
D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \ |
| 4351 |
DD DD DD |
| 4352 |
DD DD DD DD D |
| 4353 |
|
| 4354 |
positional arguments: |
| 4355 |
yyy YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \ |
| 4356 |
YHYH YHYH |
| 4357 |
YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH |
| 4358 |
|
| 4359 |
options: |
| 4360 |
-h, --help show this help message and exit |
| 4361 |
-x XX XHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH \ |
| 4362 |
HXXHH HXXHH |
| 4363 |
HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HX |
| 4364 |
|
| 4365 |
ALPHAS: |
| 4366 |
-a AHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH \ |
| 4367 |
HHAAHHH |
| 4368 |
HHAAHHH HHAAHHH HHA |
| 4369 |
''' |
| 4370 |
version = '' |
| 4371 |
|
| 4372 |
|
| 4373 |
class TestHelpWrappingLongNames(HelpTestCase): |
| 4374 |
"""Make sure that text after long names starts on the next line""" |
| 4375 |
|
| 4376 |
parser_signature = Sig(usage='USAGE', description= 'D D' * 30) |
| 4377 |
argument_signatures = [ |
| 4378 |
Sig('-v', '--version', action='version', version='V V' * 30), |
| 4379 |
Sig('-x', metavar='X' * 25, help='XH XH' * 20), |
| 4380 |
Sig('y', metavar='y' * 25, help='YH YH' * 20), |
| 4381 |
] |
| 4382 |
argument_group_signatures = [ |
| 4383 |
(Sig('ALPHAS'), [ |
| 4384 |
Sig('-a', metavar='A' * 25, help='AH AH' * 20), |
| 4385 |
Sig('z', metavar='z' * 25, help='ZH ZH' * 20)]), |
| 4386 |
] |
| 4387 |
usage = '''\ |
| 4388 |
usage: USAGE |
| 4389 |
''' |
| 4390 |
help = usage + '''\ |
| 4391 |
|
| 4392 |
D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \ |
| 4393 |
DD DD DD |
| 4394 |
DD DD DD DD D |
| 4395 |
|
| 4396 |
positional arguments: |
| 4397 |
yyyyyyyyyyyyyyyyyyyyyyyyy |
| 4398 |
YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \ |
| 4399 |
YHYH YHYH |
| 4400 |
YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH |
| 4401 |
|
| 4402 |
options: |
| 4403 |
-h, --help show this help message and exit |
| 4404 |
-v, --version show program's version number and exit |
| 4405 |
-x XXXXXXXXXXXXXXXXXXXXXXXXX |
| 4406 |
XH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH \ |
| 4407 |
XHXH XHXH |
| 4408 |
XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XH |
| 4409 |
|
| 4410 |
ALPHAS: |
| 4411 |
-a AAAAAAAAAAAAAAAAAAAAAAAAA |
| 4412 |
AH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH \ |
| 4413 |
AHAH AHAH |
| 4414 |
AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AH |
| 4415 |
zzzzzzzzzzzzzzzzzzzzzzzzz |
| 4416 |
ZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH \ |
| 4417 |
ZHZH ZHZH |
| 4418 |
ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZH |
| 4419 |
''' |
| 4420 |
version = '''\ |
| 4421 |
V VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV \ |
| 4422 |
VV VV VV |
| 4423 |
VV VV VV VV V |
| 4424 |
''' |
| 4425 |
|
| 4426 |
|
| 4427 |
class TestHelpUsage(HelpTestCase): |
| 4428 |
"""Test basic usage messages""" |
| 4429 |
|
| 4430 |
parser_signature = Sig(prog='PROG') |
| 4431 |
argument_signatures = [ |
| 4432 |
Sig('-w', nargs='+', help='w'), |
| 4433 |
Sig('-x', nargs='*', help='x'), |
| 4434 |
Sig('a', help='a'), |
| 4435 |
Sig('b', help='b', nargs=2), |
| 4436 |
Sig('c', help='c', nargs='?'), |
| 4437 |
Sig('--foo', help='Whether to foo', action=argparse.BooleanOptionalAction), |
| 4438 |
Sig('--bar', help='Whether to bar', default=True, |
| 4439 |
action=argparse.BooleanOptionalAction), |
| 4440 |
Sig('-f', '--foobar', '--barfoo', action=argparse.BooleanOptionalAction), |
| 4441 |
Sig('--bazz', action=argparse.BooleanOptionalAction, |
| 4442 |
default=argparse.SUPPRESS, help='Bazz!'), |
| 4443 |
] |
| 4444 |
argument_group_signatures = [ |
| 4445 |
(Sig('group'), [ |
| 4446 |
Sig('-y', nargs='?', help='y'), |
| 4447 |
Sig('-z', nargs=3, help='z'), |
| 4448 |
Sig('d', help='d', nargs='*'), |
| 4449 |
Sig('e', help='e', nargs='+'), |
| 4450 |
]) |
| 4451 |
] |
| 4452 |
usage = '''\ |
| 4453 |
usage: PROG [-h] [-w W [W ...]] [-x [X ...]] [--foo | --no-foo] |
| 4454 |
[--bar | --no-bar] |
| 4455 |
[-f | --foobar | --no-foobar | --barfoo | --no-barfoo] |
| 4456 |
[--bazz | --no-bazz] [-y [Y]] [-z Z Z Z] |
| 4457 |
a b b [c] [d ...] e [e ...] |
| 4458 |
''' |
| 4459 |
help = usage + '''\ |
| 4460 |
|
| 4461 |
positional arguments: |
| 4462 |
a a |
| 4463 |
b b |
| 4464 |
c c |
| 4465 |
|
| 4466 |
options: |
| 4467 |
-h, --help show this help message and exit |
| 4468 |
-w W [W ...] w |
| 4469 |
-x [X ...] x |
| 4470 |
--foo, --no-foo Whether to foo |
| 4471 |
--bar, --no-bar Whether to bar |
| 4472 |
-f, --foobar, --no-foobar, --barfoo, --no-barfoo |
| 4473 |
--bazz, --no-bazz Bazz! |
| 4474 |
|
| 4475 |
group: |
| 4476 |
-y [Y] y |
| 4477 |
-z Z Z Z z |
| 4478 |
d d |
| 4479 |
e e |
| 4480 |
''' |
| 4481 |
version = '' |
| 4482 |
|
| 4483 |
|
| 4484 |
class TestHelpUsageWithParentheses(HelpTestCase): |
| 4485 |
parser_signature = Sig(prog='PROG') |
| 4486 |
argument_signatures = [ |
| 4487 |
Sig('positional', metavar='(example) positional'), |
| 4488 |
Sig('-p', '--optional', metavar='{1 (option A), 2 (option B)}'), |
| 4489 |
] |
| 4490 |
|
| 4491 |
usage = '''\ |
| 4492 |
usage: PROG [-h] [-p {1 (option A), 2 (option B)}] (example) positional |
| 4493 |
''' |
| 4494 |
help = usage + '''\ |
| 4495 |
|
| 4496 |
positional arguments: |
| 4497 |
(example) positional |
| 4498 |
|
| 4499 |
options: |
| 4500 |
-h, --help show this help message and exit |
| 4501 |
-p, --optional {1 (option A), 2 (option B)} |
| 4502 |
''' |
| 4503 |
version = '' |
| 4504 |
|
| 4505 |
|
| 4506 |
class TestHelpOnlyUserGroups(HelpTestCase): |
| 4507 |
"""Test basic usage messages""" |
| 4508 |
|
| 4509 |
parser_signature = Sig(prog='PROG', add_help=False) |
| 4510 |
argument_signatures = [] |
| 4511 |
argument_group_signatures = [ |
| 4512 |
(Sig('xxxx'), [ |
| 4513 |
Sig('-x', help='x'), |
| 4514 |
Sig('a', help='a'), |
| 4515 |
]), |
| 4516 |
(Sig('yyyy'), [ |
| 4517 |
Sig('b', help='b'), |
| 4518 |
Sig('-y', help='y'), |
| 4519 |
]), |
| 4520 |
] |
| 4521 |
usage = '''\ |
| 4522 |
usage: PROG [-x X] [-y Y] a b |
| 4523 |
''' |
| 4524 |
help = usage + '''\ |
| 4525 |
|
| 4526 |
xxxx: |
| 4527 |
-x X x |
| 4528 |
a a |
| 4529 |
|
| 4530 |
yyyy: |
| 4531 |
b b |
| 4532 |
-y Y y |
| 4533 |
''' |
| 4534 |
version = '' |
| 4535 |
|
| 4536 |
|
| 4537 |
class TestHelpUsageLongProg(HelpTestCase): |
| 4538 |
"""Test usage messages where the prog is long""" |
| 4539 |
|
| 4540 |
parser_signature = Sig(prog='P' * 60) |
| 4541 |
argument_signatures = [ |
| 4542 |
Sig('-w', metavar='W'), |
| 4543 |
Sig('-x', metavar='X'), |
| 4544 |
Sig('a'), |
| 4545 |
Sig('b'), |
| 4546 |
] |
| 4547 |
argument_group_signatures = [] |
| 4548 |
usage = '''\ |
| 4549 |
usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP |
| 4550 |
[-h] [-w W] [-x X] a b |
| 4551 |
''' |
| 4552 |
help = usage + '''\ |
| 4553 |
|
| 4554 |
positional arguments: |
| 4555 |
a |
| 4556 |
b |
| 4557 |
|
| 4558 |
options: |
| 4559 |
-h, --help show this help message and exit |
| 4560 |
-w W |
| 4561 |
-x X |
| 4562 |
''' |
| 4563 |
version = '' |
| 4564 |
|
| 4565 |
|
| 4566 |
class TestHelpUsageLongProgOptionsWrap(HelpTestCase): |
| 4567 |
"""Test usage messages where the prog is long and the optionals wrap""" |
| 4568 |
|
| 4569 |
parser_signature = Sig(prog='P' * 60) |
| 4570 |
argument_signatures = [ |
| 4571 |
Sig('-w', metavar='W' * 25), |
| 4572 |
Sig('-x', metavar='X' * 25), |
| 4573 |
Sig('-y', metavar='Y' * 25), |
| 4574 |
Sig('-z', metavar='Z' * 25), |
| 4575 |
Sig('a'), |
| 4576 |
Sig('b'), |
| 4577 |
] |
| 4578 |
argument_group_signatures = [] |
| 4579 |
usage = '''\ |
| 4580 |
usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP |
| 4581 |
[-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \ |
| 4582 |
[-x XXXXXXXXXXXXXXXXXXXXXXXXX] |
| 4583 |
[-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ] |
| 4584 |
a b |
| 4585 |
''' |
| 4586 |
help = usage + '''\ |
| 4587 |
|
| 4588 |
positional arguments: |
| 4589 |
a |
| 4590 |
b |
| 4591 |
|
| 4592 |
options: |
| 4593 |
-h, --help show this help message and exit |
| 4594 |
-w WWWWWWWWWWWWWWWWWWWWWWWWW |
| 4595 |
-x XXXXXXXXXXXXXXXXXXXXXXXXX |
| 4596 |
-y YYYYYYYYYYYYYYYYYYYYYYYYY |
| 4597 |
-z ZZZZZZZZZZZZZZZZZZZZZZZZZ |
| 4598 |
''' |
| 4599 |
version = '' |
| 4600 |
|
| 4601 |
|
| 4602 |
class TestHelpUsageLongProgPositionalsWrap(HelpTestCase): |
| 4603 |
"""Test usage messages where the prog is long and the positionals wrap""" |
| 4604 |
|
| 4605 |
parser_signature = Sig(prog='P' * 60, add_help=False) |
| 4606 |
argument_signatures = [ |
| 4607 |
Sig('a' * 25), |
| 4608 |
Sig('b' * 25), |
| 4609 |
Sig('c' * 25), |
| 4610 |
] |
| 4611 |
argument_group_signatures = [] |
| 4612 |
usage = '''\ |
| 4613 |
usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP |
| 4614 |
aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb |
| 4615 |
ccccccccccccccccccccccccc |
| 4616 |
''' |
| 4617 |
help = usage + '''\ |
| 4618 |
|
| 4619 |
positional arguments: |
| 4620 |
aaaaaaaaaaaaaaaaaaaaaaaaa |
| 4621 |
bbbbbbbbbbbbbbbbbbbbbbbbb |
| 4622 |
ccccccccccccccccccccccccc |
| 4623 |
''' |
| 4624 |
version = '' |
| 4625 |
|
| 4626 |
|
| 4627 |
class TestHelpUsageOptionalsWrap(HelpTestCase): |
| 4628 |
"""Test usage messages where the optionals wrap""" |
| 4629 |
|
| 4630 |
parser_signature = Sig(prog='PROG') |
| 4631 |
argument_signatures = [ |
| 4632 |
Sig('-w', metavar='W' * 25), |
| 4633 |
Sig('-x', metavar='X' * 25), |
| 4634 |
Sig('-y', metavar='Y' * 25), |
| 4635 |
Sig('-z', metavar='Z' * 25), |
| 4636 |
Sig('a'), |
| 4637 |
Sig('b'), |
| 4638 |
Sig('c'), |
| 4639 |
] |
| 4640 |
argument_group_signatures = [] |
| 4641 |
usage = '''\ |
| 4642 |
usage: PROG [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \ |
| 4643 |
[-x XXXXXXXXXXXXXXXXXXXXXXXXX] |
| 4644 |
[-y YYYYYYYYYYYYYYYYYYYYYYYYY] \ |
| 4645 |
[-z ZZZZZZZZZZZZZZZZZZZZZZZZZ] |
| 4646 |
a b c |
| 4647 |
''' |
| 4648 |
help = usage + '''\ |
| 4649 |
|
| 4650 |
positional arguments: |
| 4651 |
a |
| 4652 |
b |
| 4653 |
c |
| 4654 |
|
| 4655 |
options: |
| 4656 |
-h, --help show this help message and exit |
| 4657 |
-w WWWWWWWWWWWWWWWWWWWWWWWWW |
| 4658 |
-x XXXXXXXXXXXXXXXXXXXXXXXXX |
| 4659 |
-y YYYYYYYYYYYYYYYYYYYYYYYYY |
| 4660 |
-z ZZZZZZZZZZZZZZZZZZZZZZZZZ |
| 4661 |
''' |
| 4662 |
version = '' |
| 4663 |
|
| 4664 |
|
| 4665 |
class TestHelpUsagePositionalsWrap(HelpTestCase): |
| 4666 |
"""Test usage messages where the positionals wrap""" |
| 4667 |
|
| 4668 |
parser_signature = Sig(prog='PROG') |
| 4669 |
argument_signatures = [ |
| 4670 |
Sig('-x'), |
| 4671 |
Sig('-y'), |
| 4672 |
Sig('-z'), |
| 4673 |
Sig('a' * 25), |
| 4674 |
Sig('b' * 25), |
| 4675 |
Sig('c' * 25), |
| 4676 |
] |
| 4677 |
argument_group_signatures = [] |
| 4678 |
usage = '''\ |
| 4679 |
usage: PROG [-h] [-x X] [-y Y] [-z Z] |
| 4680 |
aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb |
| 4681 |
ccccccccccccccccccccccccc |
| 4682 |
''' |
| 4683 |
help = usage + '''\ |
| 4684 |
|
| 4685 |
positional arguments: |
| 4686 |
aaaaaaaaaaaaaaaaaaaaaaaaa |
| 4687 |
bbbbbbbbbbbbbbbbbbbbbbbbb |
| 4688 |
ccccccccccccccccccccccccc |
| 4689 |
|
| 4690 |
options: |
| 4691 |
-h, --help show this help message and exit |
| 4692 |
-x X |
| 4693 |
-y Y |
| 4694 |
-z Z |
| 4695 |
''' |
| 4696 |
version = '' |
| 4697 |
|
| 4698 |
|
| 4699 |
class TestHelpUsageOptionalsPositionalsWrap(HelpTestCase): |
| 4700 |
"""Test usage messages where the optionals and positionals wrap""" |
| 4701 |
|
| 4702 |
parser_signature = Sig(prog='PROG') |
| 4703 |
argument_signatures = [ |
| 4704 |
Sig('-x', metavar='X' * 25), |
| 4705 |
Sig('-y', metavar='Y' * 25), |
| 4706 |
Sig('-z', metavar='Z' * 25), |
| 4707 |
Sig('a' * 25), |
| 4708 |
Sig('b' * 25), |
| 4709 |
Sig('c' * 25), |
| 4710 |
] |
| 4711 |
argument_group_signatures = [] |
| 4712 |
usage = '''\ |
| 4713 |
usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \ |
| 4714 |
[-y YYYYYYYYYYYYYYYYYYYYYYYYY] |
| 4715 |
[-z ZZZZZZZZZZZZZZZZZZZZZZZZZ] |
| 4716 |
aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb |
| 4717 |
ccccccccccccccccccccccccc |
| 4718 |
''' |
| 4719 |
help = usage + '''\ |
| 4720 |
|
| 4721 |
positional arguments: |
| 4722 |
aaaaaaaaaaaaaaaaaaaaaaaaa |
| 4723 |
bbbbbbbbbbbbbbbbbbbbbbbbb |
| 4724 |
ccccccccccccccccccccccccc |
| 4725 |
|
| 4726 |
options: |
| 4727 |
-h, --help show this help message and exit |
| 4728 |
-x XXXXXXXXXXXXXXXXXXXXXXXXX |
| 4729 |
-y YYYYYYYYYYYYYYYYYYYYYYYYY |
| 4730 |
-z ZZZZZZZZZZZZZZZZZZZZZZZZZ |
| 4731 |
''' |
| 4732 |
version = '' |
| 4733 |
|
| 4734 |
|
| 4735 |
class TestHelpUsageOptionalsOnlyWrap(HelpTestCase): |
| 4736 |
"""Test usage messages where there are only optionals and they wrap""" |
| 4737 |
|
| 4738 |
parser_signature = Sig(prog='PROG') |
| 4739 |
argument_signatures = [ |
| 4740 |
Sig('-x', metavar='X' * 25), |
| 4741 |
Sig('-y', metavar='Y' * 25), |
| 4742 |
Sig('-z', metavar='Z' * 25), |
| 4743 |
] |
| 4744 |
argument_group_signatures = [] |
| 4745 |
usage = '''\ |
| 4746 |
usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \ |
| 4747 |
[-y YYYYYYYYYYYYYYYYYYYYYYYYY] |
| 4748 |
[-z ZZZZZZZZZZZZZZZZZZZZZZZZZ] |
| 4749 |
''' |
| 4750 |
help = usage + '''\ |
| 4751 |
|
| 4752 |
options: |
| 4753 |
-h, --help show this help message and exit |
| 4754 |
-x XXXXXXXXXXXXXXXXXXXXXXXXX |
| 4755 |
-y YYYYYYYYYYYYYYYYYYYYYYYYY |
| 4756 |
-z ZZZZZZZZZZZZZZZZZZZZZZZZZ |
| 4757 |
''' |
| 4758 |
version = '' |
| 4759 |
|
| 4760 |
|
| 4761 |
class TestHelpUsagePositionalsOnlyWrap(HelpTestCase): |
| 4762 |
"""Test usage messages where there are only positionals and they wrap""" |
| 4763 |
|
| 4764 |
parser_signature = Sig(prog='PROG', add_help=False) |
| 4765 |
argument_signatures = [ |
| 4766 |
Sig('a' * 25), |
| 4767 |
Sig('b' * 25), |
| 4768 |
Sig('c' * 25), |
| 4769 |
] |
| 4770 |
argument_group_signatures = [] |
| 4771 |
usage = '''\ |
| 4772 |
usage: PROG aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb |
| 4773 |
ccccccccccccccccccccccccc |
| 4774 |
''' |
| 4775 |
help = usage + '''\ |
| 4776 |
|
| 4777 |
positional arguments: |
| 4778 |
aaaaaaaaaaaaaaaaaaaaaaaaa |
| 4779 |
bbbbbbbbbbbbbbbbbbbbbbbbb |
| 4780 |
ccccccccccccccccccccccccc |
| 4781 |
''' |
| 4782 |
version = '' |
| 4783 |
|
| 4784 |
|
| 4785 |
class TestHelpUsageMetavarsSpacesParentheses(HelpTestCase): |
| 4786 |
# https://github.com/python/cpython/issues/62549 |
| 4787 |
# https://github.com/python/cpython/issues/89743 |
| 4788 |
parser_signature = Sig(prog='PROG') |
| 4789 |
argument_signatures = [ |
| 4790 |
Sig('-n1', metavar='()', help='n1'), |
| 4791 |
Sig('-o1', metavar='(1, 2)', help='o1'), |
| 4792 |
Sig('-u1', metavar=' (uu) ', help='u1'), |
| 4793 |
Sig('-v1', metavar='( vv )', help='v1'), |
| 4794 |
Sig('-w1', metavar='(w)w', help='w1'), |
| 4795 |
Sig('-x1', metavar='x(x)', help='x1'), |
| 4796 |
Sig('-y1', metavar='yy)', help='y1'), |
| 4797 |
Sig('-z1', metavar='(zz', help='z1'), |
| 4798 |
Sig('-n2', metavar='[]', help='n2'), |
| 4799 |
Sig('-o2', metavar='[1, 2]', help='o2'), |
| 4800 |
Sig('-u2', metavar=' [uu] ', help='u2'), |
| 4801 |
Sig('-v2', metavar='[ vv ]', help='v2'), |
| 4802 |
Sig('-w2', metavar='[w]w', help='w2'), |
| 4803 |
Sig('-x2', metavar='x[x]', help='x2'), |
| 4804 |
Sig('-y2', metavar='yy]', help='y2'), |
| 4805 |
Sig('-z2', metavar='[zz', help='z2'), |
| 4806 |
] |
| 4807 |
|
| 4808 |
usage = '''\ |
| 4809 |
usage: PROG [-h] [-n1 ()] [-o1 (1, 2)] [-u1 (uu) ] [-v1 ( vv )] [-w1 (w)w] |
| 4810 |
[-x1 x(x)] [-y1 yy)] [-z1 (zz] [-n2 []] [-o2 [1, 2]] [-u2 [uu] ] |
| 4811 |
[-v2 [ vv ]] [-w2 [w]w] [-x2 x[x]] [-y2 yy]] [-z2 [zz] |
| 4812 |
''' |
| 4813 |
help = usage + '''\ |
| 4814 |
|
| 4815 |
options: |
| 4816 |
-h, --help show this help message and exit |
| 4817 |
-n1 () n1 |
| 4818 |
-o1 (1, 2) o1 |
| 4819 |
-u1 (uu) u1 |
| 4820 |
-v1 ( vv ) v1 |
| 4821 |
-w1 (w)w w1 |
| 4822 |
-x1 x(x) x1 |
| 4823 |
-y1 yy) y1 |
| 4824 |
-z1 (zz z1 |
| 4825 |
-n2 [] n2 |
| 4826 |
-o2 [1, 2] o2 |
| 4827 |
-u2 [uu] u2 |
| 4828 |
-v2 [ vv ] v2 |
| 4829 |
-w2 [w]w w2 |
| 4830 |
-x2 x[x] x2 |
| 4831 |
-y2 yy] y2 |
| 4832 |
-z2 [zz z2 |
| 4833 |
''' |
| 4834 |
version = '' |
| 4835 |
|
| 4836 |
|
| 4837 |
@force_not_colorized_test_class |
| 4838 |
class TestHelpUsageNoWhitespaceCrash(TestCase): |
| 4839 |
|
| 4840 |
def test_all_suppressed_mutex_followed_by_long_arg(self): |
| 4841 |
# https://github.com/python/cpython/issues/62090 |
| 4842 |
# https://github.com/python/cpython/issues/96310 |
| 4843 |
parser = argparse.ArgumentParser(prog='PROG') |
| 4844 |
mutex = parser.add_mutually_exclusive_group() |
| 4845 |
mutex.add_argument('--spam', help=argparse.SUPPRESS) |
| 4846 |
parser.add_argument('--eggs-eggs-eggs-eggs-eggs-eggs') |
| 4847 |
usage = textwrap.dedent('''\ |
| 4848 |
usage: PROG [-h] |
| 4849 |
[--eggs-eggs-eggs-eggs-eggs-eggs EGGS_EGGS_EGGS_EGGS_EGGS_EGGS] |
| 4850 |
''') |
| 4851 |
self.assertEqual(parser.format_usage(), usage) |
| 4852 |
|
| 4853 |
def test_newline_in_metavar(self): |
| 4854 |
# https://github.com/python/cpython/issues/77048 |
| 4855 |
mapping = ['123456', '12345', '12345', '123'] |
| 4856 |
parser = argparse.ArgumentParser('11111111111111') |
| 4857 |
parser.add_argument('-v', '--verbose', |
| 4858 |
help='verbose mode', action='store_true') |
| 4859 |
parser.add_argument('targets', |
| 4860 |
help='installation targets', |
| 4861 |
nargs='+', |
| 4862 |
metavar='\n'.join(mapping)) |
| 4863 |
usage = textwrap.dedent('''\ |
| 4864 |
usage: 11111111111111 [-h] [-v] |
| 4865 |
123456 |
| 4866 |
12345 |
| 4867 |
12345 |
| 4868 |
123 [123456 |
| 4869 |
12345 |
| 4870 |
12345 |
| 4871 |
123 ...] |
| 4872 |
''') |
| 4873 |
self.assertEqual(parser.format_usage(), usage) |
| 4874 |
|
| 4875 |
def test_empty_metavar_required_arg(self): |
| 4876 |
# https://github.com/python/cpython/issues/82091 |
| 4877 |
parser = argparse.ArgumentParser(prog='PROG') |
| 4878 |
parser.add_argument('--nil', metavar='', required=True) |
| 4879 |
parser.add_argument('--a', metavar='A' * 70) |
| 4880 |
usage = ( |
| 4881 |
'usage: PROG [-h] --nil \n' |
| 4882 |
' [--a AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' |
| 4883 |
'AAAAAAAAAAAAAAAAAAAAAAA]\n' |
| 4884 |
) |
| 4885 |
self.assertEqual(parser.format_usage(), usage) |
| 4886 |
|
| 4887 |
def test_all_suppressed_mutex_with_optional_nargs(self): |
| 4888 |
# https://github.com/python/cpython/issues/98666 |
| 4889 |
parser = argparse.ArgumentParser(prog='PROG') |
| 4890 |
mutex = parser.add_mutually_exclusive_group() |
| 4891 |
mutex.add_argument( |
| 4892 |
'--param1', |
| 4893 |
nargs='?', const='default', metavar='NAME', help=argparse.SUPPRESS) |
| 4894 |
mutex.add_argument( |
| 4895 |
'--param2', |
| 4896 |
nargs='?', const='default', metavar='NAME', help=argparse.SUPPRESS) |
| 4897 |
usage = 'usage: PROG [-h]\n' |
| 4898 |
self.assertEqual(parser.format_usage(), usage) |
| 4899 |
|
| 4900 |
def test_long_mutex_groups_wrap(self): |
| 4901 |
parser = argparse.ArgumentParser(prog='PROG') |
| 4902 |
g = parser.add_mutually_exclusive_group() |
| 4903 |
g.add_argument('--op1', metavar='MET', nargs='?') |
| 4904 |
g.add_argument('--op2', metavar=('MET1', 'MET2'), nargs='*') |
| 4905 |
g.add_argument('--op3', nargs='*') |
| 4906 |
g.add_argument('--op4', metavar=('MET1', 'MET2'), nargs='+') |
| 4907 |
g.add_argument('--op5', nargs='+') |
| 4908 |
g.add_argument('--op6', nargs=3) |
| 4909 |
g.add_argument('--op7', metavar=('MET1', 'MET2', 'MET3'), nargs=3) |
| 4910 |
|
| 4911 |
usage = textwrap.dedent('''\ |
| 4912 |
usage: PROG [-h] [--op1 [MET] | --op2 [MET1 [MET2 ...]] | --op3 [OP3 ...] | |
| 4913 |
--op4 MET1 [MET2 ...] | --op5 OP5 [OP5 ...] | --op6 OP6 OP6 OP6 | |
| 4914 |
--op7 MET1 MET2 MET3] |
| 4915 |
''') |
| 4916 |
self.assertEqual(parser.format_usage(), usage) |
| 4917 |
|
| 4918 |
def test_mutex_groups_with_mixed_optionals_positionals_wrap(self): |
| 4919 |
# https://github.com/python/cpython/issues/75949 |
| 4920 |
# Mutually exclusive groups containing both optionals and positionals |
| 4921 |
# should preserve pipe separators when the usage line wraps. |
| 4922 |
parser = argparse.ArgumentParser(prog='PROG') |
| 4923 |
g = parser.add_mutually_exclusive_group() |
| 4924 |
g.add_argument('-v', '--verbose', action='store_true') |
| 4925 |
g.add_argument('-q', '--quiet', action='store_true') |
| 4926 |
g.add_argument('-x', '--extra-long-option-name', nargs='?') |
| 4927 |
g.add_argument('-y', '--yet-another-long-option', nargs='?') |
| 4928 |
g.add_argument('positional', nargs='?') |
| 4929 |
|
| 4930 |
usage = textwrap.dedent('''\ |
| 4931 |
usage: PROG [-h] |
| 4932 |
[-v | -q | -x [EXTRA_LONG_OPTION_NAME] | |
| 4933 |
-y [YET_ANOTHER_LONG_OPTION] | positional] |
| 4934 |
''') |
| 4935 |
self.assertEqual(parser.format_usage(), usage) |
| 4936 |
|
| 4937 |
|
| 4938 |
class TestHelpVariableExpansion(HelpTestCase): |
| 4939 |
"""Test that variables are expanded properly in help messages""" |
| 4940 |
|
| 4941 |
parser_signature = Sig(prog='PROG') |
| 4942 |
argument_signatures = [ |
| 4943 |
Sig('-x', type=int, |
| 4944 |
help='x %(prog)s %(default)s %(type)s %%'), |
| 4945 |
Sig('-y', action='store_const', default=42, const='XXX', |
| 4946 |
help='y %(prog)s %(default)s %(const)s'), |
| 4947 |
Sig('--foo', choices=['a', 'b', 'c'], |
| 4948 |
help='foo %(prog)s %(default)s %(choices)s'), |
| 4949 |
Sig('--bar', default='baz', choices=[1, 2], metavar='BBB', |
| 4950 |
help='bar %(prog)s %(default)s %(dest)s'), |
| 4951 |
Sig('spam', help='spam %(prog)s %(default)s'), |
| 4952 |
Sig('badger', default=0.5, help='badger %(prog)s %(default)s'), |
| 4953 |
] |
| 4954 |
argument_group_signatures = [ |
| 4955 |
(Sig('group'), [ |
| 4956 |
Sig('-a', help='a %(prog)s %(default)s'), |
| 4957 |
Sig('-b', default=-1, help='b %(prog)s %(default)s'), |
| 4958 |
]) |
| 4959 |
] |
| 4960 |
usage = ('''\ |
| 4961 |
usage: PROG [-h] [-x X] [-y] [--foo {a,b,c}] [--bar BBB] [-a A] [-b B] |
| 4962 |
spam badger |
| 4963 |
''') |
| 4964 |
help = usage + '''\ |
| 4965 |
|
| 4966 |
positional arguments: |
| 4967 |
spam spam PROG None |
| 4968 |
badger badger PROG 0.5 |
| 4969 |
|
| 4970 |
options: |
| 4971 |
-h, --help show this help message and exit |
| 4972 |
-x X x PROG None int % |
| 4973 |
-y y PROG 42 XXX |
| 4974 |
--foo {a,b,c} foo PROG None a, b, c |
| 4975 |
--bar BBB bar PROG baz bar |
| 4976 |
|
| 4977 |
group: |
| 4978 |
-a A a PROG None |
| 4979 |
-b B b PROG -1 |
| 4980 |
''' |
| 4981 |
version = '' |
| 4982 |
|
| 4983 |
|
| 4984 |
class TestHelpVariableExpansionUsageSupplied(HelpTestCase): |
| 4985 |
"""Test that variables are expanded properly when usage= is present""" |
| 4986 |
|
| 4987 |
parser_signature = Sig(prog='PROG', usage='%(prog)s FOO') |
| 4988 |
argument_signatures = [] |
| 4989 |
argument_group_signatures = [] |
| 4990 |
usage = ('''\ |
| 4991 |
usage: PROG FOO |
| 4992 |
''') |
| 4993 |
help = usage + '''\ |
| 4994 |
|
| 4995 |
options: |
| 4996 |
-h, --help show this help message and exit |
| 4997 |
''' |
| 4998 |
version = '' |
| 4999 |
|
| 5000 |
|
| 5001 |
class TestHelpVariableExpansionNoArguments(HelpTestCase): |
| 5002 |
"""Test that variables are expanded properly with no arguments""" |
| 5003 |
|
| 5004 |
parser_signature = Sig(prog='PROG', add_help=False) |
| 5005 |
argument_signatures = [] |
| 5006 |
argument_group_signatures = [] |
| 5007 |
usage = ('''\ |
| 5008 |
usage: PROG |
| 5009 |
''') |
| 5010 |
help = usage |
| 5011 |
version = '' |
| 5012 |
|
| 5013 |
|
| 5014 |
class TestHelpSuppressUsage(HelpTestCase): |
| 5015 |
"""Test that items can be suppressed in usage messages""" |
| 5016 |
|
| 5017 |
parser_signature = Sig(prog='PROG', usage=argparse.SUPPRESS) |
| 5018 |
argument_signatures = [ |
| 5019 |
Sig('--foo', help='foo help'), |
| 5020 |
Sig('spam', help='spam help'), |
| 5021 |
] |
| 5022 |
argument_group_signatures = [] |
| 5023 |
help = '''\ |
| 5024 |
positional arguments: |
| 5025 |
spam spam help |
| 5026 |
|
| 5027 |
options: |
| 5028 |
-h, --help show this help message and exit |
| 5029 |
--foo FOO foo help |
| 5030 |
''' |
| 5031 |
usage = '' |
| 5032 |
version = '' |
| 5033 |
|
| 5034 |
|
| 5035 |
class TestHelpSuppressOptional(HelpTestCase): |
| 5036 |
"""Test that optional arguments can be suppressed in help messages""" |
| 5037 |
|
| 5038 |
parser_signature = Sig(prog='PROG', add_help=False) |
| 5039 |
argument_signatures = [ |
| 5040 |
Sig('--foo', help=argparse.SUPPRESS), |
| 5041 |
Sig('spam', help='spam help'), |
| 5042 |
] |
| 5043 |
argument_group_signatures = [] |
| 5044 |
usage = '''\ |
| 5045 |
usage: PROG spam |
| 5046 |
''' |
| 5047 |
help = usage + '''\ |
| 5048 |
|
| 5049 |
positional arguments: |
| 5050 |
spam spam help |
| 5051 |
''' |
| 5052 |
version = '' |
| 5053 |
|
| 5054 |
|
| 5055 |
class TestHelpSuppressOptionalGroup(HelpTestCase): |
| 5056 |
"""Test that optional groups can be suppressed in help messages""" |
| 5057 |
|
| 5058 |
parser_signature = Sig(prog='PROG') |
| 5059 |
argument_signatures = [ |
| 5060 |
Sig('--foo', help='foo help'), |
| 5061 |
Sig('spam', help='spam help'), |
| 5062 |
] |
| 5063 |
argument_group_signatures = [ |
| 5064 |
(Sig('group'), [Sig('--bar', help=argparse.SUPPRESS)]), |
| 5065 |
] |
| 5066 |
usage = '''\ |
| 5067 |
usage: PROG [-h] [--foo FOO] spam |
| 5068 |
''' |
| 5069 |
help = usage + '''\ |
| 5070 |
|
| 5071 |
positional arguments: |
| 5072 |
spam spam help |
| 5073 |
|
| 5074 |
options: |
| 5075 |
-h, --help show this help message and exit |
| 5076 |
--foo FOO foo help |
| 5077 |
''' |
| 5078 |
version = '' |
| 5079 |
|
| 5080 |
|
| 5081 |
class TestHelpSuppressPositional(HelpTestCase): |
| 5082 |
"""Test that positional arguments can be suppressed in help messages""" |
| 5083 |
|
| 5084 |
parser_signature = Sig(prog='PROG') |
| 5085 |
argument_signatures = [ |
| 5086 |
Sig('--foo', help='foo help'), |
| 5087 |
Sig('spam', help=argparse.SUPPRESS), |
| 5088 |
] |
| 5089 |
argument_group_signatures = [] |
| 5090 |
usage = '''\ |
| 5091 |
usage: PROG [-h] [--foo FOO] |
| 5092 |
''' |
| 5093 |
help = usage + '''\ |
| 5094 |
|
| 5095 |
options: |
| 5096 |
-h, --help show this help message and exit |
| 5097 |
--foo FOO foo help |
| 5098 |
''' |
| 5099 |
version = '' |
| 5100 |
|
| 5101 |
|
| 5102 |
class TestHelpRequiredOptional(HelpTestCase): |
| 5103 |
"""Test that required options don't look optional""" |
| 5104 |
|
| 5105 |
parser_signature = Sig(prog='PROG') |
| 5106 |
argument_signatures = [ |
| 5107 |
Sig('--foo', required=True, help='foo help'), |
| 5108 |
] |
| 5109 |
argument_group_signatures = [] |
| 5110 |
usage = '''\ |
| 5111 |
usage: PROG [-h] --foo FOO |
| 5112 |
''' |
| 5113 |
help = usage + '''\ |
| 5114 |
|
| 5115 |
options: |
| 5116 |
-h, --help show this help message and exit |
| 5117 |
--foo FOO foo help |
| 5118 |
''' |
| 5119 |
version = '' |
| 5120 |
|
| 5121 |
|
| 5122 |
class TestHelpAlternatePrefixChars(HelpTestCase): |
| 5123 |
"""Test that options display with different prefix characters""" |
| 5124 |
|
| 5125 |
parser_signature = Sig(prog='PROG', prefix_chars='^;', add_help=False) |
| 5126 |
argument_signatures = [ |
| 5127 |
Sig('^^foo', action='store_true', help='foo help'), |
| 5128 |
Sig(';b', ';;bar', help='bar help'), |
| 5129 |
] |
| 5130 |
argument_group_signatures = [] |
| 5131 |
usage = '''\ |
| 5132 |
usage: PROG [^^foo] [;b BAR] |
| 5133 |
''' |
| 5134 |
help = usage + '''\ |
| 5135 |
|
| 5136 |
options: |
| 5137 |
^^foo foo help |
| 5138 |
;b, ;;bar BAR bar help |
| 5139 |
''' |
| 5140 |
version = '' |
| 5141 |
|
| 5142 |
|
| 5143 |
class TestHelpNoHelpOptional(HelpTestCase): |
| 5144 |
"""Test that the --help argument can be suppressed help messages""" |
| 5145 |
|
| 5146 |
parser_signature = Sig(prog='PROG', add_help=False) |
| 5147 |
argument_signatures = [ |
| 5148 |
Sig('--foo', help='foo help'), |
| 5149 |
Sig('spam', help='spam help'), |
| 5150 |
] |
| 5151 |
argument_group_signatures = [] |
| 5152 |
usage = '''\ |
| 5153 |
usage: PROG [--foo FOO] spam |
| 5154 |
''' |
| 5155 |
help = usage + '''\ |
| 5156 |
|
| 5157 |
positional arguments: |
| 5158 |
spam spam help |
| 5159 |
|
| 5160 |
options: |
| 5161 |
--foo FOO foo help |
| 5162 |
''' |
| 5163 |
version = '' |
| 5164 |
|
| 5165 |
|
| 5166 |
class TestHelpNone(HelpTestCase): |
| 5167 |
"""Test that no errors occur if no help is specified""" |
| 5168 |
|
| 5169 |
parser_signature = Sig(prog='PROG') |
| 5170 |
argument_signatures = [ |
| 5171 |
Sig('--foo'), |
| 5172 |
Sig('spam'), |
| 5173 |
] |
| 5174 |
argument_group_signatures = [] |
| 5175 |
usage = '''\ |
| 5176 |
usage: PROG [-h] [--foo FOO] spam |
| 5177 |
''' |
| 5178 |
help = usage + '''\ |
| 5179 |
|
| 5180 |
positional arguments: |
| 5181 |
spam |
| 5182 |
|
| 5183 |
options: |
| 5184 |
-h, --help show this help message and exit |
| 5185 |
--foo FOO |
| 5186 |
''' |
| 5187 |
version = '' |
| 5188 |
|
| 5189 |
|
| 5190 |
class TestHelpTupleMetavarOptional(HelpTestCase): |
| 5191 |
"""Test specifying metavar as a tuple""" |
| 5192 |
|
| 5193 |
parser_signature = Sig(prog='PROG') |
| 5194 |
argument_signatures = [ |
| 5195 |
Sig('-w', help='w', nargs='+', metavar=('W1', 'W2')), |
| 5196 |
Sig('-x', help='x', nargs='*', metavar=('X1', 'X2')), |
| 5197 |
Sig('-y', help='y', nargs=3, metavar=('Y1', 'Y2', 'Y3')), |
| 5198 |
Sig('-z', help='z', nargs='?', metavar=('Z1', )), |
| 5199 |
] |
| 5200 |
argument_group_signatures = [] |
| 5201 |
usage = '''\ |
| 5202 |
usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] \ |
| 5203 |
[-z [Z1]] |
| 5204 |
''' |
| 5205 |
help = usage + '''\ |
| 5206 |
|
| 5207 |
options: |
| 5208 |
-h, --help show this help message and exit |
| 5209 |
-w W1 [W2 ...] w |
| 5210 |
-x [X1 [X2 ...]] x |
| 5211 |
-y Y1 Y2 Y3 y |
| 5212 |
-z [Z1] z |
| 5213 |
''' |
| 5214 |
version = '' |
| 5215 |
|
| 5216 |
|
| 5217 |
class TestHelpTupleMetavarPositional(HelpTestCase): |
| 5218 |
"""Test specifying metavar on a Positional as a tuple""" |
| 5219 |
|
| 5220 |
parser_signature = Sig(prog='PROG') |
| 5221 |
argument_signatures = [ |
| 5222 |
Sig('w', help='w help', nargs='+', metavar=('W1', 'W2')), |
| 5223 |
Sig('x', help='x help', nargs='*', metavar=('X1', 'X2')), |
| 5224 |
Sig('y', help='y help', nargs=3, metavar=('Y1', 'Y2', 'Y3')), |
| 5225 |
Sig('z', help='z help', nargs='?', metavar=('Z1',)), |
| 5226 |
] |
| 5227 |
argument_group_signatures = [] |
| 5228 |
usage = '''\ |
| 5229 |
usage: PROG [-h] W1 [W2 ...] [X1 [X2 ...]] Y1 Y2 Y3 [Z1] |
| 5230 |
''' |
| 5231 |
help = usage + '''\ |
| 5232 |
|
| 5233 |
positional arguments: |
| 5234 |
W1 W2 w help |
| 5235 |
X1 X2 x help |
| 5236 |
Y1 Y2 Y3 y help |
| 5237 |
Z1 z help |
| 5238 |
|
| 5239 |
options: |
| 5240 |
-h, --help show this help message and exit |
| 5241 |
''' |
| 5242 |
version = '' |
| 5243 |
|
| 5244 |
|
| 5245 |
class TestHelpRawText(HelpTestCase): |
| 5246 |
"""Test the RawTextHelpFormatter""" |
| 5247 |
|
| 5248 |
parser_signature = Sig( |
| 5249 |
prog='PROG', formatter_class=argparse.RawTextHelpFormatter, |
| 5250 |
description='Keep the formatting\n' |
| 5251 |
' exactly as it is written\n' |
| 5252 |
'\n' |
| 5253 |
'here\n') |
| 5254 |
|
| 5255 |
argument_signatures = [ |
| 5256 |
Sig('--foo', help=' foo help should also\n' |
| 5257 |
'appear as given here'), |
| 5258 |
Sig('spam', help='spam help'), |
| 5259 |
] |
| 5260 |
argument_group_signatures = [ |
| 5261 |
(Sig('title', description=' This text\n' |
| 5262 |
' should be indented\n' |
| 5263 |
' exactly like it is here\n'), |
| 5264 |
[Sig('--bar', help='bar help')]), |
| 5265 |
] |
| 5266 |
usage = '''\ |
| 5267 |
usage: PROG [-h] [--foo FOO] [--bar BAR] spam |
| 5268 |
''' |
| 5269 |
help = usage + '''\ |
| 5270 |
|
| 5271 |
Keep the formatting |
| 5272 |
exactly as it is written |
| 5273 |
|
| 5274 |
here |
| 5275 |
|
| 5276 |
positional arguments: |
| 5277 |
spam spam help |
| 5278 |
|
| 5279 |
options: |
| 5280 |
-h, --help show this help message and exit |
| 5281 |
--foo FOO foo help should also |
| 5282 |
appear as given here |
| 5283 |
|
| 5284 |
title: |
| 5285 |
This text |
| 5286 |
should be indented |
| 5287 |
exactly like it is here |
| 5288 |
|
| 5289 |
--bar BAR bar help |
| 5290 |
''' |
| 5291 |
version = '' |
| 5292 |
|
| 5293 |
|
| 5294 |
class TestHelpRawDescription(HelpTestCase): |
| 5295 |
"""Test the RawTextHelpFormatter""" |
| 5296 |
|
| 5297 |
parser_signature = Sig( |
| 5298 |
prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter, |
| 5299 |
description='Keep the formatting\n' |
| 5300 |
' exactly as it is written\n' |
| 5301 |
'\n' |
| 5302 |
'here\n') |
| 5303 |
|
| 5304 |
argument_signatures = [ |
| 5305 |
Sig('--foo', help=' foo help should not\n' |
| 5306 |
' retain this odd formatting'), |
| 5307 |
Sig('spam', help='spam help'), |
| 5308 |
] |
| 5309 |
argument_group_signatures = [ |
| 5310 |
(Sig('title', description=' This text\n' |
| 5311 |
' should be indented\n' |
| 5312 |
' exactly like it is here\n'), |
| 5313 |
[Sig('--bar', help='bar help')]), |
| 5314 |
] |
| 5315 |
usage = '''\ |
| 5316 |
usage: PROG [-h] [--foo FOO] [--bar BAR] spam |
| 5317 |
''' |
| 5318 |
help = usage + '''\ |
| 5319 |
|
| 5320 |
Keep the formatting |
| 5321 |
exactly as it is written |
| 5322 |
|
| 5323 |
here |
| 5324 |
|
| 5325 |
positional arguments: |
| 5326 |
spam spam help |
| 5327 |
|
| 5328 |
options: |
| 5329 |
-h, --help show this help message and exit |
| 5330 |
--foo FOO foo help should not retain this odd formatting |
| 5331 |
|
| 5332 |
title: |
| 5333 |
This text |
| 5334 |
should be indented |
| 5335 |
exactly like it is here |
| 5336 |
|
| 5337 |
--bar BAR bar help |
| 5338 |
''' |
| 5339 |
version = '' |
| 5340 |
|
| 5341 |
|
| 5342 |
class TestHelpArgumentDefaults(HelpTestCase): |
| 5343 |
"""Test the ArgumentDefaultsHelpFormatter""" |
| 5344 |
|
| 5345 |
parser_signature = Sig( |
| 5346 |
prog='PROG', formatter_class=argparse.ArgumentDefaultsHelpFormatter, |
| 5347 |
description='description') |
| 5348 |
|
| 5349 |
argument_signatures = [ |
| 5350 |
Sig('--foo', help='foo help - oh and by the way, %(default)s'), |
| 5351 |
Sig('--bar', action='store_true', help='bar help'), |
| 5352 |
Sig('--required', required=True, help='some help'), |
| 5353 |
Sig('--taz', action=argparse.BooleanOptionalAction, |
| 5354 |
help='Whether to taz it', default=True), |
| 5355 |
Sig('--corge', action=argparse.BooleanOptionalAction, |
| 5356 |
help='Whether to corge it', default=argparse.SUPPRESS), |
| 5357 |
Sig('--quux', help="Set the quux", default=42), |
| 5358 |
Sig('spam', help='spam help'), |
| 5359 |
Sig('badger', nargs='?', default='wooden', help='badger help'), |
| 5360 |
] |
| 5361 |
argument_group_signatures = [ |
| 5362 |
(Sig('title', description='description'), |
| 5363 |
[Sig('--baz', type=int, default=42, help='baz help')]), |
| 5364 |
] |
| 5365 |
usage = '''\ |
| 5366 |
usage: PROG [-h] [--foo FOO] [--bar] --required REQUIRED [--taz | --no-taz] |
| 5367 |
[--corge | --no-corge] [--quux QUUX] [--baz BAZ] |
| 5368 |
spam [badger] |
| 5369 |
''' |
| 5370 |
help = usage + '''\ |
| 5371 |
|
| 5372 |
description |
| 5373 |
|
| 5374 |
positional arguments: |
| 5375 |
spam spam help |
| 5376 |
badger badger help (default: wooden) |
| 5377 |
|
| 5378 |
options: |
| 5379 |
-h, --help show this help message and exit |
| 5380 |
--foo FOO foo help - oh and by the way, None |
| 5381 |
--bar bar help (default: False) |
| 5382 |
--required REQUIRED some help |
| 5383 |
--taz, --no-taz Whether to taz it (default: True) |
| 5384 |
--corge, --no-corge Whether to corge it |
| 5385 |
--quux QUUX Set the quux (default: 42) |
| 5386 |
|
| 5387 |
title: |
| 5388 |
description |
| 5389 |
|
| 5390 |
--baz BAZ baz help (default: 42) |
| 5391 |
''' |
| 5392 |
version = '' |
| 5393 |
|
| 5394 |
class TestHelpVersionAction(HelpTestCase): |
| 5395 |
"""Test the default help for the version action""" |
| 5396 |
|
| 5397 |
parser_signature = Sig(prog='PROG', description='description') |
| 5398 |
argument_signatures = [Sig('-V', '--version', action='version', version='3.6')] |
| 5399 |
argument_group_signatures = [] |
| 5400 |
usage = '''\ |
| 5401 |
usage: PROG [-h] [-V] |
| 5402 |
''' |
| 5403 |
help = usage + '''\ |
| 5404 |
|
| 5405 |
description |
| 5406 |
|
| 5407 |
options: |
| 5408 |
-h, --help show this help message and exit |
| 5409 |
-V, --version show program's version number and exit |
| 5410 |
''' |
| 5411 |
version = '' |
| 5412 |
|
| 5413 |
|
| 5414 |
class TestHelpVersionActionSuppress(HelpTestCase): |
| 5415 |
"""Test that the --version argument can be suppressed in help messages""" |
| 5416 |
|
| 5417 |
parser_signature = Sig(prog='PROG') |
| 5418 |
argument_signatures = [ |
| 5419 |
Sig('-v', '--version', action='version', version='1.0', |
| 5420 |
help=argparse.SUPPRESS), |
| 5421 |
Sig('--foo', help='foo help'), |
| 5422 |
Sig('spam', help='spam help'), |
| 5423 |
] |
| 5424 |
argument_group_signatures = [] |
| 5425 |
usage = '''\ |
| 5426 |
usage: PROG [-h] [--foo FOO] spam |
| 5427 |
''' |
| 5428 |
help = usage + '''\ |
| 5429 |
|
| 5430 |
positional arguments: |
| 5431 |
spam spam help |
| 5432 |
|
| 5433 |
options: |
| 5434 |
-h, --help show this help message and exit |
| 5435 |
--foo FOO foo help |
| 5436 |
''' |
| 5437 |
|
| 5438 |
|
| 5439 |
class TestHelpSubparsersOrdering(HelpTestCase): |
| 5440 |
"""Test ordering of subcommands in help matches the code""" |
| 5441 |
parser_signature = Sig(prog='PROG', |
| 5442 |
description='display some subcommands') |
| 5443 |
argument_signatures = [Sig('-v', '--version', action='version', version='0.1')] |
| 5444 |
|
| 5445 |
subparsers_signatures = [Sig(name=name) |
| 5446 |
for name in ('a', 'b', 'c', 'd', 'e')] |
| 5447 |
|
| 5448 |
usage = '''\ |
| 5449 |
usage: PROG [-h] [-v] {a,b,c,d,e} ... |
| 5450 |
''' |
| 5451 |
|
| 5452 |
help = usage + '''\ |
| 5453 |
|
| 5454 |
display some subcommands |
| 5455 |
|
| 5456 |
positional arguments: |
| 5457 |
{a,b,c,d,e} |
| 5458 |
|
| 5459 |
options: |
| 5460 |
-h, --help show this help message and exit |
| 5461 |
-v, --version show program's version number and exit |
| 5462 |
''' |
| 5463 |
|
| 5464 |
version = '''\ |
| 5465 |
0.1 |
| 5466 |
''' |
| 5467 |
|
| 5468 |
class TestHelpSubparsersWithHelpOrdering(HelpTestCase): |
| 5469 |
"""Test ordering of subcommands in help matches the code""" |
| 5470 |
parser_signature = Sig(prog='PROG', |
| 5471 |
description='display some subcommands') |
| 5472 |
argument_signatures = [Sig('-v', '--version', action='version', version='0.1')] |
| 5473 |
|
| 5474 |
subcommand_data = (('a', 'a subcommand help'), |
| 5475 |
('b', 'b subcommand help'), |
| 5476 |
('c', 'c subcommand help'), |
| 5477 |
('d', 'd subcommand help'), |
| 5478 |
('e', 'e subcommand help'), |
| 5479 |
) |
| 5480 |
|
| 5481 |
subparsers_signatures = [Sig(name=name, help=help) |
| 5482 |
for name, help in subcommand_data] |
| 5483 |
|
| 5484 |
usage = '''\ |
| 5485 |
usage: PROG [-h] [-v] {a,b,c,d,e} ... |
| 5486 |
''' |
| 5487 |
|
| 5488 |
help = usage + '''\ |
| 5489 |
|
| 5490 |
display some subcommands |
| 5491 |
|
| 5492 |
positional arguments: |
| 5493 |
{a,b,c,d,e} |
| 5494 |
a a subcommand help |
| 5495 |
b b subcommand help |
| 5496 |
c c subcommand help |
| 5497 |
d d subcommand help |
| 5498 |
e e subcommand help |
| 5499 |
|
| 5500 |
options: |
| 5501 |
-h, --help show this help message and exit |
| 5502 |
-v, --version show program's version number and exit |
| 5503 |
''' |
| 5504 |
|
| 5505 |
version = '''\ |
| 5506 |
0.1 |
| 5507 |
''' |
| 5508 |
|
| 5509 |
|
| 5510 |
|
| 5511 |
class TestHelpMetavarTypeFormatter(HelpTestCase): |
| 5512 |
|
| 5513 |
def custom_type(string): |
| 5514 |
return string |
| 5515 |
|
| 5516 |
parser_signature = Sig(prog='PROG', description='description', |
| 5517 |
formatter_class=argparse.MetavarTypeHelpFormatter) |
| 5518 |
argument_signatures = [Sig('a', type=int), |
| 5519 |
Sig('-b', type=custom_type), |
| 5520 |
Sig('-c', type=float, metavar='SOME FLOAT')] |
| 5521 |
argument_group_signatures = [] |
| 5522 |
usage = '''\ |
| 5523 |
usage: PROG [-h] [-b custom_type] [-c SOME FLOAT] int |
| 5524 |
''' |
| 5525 |
help = usage + '''\ |
| 5526 |
|
| 5527 |
description |
| 5528 |
|
| 5529 |
positional arguments: |
| 5530 |
int |
| 5531 |
|
| 5532 |
options: |
| 5533 |
-h, --help show this help message and exit |
| 5534 |
-b custom_type |
| 5535 |
-c SOME FLOAT |
| 5536 |
''' |
| 5537 |
version = '' |
| 5538 |
|
| 5539 |
|
| 5540 |
@force_not_colorized_test_class |
| 5541 |
class TestHelpCustomHelpFormatter(TestCase): |
| 5542 |
maxDiff = None |
| 5543 |
|
| 5544 |
def test_custom_formatter_function(self): |
| 5545 |
def custom_formatter(prog): |
| 5546 |
return argparse.RawTextHelpFormatter(prog, indent_increment=5) |
| 5547 |
|
| 5548 |
parser = argparse.ArgumentParser( |
| 5549 |
prog='PROG', |
| 5550 |
prefix_chars='-+', |
| 5551 |
formatter_class=custom_formatter |
| 5552 |
) |
| 5553 |
parser.add_argument('+f', '++foo', help="foo help") |
| 5554 |
parser.add_argument('spam', help="spam help") |
| 5555 |
|
| 5556 |
parser_help = parser.format_help() |
| 5557 |
self.assertEqual(parser_help, textwrap.dedent('''\ |
| 5558 |
usage: PROG [-h] [+f FOO] spam |
| 5559 |
|
| 5560 |
positional arguments: |
| 5561 |
spam spam help |
| 5562 |
|
| 5563 |
options: |
| 5564 |
-h, --help show this help message and exit |
| 5565 |
+f, ++foo FOO foo help |
| 5566 |
''')) |
| 5567 |
|
| 5568 |
def test_custom_formatter_class(self): |
| 5569 |
class CustomFormatter(argparse.RawTextHelpFormatter): |
| 5570 |
def __init__(self, prog): |
| 5571 |
super().__init__(prog, indent_increment=5) |
| 5572 |
|
| 5573 |
parser = argparse.ArgumentParser( |
| 5574 |
prog='PROG', |
| 5575 |
prefix_chars='-+', |
| 5576 |
formatter_class=CustomFormatter |
| 5577 |
) |
| 5578 |
parser.add_argument('+f', '++foo', help="foo help") |
| 5579 |
parser.add_argument('spam', help="spam help") |
| 5580 |
|
| 5581 |
parser_help = parser.format_help() |
| 5582 |
self.assertEqual(parser_help, textwrap.dedent('''\ |
| 5583 |
usage: PROG [-h] [+f FOO] spam |
| 5584 |
|
| 5585 |
positional arguments: |
| 5586 |
spam spam help |
| 5587 |
|
| 5588 |
options: |
| 5589 |
-h, --help show this help message and exit |
| 5590 |
+f, ++foo FOO foo help |
| 5591 |
''')) |
| 5592 |
|
| 5593 |
def test_usage_long_subparser_command(self): |
| 5594 |
"""Test that subparser commands are formatted correctly in help""" |
| 5595 |
def custom_formatter(prog): |
| 5596 |
return argparse.RawTextHelpFormatter(prog, max_help_position=50) |
| 5597 |
|
| 5598 |
parent_parser = argparse.ArgumentParser( |
| 5599 |
prog='PROG', |
| 5600 |
formatter_class=custom_formatter |
| 5601 |
) |
| 5602 |
|
| 5603 |
cmd_subparsers = parent_parser.add_subparsers(title="commands", |
| 5604 |
metavar='CMD', |
| 5605 |
help='command to use') |
| 5606 |
cmd_subparsers.add_parser("add", |
| 5607 |
help="add something") |
| 5608 |
|
| 5609 |
cmd_subparsers.add_parser("remove", |
| 5610 |
help="remove something") |
| 5611 |
|
| 5612 |
cmd_subparsers.add_parser("a-very-long-command", |
| 5613 |
help="command that does something") |
| 5614 |
|
| 5615 |
parser_help = parent_parser.format_help() |
| 5616 |
self.assertEqual(parser_help, textwrap.dedent('''\ |
| 5617 |
usage: PROG [-h] CMD ... |
| 5618 |
|
| 5619 |
options: |
| 5620 |
-h, --help show this help message and exit |
| 5621 |
|
| 5622 |
commands: |
| 5623 |
CMD command to use |
| 5624 |
add add something |
| 5625 |
remove remove something |
| 5626 |
a-very-long-command command that does something |
| 5627 |
''')) |
| 5628 |
|
| 5629 |
|
| 5630 |
# ===================================== |
| 5631 |
# Optional/Positional constructor tests |
| 5632 |
# ===================================== |
| 5633 |
|
| 5634 |
class TestInvalidArgumentConstructors(TestCase): |
| 5635 |
"""Test a bunch of invalid Argument constructors""" |
| 5636 |
|
| 5637 |
def assertTypeError(self, *args, errmsg=None, **kwargs): |
| 5638 |
parser = argparse.ArgumentParser() |
| 5639 |
self.assertRaisesRegex(TypeError, errmsg, parser.add_argument, |
| 5640 |
*args, **kwargs) |
| 5641 |
|
| 5642 |
def assertValueError(self, *args, errmsg=None, **kwargs): |
| 5643 |
parser = argparse.ArgumentParser() |
| 5644 |
self.assertRaisesRegex(ValueError, errmsg, parser.add_argument, |
| 5645 |
*args, **kwargs) |
| 5646 |
|
| 5647 |
def test_invalid_keyword_arguments(self): |
| 5648 |
self.assertTypeError('-x', bar=None) |
| 5649 |
self.assertTypeError('-y', callback='foo') |
| 5650 |
self.assertTypeError('-y', callback_args=()) |
| 5651 |
self.assertTypeError('-y', callback_kwargs={}) |
| 5652 |
|
| 5653 |
def test_missing_destination(self): |
| 5654 |
self.assertTypeError() |
| 5655 |
for action in ['store', 'append', 'extend']: |
| 5656 |
with self.subTest(action=action): |
| 5657 |
self.assertTypeError(action=action) |
| 5658 |
|
| 5659 |
def test_invalid_option_strings(self): |
| 5660 |
self.assertTypeError('-', errmsg='dest= is required') |
| 5661 |
self.assertTypeError('--', errmsg='dest= is required') |
| 5662 |
self.assertTypeError('---', errmsg='dest= is required') |
| 5663 |
|
| 5664 |
def test_invalid_prefix(self): |
| 5665 |
self.assertValueError('--foo', '+foo', |
| 5666 |
errmsg='must start with a character') |
| 5667 |
|
| 5668 |
def test_invalid_type(self): |
| 5669 |
self.assertTypeError('--foo', type='int', |
| 5670 |
errmsg="'int' is not callable") |
| 5671 |
self.assertTypeError('--foo', type=(int, float), |
| 5672 |
errmsg='is not callable') |
| 5673 |
|
| 5674 |
def test_invalid_action(self): |
| 5675 |
self.assertValueError('-x', action='foo', |
| 5676 |
errmsg='unknown action') |
| 5677 |
self.assertValueError('foo', action='baz', |
| 5678 |
errmsg='unknown action') |
| 5679 |
self.assertValueError('--foo', action=('store', 'append'), |
| 5680 |
errmsg='unknown action') |
| 5681 |
self.assertValueError('--foo', action="store-true", |
| 5682 |
errmsg='unknown action') |
| 5683 |
|
| 5684 |
def test_invalid_help(self): |
| 5685 |
self.assertValueError('--foo', help='%Y-%m-%d', |
| 5686 |
errmsg='badly formed help string') |
| 5687 |
self.assertValueError('--foo', help='%(spam)s', |
| 5688 |
errmsg='badly formed help string') |
| 5689 |
self.assertValueError('--foo', help='%(prog)d', |
| 5690 |
errmsg='badly formed help string') |
| 5691 |
|
| 5692 |
def test_multiple_dest(self): |
| 5693 |
parser = argparse.ArgumentParser() |
| 5694 |
parser.add_argument(dest='foo') |
| 5695 |
with self.assertRaises(TypeError) as cm: |
| 5696 |
parser.add_argument('bar', dest='baz') |
| 5697 |
self.assertIn('dest supplied twice for positional argument,' |
| 5698 |
' did you mean metavar?', |
| 5699 |
str(cm.exception)) |
| 5700 |
|
| 5701 |
def test_no_argument_actions(self): |
| 5702 |
for action in ['store_const', 'store_true', 'store_false', |
| 5703 |
'append_const', 'count']: |
| 5704 |
with self.subTest(action=action): |
| 5705 |
for attrs in [dict(type=int), dict(nargs='+'), |
| 5706 |
dict(choices=['a', 'b'])]: |
| 5707 |
with self.subTest(attrs=attrs): |
| 5708 |
self.assertTypeError('-x', action=action, **attrs) |
| 5709 |
self.assertTypeError('x', action=action, **attrs) |
| 5710 |
self.assertValueError('x', action=action, |
| 5711 |
errmsg=f"action '{action}' is not valid for positional arguments") |
| 5712 |
self.assertTypeError('-x', action=action, nargs=0) |
| 5713 |
self.assertValueError('x', action=action, nargs=0, |
| 5714 |
errmsg='nargs for positionals must be != 0') |
| 5715 |
|
| 5716 |
def test_no_argument_no_const_actions(self): |
| 5717 |
# options with zero arguments |
| 5718 |
for action in ['store_true', 'store_false', 'count']: |
| 5719 |
with self.subTest(action=action): |
| 5720 |
# const is always disallowed |
| 5721 |
self.assertTypeError('-x', const='foo', action=action) |
| 5722 |
|
| 5723 |
# nargs is always disallowed |
| 5724 |
self.assertTypeError('-x', nargs='*', action=action) |
| 5725 |
|
| 5726 |
def test_more_than_one_argument_actions(self): |
| 5727 |
for action in ['store', 'append', 'extend']: |
| 5728 |
with self.subTest(action=action): |
| 5729 |
# nargs=0 is disallowed |
| 5730 |
action_name = 'append' if action == 'extend' else action |
| 5731 |
self.assertValueError('-x', nargs=0, action=action, |
| 5732 |
errmsg=f'nargs for {action_name} actions must be != 0') |
| 5733 |
self.assertValueError('spam', nargs=0, action=action, |
| 5734 |
errmsg='nargs for positionals must be != 0') |
| 5735 |
|
| 5736 |
# const is disallowed with non-optional arguments |
| 5737 |
for nargs in [1, '*', '+']: |
| 5738 |
self.assertValueError('-x', const='foo', |
| 5739 |
nargs=nargs, action=action) |
| 5740 |
self.assertValueError('spam', const='foo', |
| 5741 |
nargs=nargs, action=action) |
| 5742 |
|
| 5743 |
def test_required_const_actions(self): |
| 5744 |
for action in ['store_const', 'append_const']: |
| 5745 |
with self.subTest(action=action): |
| 5746 |
# nargs is always disallowed |
| 5747 |
self.assertTypeError('-x', nargs='+', action=action) |
| 5748 |
|
| 5749 |
def test_parsers_action_missing_params(self): |
| 5750 |
self.assertTypeError('command', action='parsers') |
| 5751 |
self.assertTypeError('command', action='parsers', prog='PROG') |
| 5752 |
self.assertTypeError('command', action='parsers', |
| 5753 |
parser_class=argparse.ArgumentParser) |
| 5754 |
|
| 5755 |
def test_version_missing_params(self): |
| 5756 |
self.assertTypeError('command', action='version') |
| 5757 |
|
| 5758 |
def test_required_positional(self): |
| 5759 |
self.assertTypeError('foo', required=True) |
| 5760 |
|
| 5761 |
def test_user_defined_action(self): |
| 5762 |
|
| 5763 |
class Success(Exception): |
| 5764 |
pass |
| 5765 |
|
| 5766 |
class Action(object): |
| 5767 |
|
| 5768 |
def __init__(self, |
| 5769 |
option_strings, |
| 5770 |
dest, |
| 5771 |
const, |
| 5772 |
default, |
| 5773 |
required=False): |
| 5774 |
if dest == 'spam': |
| 5775 |
if const is Success: |
| 5776 |
if default is Success: |
| 5777 |
raise Success() |
| 5778 |
|
| 5779 |
def __call__(self, *args, **kwargs): |
| 5780 |
pass |
| 5781 |
|
| 5782 |
parser = argparse.ArgumentParser() |
| 5783 |
self.assertRaises(Success, parser.add_argument, '--spam', |
| 5784 |
action=Action, default=Success, const=Success) |
| 5785 |
self.assertRaises(Success, parser.add_argument, 'spam', |
| 5786 |
action=Action, default=Success, const=Success) |
| 5787 |
|
| 5788 |
# ================================ |
| 5789 |
# Actions returned by add_argument |
| 5790 |
# ================================ |
| 5791 |
|
| 5792 |
class TestActionsReturned(TestCase): |
| 5793 |
|
| 5794 |
def test_dest(self): |
| 5795 |
parser = argparse.ArgumentParser() |
| 5796 |
action = parser.add_argument('--foo') |
| 5797 |
self.assertEqual(action.dest, 'foo') |
| 5798 |
action = parser.add_argument('-b', '--bar') |
| 5799 |
self.assertEqual(action.dest, 'bar') |
| 5800 |
action = parser.add_argument('-x', '-y') |
| 5801 |
self.assertEqual(action.dest, 'x') |
| 5802 |
|
| 5803 |
def test_misc(self): |
| 5804 |
parser = argparse.ArgumentParser() |
| 5805 |
action = parser.add_argument('--foo', nargs='?', const=42, |
| 5806 |
default=84, type=int, choices=[1, 2], |
| 5807 |
help='FOO', metavar='BAR', dest='baz') |
| 5808 |
self.assertEqual(action.nargs, '?') |
| 5809 |
self.assertEqual(action.const, 42) |
| 5810 |
self.assertEqual(action.default, 84) |
| 5811 |
self.assertEqual(action.type, int) |
| 5812 |
self.assertEqual(action.choices, [1, 2]) |
| 5813 |
self.assertEqual(action.help, 'FOO') |
| 5814 |
self.assertEqual(action.metavar, 'BAR') |
| 5815 |
self.assertEqual(action.dest, 'baz') |
| 5816 |
|
| 5817 |
|
| 5818 |
# ================================ |
| 5819 |
# Argument conflict handling tests |
| 5820 |
# ================================ |
| 5821 |
|
| 5822 |
class TestConflictHandling(TestCase): |
| 5823 |
|
| 5824 |
def test_bad_type(self): |
| 5825 |
self.assertRaises(ValueError, argparse.ArgumentParser, |
| 5826 |
conflict_handler='foo') |
| 5827 |
|
| 5828 |
def test_conflict_error(self): |
| 5829 |
parser = argparse.ArgumentParser() |
| 5830 |
parser.add_argument('-x') |
| 5831 |
self.assertRaises(argparse.ArgumentError, |
| 5832 |
parser.add_argument, '-x') |
| 5833 |
parser.add_argument('--spam') |
| 5834 |
self.assertRaises(argparse.ArgumentError, |
| 5835 |
parser.add_argument, '--spam') |
| 5836 |
|
| 5837 |
@force_not_colorized |
| 5838 |
def test_resolve_error(self): |
| 5839 |
get_parser = argparse.ArgumentParser |
| 5840 |
parser = get_parser(prog='PROG', conflict_handler='resolve') |
| 5841 |
|
| 5842 |
parser.add_argument('-x', help='OLD X') |
| 5843 |
parser.add_argument('-x', help='NEW X') |
| 5844 |
self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
| 5845 |
usage: PROG [-h] [-x X] |
| 5846 |
|
| 5847 |
options: |
| 5848 |
-h, --help show this help message and exit |
| 5849 |
-x X NEW X |
| 5850 |
''')) |
| 5851 |
|
| 5852 |
parser.add_argument('--spam', metavar='OLD_SPAM') |
| 5853 |
parser.add_argument('--spam', metavar='NEW_SPAM') |
| 5854 |
self.assertEqual(parser.format_help(), textwrap.dedent('''\ |
| 5855 |
usage: PROG [-h] [-x X] [--spam NEW_SPAM] |
| 5856 |
|
| 5857 |
options: |
| 5858 |
-h, --help show this help message and exit |
| 5859 |
-x X NEW X |
| 5860 |
--spam NEW_SPAM |
| 5861 |
''')) |
| 5862 |
|
| 5863 |
def test_subparser_conflict(self): |
| 5864 |
parser = argparse.ArgumentParser() |
| 5865 |
sp = parser.add_subparsers() |
| 5866 |
sp.add_parser('fullname', aliases=['alias']) |
| 5867 |
self.assertRaisesRegex(ValueError, |
| 5868 |
'conflicting subparser: fullname', |
| 5869 |
sp.add_parser, 'fullname') |
| 5870 |
self.assertRaisesRegex(ValueError, |
| 5871 |
'conflicting subparser: alias', |
| 5872 |
sp.add_parser, 'alias') |
| 5873 |
self.assertRaisesRegex(ValueError, |
| 5874 |
'conflicting subparser alias: fullname', |
| 5875 |
sp.add_parser, 'other', aliases=['fullname']) |
| 5876 |
self.assertRaisesRegex(ValueError, |
| 5877 |
'conflicting subparser alias: alias', |
| 5878 |
sp.add_parser, 'other', aliases=['alias']) |
| 5879 |
|
| 5880 |
|
| 5881 |
# ============================= |
| 5882 |
# Help and Version option tests |
| 5883 |
# ============================= |
| 5884 |
|
| 5885 |
@force_not_colorized_test_class |
| 5886 |
class TestOptionalsHelpVersionActions(TestCase): |
| 5887 |
"""Test the help and version actions""" |
| 5888 |
|
| 5889 |
def assertPrintHelpExit(self, parser, args_str): |
| 5890 |
with self.assertRaises(ArgumentParserError) as cm: |
| 5891 |
parser.parse_args(args_str.split()) |
| 5892 |
self.assertEqual(parser.format_help(), cm.exception.stdout) |
| 5893 |
|
| 5894 |
def assertArgumentParserError(self, parser, *args): |
| 5895 |
self.assertRaises(ArgumentParserError, parser.parse_args, args) |
| 5896 |
|
| 5897 |
def test_version(self): |
| 5898 |
parser = ErrorRaisingArgumentParser() |
| 5899 |
parser.add_argument('-v', '--version', action='version', version='1.0') |
| 5900 |
self.assertPrintHelpExit(parser, '-h') |
| 5901 |
self.assertPrintHelpExit(parser, '--help') |
| 5902 |
self.assertRaises(AttributeError, getattr, parser, 'format_version') |
| 5903 |
|
| 5904 |
def test_version_format(self): |
| 5905 |
parser = ErrorRaisingArgumentParser(prog='PPP') |
| 5906 |
parser.add_argument('-v', '--version', action='version', version='%(prog)s 3.5') |
| 5907 |
with self.assertRaises(ArgumentParserError) as cm: |
| 5908 |
parser.parse_args(['-v']) |
| 5909 |
self.assertEqual('PPP 3.5\n', cm.exception.stdout) |
| 5910 |
|
| 5911 |
def test_version_no_help(self): |
| 5912 |
parser = ErrorRaisingArgumentParser(add_help=False) |
| 5913 |
parser.add_argument('-v', '--version', action='version', version='1.0') |
| 5914 |
self.assertArgumentParserError(parser, '-h') |
| 5915 |
self.assertArgumentParserError(parser, '--help') |
| 5916 |
self.assertRaises(AttributeError, getattr, parser, 'format_version') |
| 5917 |
|
| 5918 |
def test_version_action(self): |
| 5919 |
parser = ErrorRaisingArgumentParser(prog='XXX') |
| 5920 |
parser.add_argument('-V', action='version', version='%(prog)s 3.7') |
| 5921 |
with self.assertRaises(ArgumentParserError) as cm: |
| 5922 |
parser.parse_args(['-V']) |
| 5923 |
self.assertEqual('XXX 3.7\n', cm.exception.stdout) |
| 5924 |
|
| 5925 |
def test_no_help(self): |
| 5926 |
parser = ErrorRaisingArgumentParser(add_help=False) |
| 5927 |
self.assertArgumentParserError(parser, '-h') |
| 5928 |
self.assertArgumentParserError(parser, '--help') |
| 5929 |
self.assertArgumentParserError(parser, '-v') |
| 5930 |
self.assertArgumentParserError(parser, '--version') |
| 5931 |
|
| 5932 |
def test_alternate_help_version(self): |
| 5933 |
parser = ErrorRaisingArgumentParser() |
| 5934 |
parser.add_argument('-x', action='help') |
| 5935 |
parser.add_argument('-y', action='version') |
| 5936 |
self.assertPrintHelpExit(parser, '-x') |
| 5937 |
self.assertArgumentParserError(parser, '-v') |
| 5938 |
self.assertArgumentParserError(parser, '--version') |
| 5939 |
self.assertRaises(AttributeError, getattr, parser, 'format_version') |
| 5940 |
|
| 5941 |
def test_help_version_extra_arguments(self): |
| 5942 |
parser = ErrorRaisingArgumentParser() |
| 5943 |
parser.add_argument('--version', action='version', version='1.0') |
| 5944 |
parser.add_argument('-x', action='store_true') |
| 5945 |
parser.add_argument('y') |
| 5946 |
|
| 5947 |
# try all combinations of valid prefixes and suffixes |
| 5948 |
valid_prefixes = ['', '-x', 'foo', '-x bar', 'baz -x'] |
| 5949 |
valid_suffixes = valid_prefixes + ['--bad-option', 'foo bar baz'] |
| 5950 |
for prefix in valid_prefixes: |
| 5951 |
for suffix in valid_suffixes: |
| 5952 |
format = '%s %%s %s' % (prefix, suffix) |
| 5953 |
self.assertPrintHelpExit(parser, format % '-h') |
| 5954 |
self.assertPrintHelpExit(parser, format % '--help') |
| 5955 |
self.assertRaises(AttributeError, getattr, parser, 'format_version') |
| 5956 |
|
| 5957 |
|
| 5958 |
# ====================== |
| 5959 |
# str() and repr() tests |
| 5960 |
# ====================== |
| 5961 |
|
| 5962 |
class TestStrings(TestCase): |
| 5963 |
"""Test str() and repr() on Optionals and Positionals""" |
| 5964 |
|
| 5965 |
def assertStringEqual(self, obj, result_string): |
| 5966 |
for func in [str, repr]: |
| 5967 |
self.assertEqual(func(obj), result_string) |
| 5968 |
|
| 5969 |
def test_optional(self): |
| 5970 |
option = argparse.Action( |
| 5971 |
option_strings=['--foo', '-a', '-b'], |
| 5972 |
dest='b', |
| 5973 |
type='int', |
| 5974 |
nargs='+', |
| 5975 |
default=42, |
| 5976 |
choices=[1, 2, 3], |
| 5977 |
required=False, |
| 5978 |
help='HELP', |
| 5979 |
metavar='METAVAR') |
| 5980 |
string = ( |
| 5981 |
"Action(option_strings=['--foo', '-a', '-b'], dest='b', " |
| 5982 |
"nargs='+', const=None, default=42, type='int', " |
| 5983 |
"choices=[1, 2, 3], required=False, help='HELP', " |
| 5984 |
"metavar='METAVAR', deprecated=False)") |
| 5985 |
self.assertStringEqual(option, string) |
| 5986 |
|
| 5987 |
def test_argument(self): |
| 5988 |
argument = argparse.Action( |
| 5989 |
option_strings=[], |
| 5990 |
dest='x', |
| 5991 |
type=float, |
| 5992 |
nargs='?', |
| 5993 |
default=2.5, |
| 5994 |
choices=[0.5, 1.5, 2.5], |
| 5995 |
required=True, |
| 5996 |
help='H HH H', |
| 5997 |
metavar='MV MV MV') |
| 5998 |
string = ( |
| 5999 |
"Action(option_strings=[], dest='x', nargs='?', " |
| 6000 |
"const=None, default=2.5, type=%r, choices=[0.5, 1.5, 2.5], " |
| 6001 |
"required=True, help='H HH H', metavar='MV MV MV', " |
| 6002 |
"deprecated=False)" % float) |
| 6003 |
self.assertStringEqual(argument, string) |
| 6004 |
|
| 6005 |
def test_namespace(self): |
| 6006 |
ns = argparse.Namespace(foo=42, bar='spam') |
| 6007 |
string = "Namespace(foo=42, bar='spam')" |
| 6008 |
self.assertStringEqual(ns, string) |
| 6009 |
|
| 6010 |
def test_namespace_starkwargs_notidentifier(self): |
| 6011 |
ns = argparse.Namespace(**{'"': 'quote'}) |
| 6012 |
string = """Namespace(**{'"': 'quote'})""" |
| 6013 |
self.assertStringEqual(ns, string) |
| 6014 |
|
| 6015 |
def test_namespace_kwargs_and_starkwargs_notidentifier(self): |
| 6016 |
ns = argparse.Namespace(a=1, **{'"': 'quote'}) |
| 6017 |
string = """Namespace(a=1, **{'"': 'quote'})""" |
| 6018 |
self.assertStringEqual(ns, string) |
| 6019 |
|
| 6020 |
def test_namespace_starkwargs_identifier(self): |
| 6021 |
ns = argparse.Namespace(**{'valid': True}) |
| 6022 |
string = "Namespace(valid=True)" |
| 6023 |
self.assertStringEqual(ns, string) |
| 6024 |
|
| 6025 |
def test_parser(self): |
| 6026 |
parser = argparse.ArgumentParser(prog='PROG') |
| 6027 |
string = ( |
| 6028 |
"ArgumentParser(prog='PROG', usage=None, description=None, " |
| 6029 |
"formatter_class=%r, conflict_handler='error', " |
| 6030 |
"add_help=True)" % argparse.HelpFormatter) |
| 6031 |
self.assertStringEqual(parser, string) |
| 6032 |
|
| 6033 |
# =============== |
| 6034 |
# Namespace tests |
| 6035 |
# =============== |
| 6036 |
|
| 6037 |
class TestNamespace(TestCase): |
| 6038 |
|
| 6039 |
def test_constructor(self): |
| 6040 |
ns = argparse.Namespace() |
| 6041 |
self.assertRaises(AttributeError, getattr, ns, 'x') |
| 6042 |
|
| 6043 |
ns = argparse.Namespace(a=42, b='spam') |
| 6044 |
self.assertEqual(ns.a, 42) |
| 6045 |
self.assertEqual(ns.b, 'spam') |
| 6046 |
|
| 6047 |
def test_equality(self): |
| 6048 |
ns1 = argparse.Namespace(a=1, b=2) |
| 6049 |
ns2 = argparse.Namespace(b=2, a=1) |
| 6050 |
ns3 = argparse.Namespace(a=1) |
| 6051 |
ns4 = argparse.Namespace(b=2) |
| 6052 |
|
| 6053 |
self.assertEqual(ns1, ns2) |
| 6054 |
self.assertNotEqual(ns1, ns3) |
| 6055 |
self.assertNotEqual(ns1, ns4) |
| 6056 |
self.assertNotEqual(ns2, ns3) |
| 6057 |
self.assertNotEqual(ns2, ns4) |
| 6058 |
self.assertTrue(ns1 != ns3) |
| 6059 |
self.assertTrue(ns1 != ns4) |
| 6060 |
self.assertTrue(ns2 != ns3) |
| 6061 |
self.assertTrue(ns2 != ns4) |
| 6062 |
|
| 6063 |
def test_equality_returns_notimplemented(self): |
| 6064 |
# See issue 21481 |
| 6065 |
ns = argparse.Namespace(a=1, b=2) |
| 6066 |
self.assertIs(ns.__eq__(None), NotImplemented) |
| 6067 |
self.assertIs(ns.__ne__(None), NotImplemented) |
| 6068 |
|
| 6069 |
|
| 6070 |
# =================== |
| 6071 |
# File encoding tests |
| 6072 |
# =================== |
| 6073 |
|
| 6074 |
class TestEncoding(TestCase): |
| 6075 |
|
| 6076 |
def _test_module_encoding(self, path): |
| 6077 |
path, _ = os.path.splitext(path) |
| 6078 |
path += ".py" |
| 6079 |
with open(path, 'r', encoding='utf-8') as f: |
| 6080 |
f.read() |
| 6081 |
|
| 6082 |
def test_argparse_module_encoding(self): |
| 6083 |
self._test_module_encoding(argparse.__file__) |
| 6084 |
|
| 6085 |
def test_test_argparse_module_encoding(self): |
| 6086 |
self._test_module_encoding(__file__) |
| 6087 |
|
| 6088 |
# =================== |
| 6089 |
# ArgumentError tests |
| 6090 |
# =================== |
| 6091 |
|
| 6092 |
class TestArgumentError(TestCase): |
| 6093 |
|
| 6094 |
def test_argument_error(self): |
| 6095 |
msg = "my error here" |
| 6096 |
error = argparse.ArgumentError(None, msg) |
| 6097 |
self.assertEqual(str(error), msg) |
| 6098 |
|
| 6099 |
# ======================= |
| 6100 |
# ArgumentTypeError tests |
| 6101 |
# ======================= |
| 6102 |
|
| 6103 |
class TestArgumentTypeError(TestCase): |
| 6104 |
|
| 6105 |
@force_not_colorized |
| 6106 |
def test_argument_type_error(self): |
| 6107 |
|
| 6108 |
def spam(string): |
| 6109 |
raise argparse.ArgumentTypeError('spam!') |
| 6110 |
|
| 6111 |
parser = ErrorRaisingArgumentParser(prog='PROG', add_help=False) |
| 6112 |
parser.add_argument('x', type=spam) |
| 6113 |
with self.assertRaises(ArgumentParserError) as cm: |
| 6114 |
parser.parse_args(['XXX']) |
| 6115 |
self.assertEqual('usage: PROG x\nPROG: error: argument x: spam!\n', |
| 6116 |
cm.exception.stderr) |
| 6117 |
|
| 6118 |
# ========================= |
| 6119 |
# MessageContentError tests |
| 6120 |
# ========================= |
| 6121 |
|
| 6122 |
class TestMessageContentError(TestCase): |
| 6123 |
|
| 6124 |
def test_missing_argument_name_in_message(self): |
| 6125 |
parser = ErrorRaisingArgumentParser(prog='PROG', usage='') |
| 6126 |
parser.add_argument('req_pos', type=str) |
| 6127 |
parser.add_argument('-req_opt', type=int, required=True) |
| 6128 |
parser.add_argument('need_one', type=str, nargs='+') |
| 6129 |
|
| 6130 |
with self.assertRaises(ArgumentParserError) as cm: |
| 6131 |
parser.parse_args([]) |
| 6132 |
msg = str(cm.exception) |
| 6133 |
self.assertRegex(msg, 'req_pos') |
| 6134 |
self.assertRegex(msg, 'req_opt') |
| 6135 |
self.assertRegex(msg, 'need_one') |
| 6136 |
with self.assertRaises(ArgumentParserError) as cm: |
| 6137 |
parser.parse_args(['myXargument']) |
| 6138 |
msg = str(cm.exception) |
| 6139 |
self.assertNotIn(msg, 'req_pos') |
| 6140 |
self.assertRegex(msg, 'req_opt') |
| 6141 |
self.assertRegex(msg, 'need_one') |
| 6142 |
with self.assertRaises(ArgumentParserError) as cm: |
| 6143 |
parser.parse_args(['myXargument', '-req_opt=1']) |
| 6144 |
msg = str(cm.exception) |
| 6145 |
self.assertNotIn(msg, 'req_pos') |
| 6146 |
self.assertNotIn(msg, 'req_opt') |
| 6147 |
self.assertRegex(msg, 'need_one') |
| 6148 |
|
| 6149 |
def test_optional_optional_not_in_message(self): |
| 6150 |
parser = ErrorRaisingArgumentParser(prog='PROG', usage='') |
| 6151 |
parser.add_argument('req_pos', type=str) |
| 6152 |
parser.add_argument('--req_opt', type=int, required=True) |
| 6153 |
parser.add_argument('--opt_opt', type=bool, nargs='?', |
| 6154 |
default=True) |
| 6155 |
with self.assertRaises(ArgumentParserError) as cm: |
| 6156 |
parser.parse_args([]) |
| 6157 |
msg = str(cm.exception) |
| 6158 |
self.assertRegex(msg, 'req_pos') |
| 6159 |
self.assertRegex(msg, 'req_opt') |
| 6160 |
self.assertNotIn(msg, 'opt_opt') |
| 6161 |
with self.assertRaises(ArgumentParserError) as cm: |
| 6162 |
parser.parse_args(['--req_opt=1']) |
| 6163 |
msg = str(cm.exception) |
| 6164 |
self.assertRegex(msg, 'req_pos') |
| 6165 |
self.assertNotIn(msg, 'req_opt') |
| 6166 |
self.assertNotIn(msg, 'opt_opt') |
| 6167 |
|
| 6168 |
def test_optional_positional_not_in_message(self): |
| 6169 |
parser = ErrorRaisingArgumentParser(prog='PROG', usage='') |
| 6170 |
parser.add_argument('req_pos') |
| 6171 |
parser.add_argument('optional_positional', nargs='?', default='eggs') |
| 6172 |
with self.assertRaises(ArgumentParserError) as cm: |
| 6173 |
parser.parse_args([]) |
| 6174 |
msg = str(cm.exception) |
| 6175 |
self.assertRegex(msg, 'req_pos') |
| 6176 |
self.assertNotIn(msg, 'optional_positional') |
| 6177 |
|
| 6178 |
|
| 6179 |
# ================================================ |
| 6180 |
# Check that the type function is called only once |
| 6181 |
# ================================================ |
| 6182 |
|
| 6183 |
class TestTypeFunctionCallOnlyOnce(TestCase): |
| 6184 |
|
| 6185 |
def test_type_function_call_only_once(self): |
| 6186 |
def spam(string_to_convert): |
| 6187 |
self.assertEqual(string_to_convert, 'spam!') |
| 6188 |
return 'foo_converted' |
| 6189 |
|
| 6190 |
parser = argparse.ArgumentParser() |
| 6191 |
parser.add_argument('--foo', type=spam, default='bar') |
| 6192 |
args = parser.parse_args('--foo spam!'.split()) |
| 6193 |
self.assertEqual(NS(foo='foo_converted'), args) |
| 6194 |
|
| 6195 |
|
| 6196 |
# ============================================== |
| 6197 |
# Check that deprecated arguments output warning |
| 6198 |
# ============================================== |
| 6199 |
|
| 6200 |
class TestDeprecatedArguments(TestCase): |
| 6201 |
|
| 6202 |
def test_deprecated_option(self): |
| 6203 |
parser = argparse.ArgumentParser() |
| 6204 |
parser.add_argument('-f', '--foo', deprecated=True) |
| 6205 |
|
| 6206 |
with captured_stderr() as stderr: |
| 6207 |
parser.parse_args(['--foo', 'spam']) |
| 6208 |
stderr = stderr.getvalue() |
| 6209 |
self.assertRegex(stderr, "warning: option '--foo' is deprecated") |
| 6210 |
self.assertEqual(stderr.count('is deprecated'), 1) |
| 6211 |
|
| 6212 |
with captured_stderr() as stderr: |
| 6213 |
parser.parse_args(['-f', 'spam']) |
| 6214 |
stderr = stderr.getvalue() |
| 6215 |
self.assertRegex(stderr, "warning: option '-f' is deprecated") |
| 6216 |
self.assertEqual(stderr.count('is deprecated'), 1) |
| 6217 |
|
| 6218 |
with captured_stderr() as stderr: |
| 6219 |
parser.parse_args(['--foo', 'spam', '-f', 'ham']) |
| 6220 |
stderr = stderr.getvalue() |
| 6221 |
self.assertRegex(stderr, "warning: option '--foo' is deprecated") |
| 6222 |
self.assertRegex(stderr, "warning: option '-f' is deprecated") |
| 6223 |
self.assertEqual(stderr.count('is deprecated'), 2) |
| 6224 |
|
| 6225 |
with captured_stderr() as stderr: |
| 6226 |
parser.parse_args(['--foo', 'spam', '--foo', 'ham']) |
| 6227 |
stderr = stderr.getvalue() |
| 6228 |
self.assertRegex(stderr, "warning: option '--foo' is deprecated") |
| 6229 |
self.assertEqual(stderr.count('is deprecated'), 1) |
| 6230 |
|
| 6231 |
def test_deprecated_boolean_option(self): |
| 6232 |
parser = argparse.ArgumentParser() |
| 6233 |
parser.add_argument('-f', '--foo', action=argparse.BooleanOptionalAction, deprecated=True) |
| 6234 |
|
| 6235 |
with captured_stderr() as stderr: |
| 6236 |
parser.parse_args(['--foo']) |
| 6237 |
stderr = stderr.getvalue() |
| 6238 |
self.assertRegex(stderr, "warning: option '--foo' is deprecated") |
| 6239 |
self.assertEqual(stderr.count('is deprecated'), 1) |
| 6240 |
|
| 6241 |
with captured_stderr() as stderr: |
| 6242 |
parser.parse_args(['-f']) |
| 6243 |
stderr = stderr.getvalue() |
| 6244 |
self.assertRegex(stderr, "warning: option '-f' is deprecated") |
| 6245 |
self.assertEqual(stderr.count('is deprecated'), 1) |
| 6246 |
|
| 6247 |
with captured_stderr() as stderr: |
| 6248 |
parser.parse_args(['--no-foo']) |
| 6249 |
stderr = stderr.getvalue() |
| 6250 |
self.assertRegex(stderr, "warning: option '--no-foo' is deprecated") |
| 6251 |
self.assertEqual(stderr.count('is deprecated'), 1) |
| 6252 |
|
| 6253 |
with captured_stderr() as stderr: |
| 6254 |
parser.parse_args(['--foo', '--no-foo']) |
| 6255 |
stderr = stderr.getvalue() |
| 6256 |
self.assertRegex(stderr, "warning: option '--foo' is deprecated") |
| 6257 |
self.assertRegex(stderr, "warning: option '--no-foo' is deprecated") |
| 6258 |
self.assertEqual(stderr.count('is deprecated'), 2) |
| 6259 |
|
| 6260 |
def test_deprecated_arguments(self): |
| 6261 |
parser = argparse.ArgumentParser() |
| 6262 |
parser.add_argument('foo', nargs='?', deprecated=True) |
| 6263 |
parser.add_argument('bar', nargs='?', deprecated=True) |
| 6264 |
|
| 6265 |
with captured_stderr() as stderr: |
| 6266 |
parser.parse_args([]) |
| 6267 |
stderr = stderr.getvalue() |
| 6268 |
self.assertEqual(stderr.count('is deprecated'), 0) |
| 6269 |
|
| 6270 |
with captured_stderr() as stderr: |
| 6271 |
parser.parse_args(['spam']) |
| 6272 |
stderr = stderr.getvalue() |
| 6273 |
self.assertRegex(stderr, "warning: argument 'foo' is deprecated") |
| 6274 |
self.assertEqual(stderr.count('is deprecated'), 1) |
| 6275 |
|
| 6276 |
with captured_stderr() as stderr: |
| 6277 |
parser.parse_args(['spam', 'ham']) |
| 6278 |
stderr = stderr.getvalue() |
| 6279 |
self.assertRegex(stderr, "warning: argument 'foo' is deprecated") |
| 6280 |
self.assertRegex(stderr, "warning: argument 'bar' is deprecated") |
| 6281 |
self.assertEqual(stderr.count('is deprecated'), 2) |
| 6282 |
|
| 6283 |
def test_deprecated_varargument(self): |
| 6284 |
parser = argparse.ArgumentParser() |
| 6285 |
parser.add_argument('foo', nargs='*', deprecated=True) |
| 6286 |
|
| 6287 |
with captured_stderr() as stderr: |
| 6288 |
parser.parse_args([]) |
| 6289 |
stderr = stderr.getvalue() |
| 6290 |
self.assertEqual(stderr.count('is deprecated'), 0) |
| 6291 |
|
| 6292 |
with captured_stderr() as stderr: |
| 6293 |
parser.parse_args(['spam']) |
| 6294 |
stderr = stderr.getvalue() |
| 6295 |
self.assertRegex(stderr, "warning: argument 'foo' is deprecated") |
| 6296 |
self.assertEqual(stderr.count('is deprecated'), 1) |
| 6297 |
|
| 6298 |
with captured_stderr() as stderr: |
| 6299 |
parser.parse_args(['spam', 'ham']) |
| 6300 |
stderr = stderr.getvalue() |
| 6301 |
self.assertRegex(stderr, "warning: argument 'foo' is deprecated") |
| 6302 |
self.assertEqual(stderr.count('is deprecated'), 1) |
| 6303 |
|
| 6304 |
def test_deprecated_subparser(self): |
| 6305 |
parser = argparse.ArgumentParser() |
| 6306 |
subparsers = parser.add_subparsers() |
| 6307 |
subparsers.add_parser('foo', aliases=['baz'], deprecated=True) |
| 6308 |
subparsers.add_parser('bar') |
| 6309 |
|
| 6310 |
with captured_stderr() as stderr: |
| 6311 |
parser.parse_args(['bar']) |
| 6312 |
stderr = stderr.getvalue() |
| 6313 |
self.assertEqual(stderr.count('is deprecated'), 0) |
| 6314 |
|
| 6315 |
with captured_stderr() as stderr: |
| 6316 |
parser.parse_args(['foo']) |
| 6317 |
stderr = stderr.getvalue() |
| 6318 |
self.assertRegex(stderr, "warning: command 'foo' is deprecated") |
| 6319 |
self.assertEqual(stderr.count('is deprecated'), 1) |
| 6320 |
|
| 6321 |
with captured_stderr() as stderr: |
| 6322 |
parser.parse_args(['baz']) |
| 6323 |
stderr = stderr.getvalue() |
| 6324 |
self.assertRegex(stderr, "warning: command 'baz' is deprecated") |
| 6325 |
self.assertEqual(stderr.count('is deprecated'), 1) |
| 6326 |
|
| 6327 |
|
| 6328 |
# ================================================================== |
| 6329 |
# Check semantics regarding the default argument and type conversion |
| 6330 |
# ================================================================== |
| 6331 |
|
| 6332 |
class TestTypeFunctionCalledOnDefault(TestCase): |
| 6333 |
|
| 6334 |
def test_type_function_call_with_non_string_default(self): |
| 6335 |
def spam(int_to_convert): |
| 6336 |
self.assertEqual(int_to_convert, 0) |
| 6337 |
return 'foo_converted' |
| 6338 |
|
| 6339 |
parser = argparse.ArgumentParser() |
| 6340 |
parser.add_argument('--foo', type=spam, default=0) |
| 6341 |
args = parser.parse_args([]) |
| 6342 |
# foo should *not* be converted because its default is not a string. |
| 6343 |
self.assertEqual(NS(foo=0), args) |
| 6344 |
|
| 6345 |
def test_type_function_call_with_string_default(self): |
| 6346 |
def spam(int_to_convert): |
| 6347 |
return 'foo_converted' |
| 6348 |
|
| 6349 |
parser = argparse.ArgumentParser() |
| 6350 |
parser.add_argument('--foo', type=spam, default='0') |
| 6351 |
args = parser.parse_args([]) |
| 6352 |
# foo is converted because its default is a string. |
| 6353 |
self.assertEqual(NS(foo='foo_converted'), args) |
| 6354 |
|
| 6355 |
def test_no_double_type_conversion_of_default(self): |
| 6356 |
def extend(str_to_convert): |
| 6357 |
return str_to_convert + '*' |
| 6358 |
|
| 6359 |
parser = argparse.ArgumentParser() |
| 6360 |
parser.add_argument('--test', type=extend, default='*') |
| 6361 |
args = parser.parse_args([]) |
| 6362 |
# The test argument will be two stars, one coming from the default |
| 6363 |
# value and one coming from the type conversion being called exactly |
| 6364 |
# once. |
| 6365 |
self.assertEqual(NS(test='**'), args) |
| 6366 |
|
| 6367 |
def test_issue_15906(self): |
| 6368 |
# Issue #15906: When action='append', type=str, default=[] are |
| 6369 |
# providing, the dest value was the string representation "[]" when it |
| 6370 |
# should have been an empty list. |
| 6371 |
parser = argparse.ArgumentParser() |
| 6372 |
parser.add_argument('--test', dest='test', type=str, |
| 6373 |
default=[], action='append') |
| 6374 |
args = parser.parse_args([]) |
| 6375 |
self.assertEqual(args.test, []) |
| 6376 |
|
| 6377 |
# ====================== |
| 6378 |
# parse_known_args tests |
| 6379 |
# ====================== |
| 6380 |
|
| 6381 |
class TestParseKnownArgs(TestCase): |
| 6382 |
|
| 6383 |
def test_arguments_tuple(self): |
| 6384 |
parser = argparse.ArgumentParser() |
| 6385 |
parser.parse_args(()) |
| 6386 |
|
| 6387 |
def test_arguments_list(self): |
| 6388 |
parser = argparse.ArgumentParser() |
| 6389 |
parser.parse_args([]) |
| 6390 |
|
| 6391 |
def test_arguments_tuple_positional(self): |
| 6392 |
parser = argparse.ArgumentParser() |
| 6393 |
parser.add_argument('x') |
| 6394 |
parser.parse_args(('x',)) |
| 6395 |
|
| 6396 |
def test_arguments_list_positional(self): |
| 6397 |
parser = argparse.ArgumentParser() |
| 6398 |
parser.add_argument('x') |
| 6399 |
parser.parse_args(['x']) |
| 6400 |
|
| 6401 |
def test_optionals(self): |
| 6402 |
parser = argparse.ArgumentParser() |
| 6403 |
parser.add_argument('--foo') |
| 6404 |
args, extras = parser.parse_known_args('--foo F --bar --baz'.split()) |
| 6405 |
self.assertEqual(NS(foo='F'), args) |
| 6406 |
self.assertEqual(['--bar', '--baz'], extras) |
| 6407 |
|
| 6408 |
def test_mixed(self): |
| 6409 |
parser = argparse.ArgumentParser() |
| 6410 |
parser.add_argument('-v', nargs='?', const=1, type=int) |
| 6411 |
parser.add_argument('--spam', action='store_false') |
| 6412 |
parser.add_argument('badger') |
| 6413 |
|
| 6414 |
argv = ["B", "C", "--foo", "-v", "3", "4"] |
| 6415 |
args, extras = parser.parse_known_args(argv) |
| 6416 |
self.assertEqual(NS(v=3, spam=True, badger="B"), args) |
| 6417 |
self.assertEqual(["C", "--foo", "4"], extras) |
| 6418 |
|
| 6419 |
def test_zero_or_more_optional(self): |
| 6420 |
parser = argparse.ArgumentParser() |
| 6421 |
parser.add_argument('x', nargs='*', choices=('x', 'y')) |
| 6422 |
args = parser.parse_args([]) |
| 6423 |
self.assertEqual(NS(x=[]), args) |
| 6424 |
|
| 6425 |
|
| 6426 |
class TestDoubleDash(TestCase): |
| 6427 |
def test_single_argument_option(self): |
| 6428 |
parser = argparse.ArgumentParser(exit_on_error=False) |
| 6429 |
parser.add_argument('-f', '--foo') |
| 6430 |
parser.add_argument('bar', nargs='*') |
| 6431 |
|
| 6432 |
args = parser.parse_args(['--foo=--']) |
| 6433 |
self.assertEqual(NS(foo='--', bar=[]), args) |
| 6434 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6435 |
'argument -f/--foo: expected one argument', |
| 6436 |
parser.parse_args, ['--foo', '--']) |
| 6437 |
args = parser.parse_args(['-f--']) |
| 6438 |
self.assertEqual(NS(foo='--', bar=[]), args) |
| 6439 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6440 |
'argument -f/--foo: expected one argument', |
| 6441 |
parser.parse_args, ['-f', '--']) |
| 6442 |
args = parser.parse_args(['--foo', 'a', '--', 'b', 'c']) |
| 6443 |
self.assertEqual(NS(foo='a', bar=['b', 'c']), args) |
| 6444 |
args = parser.parse_args(['a', 'b', '--foo', 'c']) |
| 6445 |
self.assertEqual(NS(foo='c', bar=['a', 'b']), args) |
| 6446 |
args = parser.parse_args(['a', '--', 'b', '--foo', 'c']) |
| 6447 |
self.assertEqual(NS(foo=None, bar=['a', 'b', '--foo', 'c']), args) |
| 6448 |
args = parser.parse_args(['a', '--', 'b', '--', 'c', '--foo', 'd']) |
| 6449 |
self.assertEqual(NS(foo=None, bar=['a', 'b', '--', 'c', '--foo', 'd']), args) |
| 6450 |
|
| 6451 |
def test_multiple_argument_option(self): |
| 6452 |
parser = argparse.ArgumentParser(exit_on_error=False) |
| 6453 |
parser.add_argument('-f', '--foo', nargs='*') |
| 6454 |
parser.add_argument('bar', nargs='*') |
| 6455 |
|
| 6456 |
args = parser.parse_args(['--foo=--']) |
| 6457 |
self.assertEqual(NS(foo=['--'], bar=[]), args) |
| 6458 |
args = parser.parse_args(['--foo', '--']) |
| 6459 |
self.assertEqual(NS(foo=[], bar=[]), args) |
| 6460 |
args = parser.parse_args(['-f--']) |
| 6461 |
self.assertEqual(NS(foo=['--'], bar=[]), args) |
| 6462 |
args = parser.parse_args(['-f', '--']) |
| 6463 |
self.assertEqual(NS(foo=[], bar=[]), args) |
| 6464 |
args = parser.parse_args(['--foo', 'a', 'b', '--', 'c', 'd']) |
| 6465 |
self.assertEqual(NS(foo=['a', 'b'], bar=['c', 'd']), args) |
| 6466 |
args = parser.parse_args(['a', 'b', '--foo', 'c', 'd']) |
| 6467 |
self.assertEqual(NS(foo=['c', 'd'], bar=['a', 'b']), args) |
| 6468 |
args = parser.parse_args(['a', '--', 'b', '--foo', 'c', 'd']) |
| 6469 |
self.assertEqual(NS(foo=None, bar=['a', 'b', '--foo', 'c', 'd']), args) |
| 6470 |
args, argv = parser.parse_known_args(['a', 'b', '--foo', 'c', '--', 'd']) |
| 6471 |
self.assertEqual(NS(foo=['c'], bar=['a', 'b']), args) |
| 6472 |
self.assertEqual(argv, ['--', 'd']) |
| 6473 |
|
| 6474 |
def test_multiple_double_dashes(self): |
| 6475 |
parser = argparse.ArgumentParser(exit_on_error=False) |
| 6476 |
parser.add_argument('foo') |
| 6477 |
parser.add_argument('bar', nargs='*') |
| 6478 |
|
| 6479 |
args = parser.parse_args(['--', 'a', 'b', 'c']) |
| 6480 |
self.assertEqual(NS(foo='a', bar=['b', 'c']), args) |
| 6481 |
args = parser.parse_args(['a', '--', 'b', 'c']) |
| 6482 |
self.assertEqual(NS(foo='a', bar=['b', 'c']), args) |
| 6483 |
args = parser.parse_args(['a', 'b', '--', 'c']) |
| 6484 |
self.assertEqual(NS(foo='a', bar=['b', 'c']), args) |
| 6485 |
args = parser.parse_args(['a', '--', 'b', '--', 'c']) |
| 6486 |
self.assertEqual(NS(foo='a', bar=['b', '--', 'c']), args) |
| 6487 |
args = parser.parse_args(['--', '--', 'a', '--', 'b', 'c']) |
| 6488 |
self.assertEqual(NS(foo='--', bar=['a', '--', 'b', 'c']), args) |
| 6489 |
|
| 6490 |
def test_remainder(self): |
| 6491 |
parser = argparse.ArgumentParser(exit_on_error=False) |
| 6492 |
parser.add_argument('foo') |
| 6493 |
parser.add_argument('bar', nargs='...') |
| 6494 |
|
| 6495 |
args = parser.parse_args(['--', 'a', 'b', 'c']) |
| 6496 |
self.assertEqual(NS(foo='a', bar=['b', 'c']), args) |
| 6497 |
args = parser.parse_args(['a', '--', 'b', 'c']) |
| 6498 |
self.assertEqual(NS(foo='a', bar=['b', 'c']), args) |
| 6499 |
args = parser.parse_args(['a', 'b', '--', 'c']) |
| 6500 |
self.assertEqual(NS(foo='a', bar=['b', '--', 'c']), args) |
| 6501 |
args = parser.parse_args(['a', '--', 'b', '--', 'c']) |
| 6502 |
self.assertEqual(NS(foo='a', bar=['b', '--', 'c']), args) |
| 6503 |
|
| 6504 |
parser = argparse.ArgumentParser(exit_on_error=False) |
| 6505 |
parser.add_argument('--foo') |
| 6506 |
parser.add_argument('bar', nargs='...') |
| 6507 |
args = parser.parse_args(['--foo', 'a', '--', 'b', '--', 'c']) |
| 6508 |
self.assertEqual(NS(foo='a', bar=['--', 'b', '--', 'c']), args) |
| 6509 |
|
| 6510 |
def test_subparser(self): |
| 6511 |
parser = argparse.ArgumentParser(exit_on_error=False) |
| 6512 |
parser.add_argument('foo') |
| 6513 |
subparsers = parser.add_subparsers() |
| 6514 |
parser1 = subparsers.add_parser('run') |
| 6515 |
parser1.add_argument('-f') |
| 6516 |
parser1.add_argument('bar', nargs='*') |
| 6517 |
|
| 6518 |
args = parser.parse_args(['x', 'run', 'a', 'b', '-f', 'c']) |
| 6519 |
self.assertEqual(NS(foo='x', f='c', bar=['a', 'b']), args) |
| 6520 |
args = parser.parse_args(['x', 'run', 'a', 'b', '--', '-f', 'c']) |
| 6521 |
self.assertEqual(NS(foo='x', f=None, bar=['a', 'b', '-f', 'c']), args) |
| 6522 |
args = parser.parse_args(['x', 'run', 'a', '--', 'b', '-f', 'c']) |
| 6523 |
self.assertEqual(NS(foo='x', f=None, bar=['a', 'b', '-f', 'c']), args) |
| 6524 |
args = parser.parse_args(['x', 'run', '--', 'a', 'b', '-f', 'c']) |
| 6525 |
self.assertEqual(NS(foo='x', f=None, bar=['a', 'b', '-f', 'c']), args) |
| 6526 |
args = parser.parse_args(['x', '--', 'run', 'a', 'b', '-f', 'c']) |
| 6527 |
self.assertEqual(NS(foo='x', f='c', bar=['a', 'b']), args) |
| 6528 |
args = parser.parse_args(['--', 'x', 'run', 'a', 'b', '-f', 'c']) |
| 6529 |
self.assertEqual(NS(foo='x', f='c', bar=['a', 'b']), args) |
| 6530 |
args = parser.parse_args(['x', 'run', '--', 'a', '--', 'b']) |
| 6531 |
self.assertEqual(NS(foo='x', f=None, bar=['a', '--', 'b']), args) |
| 6532 |
args = parser.parse_args(['x', '--', 'run', '--', 'a', '--', 'b']) |
| 6533 |
self.assertEqual(NS(foo='x', f=None, bar=['a', '--', 'b']), args) |
| 6534 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6535 |
"invalid choice: '--'", |
| 6536 |
parser.parse_args, ['--', 'x', '--', 'run', 'a', 'b']) |
| 6537 |
|
| 6538 |
def test_subparser_after_multiple_argument_option(self): |
| 6539 |
parser = argparse.ArgumentParser(exit_on_error=False) |
| 6540 |
parser.add_argument('--foo', nargs='*') |
| 6541 |
subparsers = parser.add_subparsers() |
| 6542 |
parser1 = subparsers.add_parser('run') |
| 6543 |
parser1.add_argument('-f') |
| 6544 |
parser1.add_argument('bar', nargs='*') |
| 6545 |
|
| 6546 |
args = parser.parse_args(['--foo', 'x', 'y', '--', 'run', 'a', 'b', '-f', 'c']) |
| 6547 |
self.assertEqual(NS(foo=['x', 'y'], f='c', bar=['a', 'b']), args) |
| 6548 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6549 |
"invalid choice: '--'", |
| 6550 |
parser.parse_args, ['--foo', 'x', '--', '--', 'run', 'a', 'b']) |
| 6551 |
|
| 6552 |
|
| 6553 |
# =========================== |
| 6554 |
# parse_intermixed_args tests |
| 6555 |
# =========================== |
| 6556 |
|
| 6557 |
class TestIntermixedArgs(TestCase): |
| 6558 |
def test_basic(self): |
| 6559 |
# test parsing intermixed optionals and positionals |
| 6560 |
parser = argparse.ArgumentParser(prog='PROG') |
| 6561 |
parser.add_argument('--foo', dest='foo') |
| 6562 |
bar = parser.add_argument('--bar', dest='bar', required=True) |
| 6563 |
parser.add_argument('cmd') |
| 6564 |
parser.add_argument('rest', nargs='*', type=int) |
| 6565 |
argv = 'cmd --foo x 1 --bar y 2 3'.split() |
| 6566 |
args = parser.parse_intermixed_args(argv) |
| 6567 |
# rest gets [1,2,3] despite the foo and bar strings |
| 6568 |
self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args) |
| 6569 |
|
| 6570 |
args, extras = parser.parse_known_args(argv) |
| 6571 |
# cannot parse the '1,2,3' |
| 6572 |
self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1]), args) |
| 6573 |
self.assertEqual(["2", "3"], extras) |
| 6574 |
args, extras = parser.parse_known_intermixed_args(argv) |
| 6575 |
self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args) |
| 6576 |
self.assertEqual([], extras) |
| 6577 |
|
| 6578 |
# unknown optionals go into extras |
| 6579 |
argv = 'cmd --foo x --error 1 2 --bar y 3'.split() |
| 6580 |
args, extras = parser.parse_known_intermixed_args(argv) |
| 6581 |
self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args) |
| 6582 |
self.assertEqual(['--error'], extras) |
| 6583 |
argv = 'cmd --foo x 1 --error 2 --bar y 3'.split() |
| 6584 |
args, extras = parser.parse_known_intermixed_args(argv) |
| 6585 |
self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args) |
| 6586 |
self.assertEqual(['--error'], extras) |
| 6587 |
argv = 'cmd --foo x 1 2 --error --bar y 3'.split() |
| 6588 |
args, extras = parser.parse_known_intermixed_args(argv) |
| 6589 |
self.assertEqual(NS(bar='y', cmd='cmd', foo='x', rest=[1, 2, 3]), args) |
| 6590 |
self.assertEqual(['--error'], extras) |
| 6591 |
|
| 6592 |
# restores attributes that were temporarily changed |
| 6593 |
self.assertIsNone(parser.usage) |
| 6594 |
self.assertEqual(bar.required, True) |
| 6595 |
|
| 6596 |
def test_remainder(self): |
| 6597 |
# Intermixed and remainder are incompatible |
| 6598 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 6599 |
parser.add_argument('-z') |
| 6600 |
parser.add_argument('x') |
| 6601 |
parser.add_argument('y', nargs='...') |
| 6602 |
argv = 'X A B -z Z'.split() |
| 6603 |
# intermixed fails with '...' (also 'A...') |
| 6604 |
# self.assertRaises(TypeError, parser.parse_intermixed_args, argv) |
| 6605 |
with self.assertRaises(TypeError) as cm: |
| 6606 |
parser.parse_intermixed_args(argv) |
| 6607 |
self.assertRegex(str(cm.exception), r'\.\.\.') |
| 6608 |
|
| 6609 |
def test_required_exclusive(self): |
| 6610 |
# required mutually exclusive group; intermixed works fine |
| 6611 |
parser = argparse.ArgumentParser(prog='PROG', exit_on_error=False) |
| 6612 |
group = parser.add_mutually_exclusive_group(required=True) |
| 6613 |
group.add_argument('--foo', action='store_true', help='FOO') |
| 6614 |
group.add_argument('--spam', help='SPAM') |
| 6615 |
parser.add_argument('badger', nargs='*', default='X', help='BADGER') |
| 6616 |
args = parser.parse_intermixed_args('--foo 1 2'.split()) |
| 6617 |
self.assertEqual(NS(badger=['1', '2'], foo=True, spam=None), args) |
| 6618 |
args = parser.parse_intermixed_args('1 --foo 2'.split()) |
| 6619 |
self.assertEqual(NS(badger=['1', '2'], foo=True, spam=None), args) |
| 6620 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6621 |
'one of the arguments --foo --spam is required', |
| 6622 |
parser.parse_intermixed_args, '1 2'.split()) |
| 6623 |
self.assertEqual(group.required, True) |
| 6624 |
|
| 6625 |
def test_required_exclusive_with_positional(self): |
| 6626 |
# required mutually exclusive group with positional argument |
| 6627 |
parser = argparse.ArgumentParser(prog='PROG', exit_on_error=False) |
| 6628 |
group = parser.add_mutually_exclusive_group(required=True) |
| 6629 |
group.add_argument('--foo', action='store_true', help='FOO') |
| 6630 |
group.add_argument('--spam', help='SPAM') |
| 6631 |
group.add_argument('badger', nargs='*', default='X', help='BADGER') |
| 6632 |
args = parser.parse_intermixed_args(['--foo']) |
| 6633 |
self.assertEqual(NS(foo=True, spam=None, badger='X'), args) |
| 6634 |
args = parser.parse_intermixed_args(['a', 'b']) |
| 6635 |
self.assertEqual(NS(foo=False, spam=None, badger=['a', 'b']), args) |
| 6636 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6637 |
'one of the arguments --foo --spam badger is required', |
| 6638 |
parser.parse_intermixed_args, []) |
| 6639 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6640 |
'argument badger: not allowed with argument --foo', |
| 6641 |
parser.parse_intermixed_args, ['--foo', 'a', 'b']) |
| 6642 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6643 |
'argument badger: not allowed with argument --foo', |
| 6644 |
parser.parse_intermixed_args, ['a', '--foo', 'b']) |
| 6645 |
self.assertEqual(group.required, True) |
| 6646 |
|
| 6647 |
def test_invalid_args(self): |
| 6648 |
parser = ErrorRaisingArgumentParser(prog='PROG') |
| 6649 |
self.assertRaises(ArgumentParserError, parser.parse_intermixed_args, ['a']) |
| 6650 |
|
| 6651 |
|
| 6652 |
class TestIntermixedMessageContentError(TestCase): |
| 6653 |
# case where Intermixed gives different error message |
| 6654 |
# error is raised by 1st parsing step |
| 6655 |
def test_missing_argument_name_in_message(self): |
| 6656 |
parser = ErrorRaisingArgumentParser(prog='PROG', usage='') |
| 6657 |
parser.add_argument('req_pos', type=str) |
| 6658 |
parser.add_argument('-req_opt', type=int, required=True) |
| 6659 |
|
| 6660 |
with self.assertRaises(ArgumentParserError) as cm: |
| 6661 |
parser.parse_args([]) |
| 6662 |
msg = str(cm.exception) |
| 6663 |
self.assertRegex(msg, 'req_pos') |
| 6664 |
self.assertRegex(msg, 'req_opt') |
| 6665 |
|
| 6666 |
with self.assertRaises(ArgumentParserError) as cm: |
| 6667 |
parser.parse_intermixed_args([]) |
| 6668 |
msg = str(cm.exception) |
| 6669 |
self.assertRegex(msg, 'req_pos') |
| 6670 |
self.assertRegex(msg, 'req_opt') |
| 6671 |
|
| 6672 |
# ========================== |
| 6673 |
# add_argument metavar tests |
| 6674 |
# ========================== |
| 6675 |
|
| 6676 |
class TestAddArgumentMetavar(TestCase): |
| 6677 |
|
| 6678 |
EXPECTED_MESSAGE = "length of metavar tuple does not match nargs" |
| 6679 |
|
| 6680 |
def do_test_no_exception(self, nargs, metavar): |
| 6681 |
parser = argparse.ArgumentParser() |
| 6682 |
parser.add_argument("--foo", nargs=nargs, metavar=metavar) |
| 6683 |
|
| 6684 |
def do_test_exception(self, nargs, metavar): |
| 6685 |
parser = argparse.ArgumentParser() |
| 6686 |
with self.assertRaises(ValueError) as cm: |
| 6687 |
parser.add_argument("--foo", nargs=nargs, metavar=metavar) |
| 6688 |
self.assertEqual(cm.exception.args[0], self.EXPECTED_MESSAGE) |
| 6689 |
|
| 6690 |
# Unit tests for different values of metavar when nargs=None |
| 6691 |
|
| 6692 |
def test_nargs_None_metavar_string(self): |
| 6693 |
self.do_test_no_exception(nargs=None, metavar="1") |
| 6694 |
|
| 6695 |
def test_nargs_None_metavar_length0(self): |
| 6696 |
self.do_test_exception(nargs=None, metavar=tuple()) |
| 6697 |
|
| 6698 |
def test_nargs_None_metavar_length1(self): |
| 6699 |
self.do_test_no_exception(nargs=None, metavar=("1",)) |
| 6700 |
|
| 6701 |
def test_nargs_None_metavar_length2(self): |
| 6702 |
self.do_test_exception(nargs=None, metavar=("1", "2")) |
| 6703 |
|
| 6704 |
def test_nargs_None_metavar_length3(self): |
| 6705 |
self.do_test_exception(nargs=None, metavar=("1", "2", "3")) |
| 6706 |
|
| 6707 |
# Unit tests for different values of metavar when nargs=? |
| 6708 |
|
| 6709 |
def test_nargs_optional_metavar_string(self): |
| 6710 |
self.do_test_no_exception(nargs="?", metavar="1") |
| 6711 |
|
| 6712 |
def test_nargs_optional_metavar_length0(self): |
| 6713 |
self.do_test_exception(nargs="?", metavar=tuple()) |
| 6714 |
|
| 6715 |
def test_nargs_optional_metavar_length1(self): |
| 6716 |
self.do_test_no_exception(nargs="?", metavar=("1",)) |
| 6717 |
|
| 6718 |
def test_nargs_optional_metavar_length2(self): |
| 6719 |
self.do_test_exception(nargs="?", metavar=("1", "2")) |
| 6720 |
|
| 6721 |
def test_nargs_optional_metavar_length3(self): |
| 6722 |
self.do_test_exception(nargs="?", metavar=("1", "2", "3")) |
| 6723 |
|
| 6724 |
# Unit tests for different values of metavar when nargs=* |
| 6725 |
|
| 6726 |
def test_nargs_zeroormore_metavar_string(self): |
| 6727 |
self.do_test_no_exception(nargs="*", metavar="1") |
| 6728 |
|
| 6729 |
def test_nargs_zeroormore_metavar_length0(self): |
| 6730 |
self.do_test_exception(nargs="*", metavar=tuple()) |
| 6731 |
|
| 6732 |
def test_nargs_zeroormore_metavar_length1(self): |
| 6733 |
self.do_test_no_exception(nargs="*", metavar=("1",)) |
| 6734 |
|
| 6735 |
def test_nargs_zeroormore_metavar_length2(self): |
| 6736 |
self.do_test_no_exception(nargs="*", metavar=("1", "2")) |
| 6737 |
|
| 6738 |
def test_nargs_zeroormore_metavar_length3(self): |
| 6739 |
self.do_test_exception(nargs="*", metavar=("1", "2", "3")) |
| 6740 |
|
| 6741 |
# Unit tests for different values of metavar when nargs=+ |
| 6742 |
|
| 6743 |
def test_nargs_oneormore_metavar_string(self): |
| 6744 |
self.do_test_no_exception(nargs="+", metavar="1") |
| 6745 |
|
| 6746 |
def test_nargs_oneormore_metavar_length0(self): |
| 6747 |
self.do_test_exception(nargs="+", metavar=tuple()) |
| 6748 |
|
| 6749 |
def test_nargs_oneormore_metavar_length1(self): |
| 6750 |
self.do_test_exception(nargs="+", metavar=("1",)) |
| 6751 |
|
| 6752 |
def test_nargs_oneormore_metavar_length2(self): |
| 6753 |
self.do_test_no_exception(nargs="+", metavar=("1", "2")) |
| 6754 |
|
| 6755 |
def test_nargs_oneormore_metavar_length3(self): |
| 6756 |
self.do_test_exception(nargs="+", metavar=("1", "2", "3")) |
| 6757 |
|
| 6758 |
# Unit tests for different values of metavar when nargs=... |
| 6759 |
|
| 6760 |
def test_nargs_remainder_metavar_string(self): |
| 6761 |
self.do_test_no_exception(nargs="...", metavar="1") |
| 6762 |
|
| 6763 |
def test_nargs_remainder_metavar_length0(self): |
| 6764 |
self.do_test_no_exception(nargs="...", metavar=tuple()) |
| 6765 |
|
| 6766 |
def test_nargs_remainder_metavar_length1(self): |
| 6767 |
self.do_test_no_exception(nargs="...", metavar=("1",)) |
| 6768 |
|
| 6769 |
def test_nargs_remainder_metavar_length2(self): |
| 6770 |
self.do_test_no_exception(nargs="...", metavar=("1", "2")) |
| 6771 |
|
| 6772 |
def test_nargs_remainder_metavar_length3(self): |
| 6773 |
self.do_test_no_exception(nargs="...", metavar=("1", "2", "3")) |
| 6774 |
|
| 6775 |
# Unit tests for different values of metavar when nargs=A... |
| 6776 |
|
| 6777 |
def test_nargs_parser_metavar_string(self): |
| 6778 |
self.do_test_no_exception(nargs="A...", metavar="1") |
| 6779 |
|
| 6780 |
def test_nargs_parser_metavar_length0(self): |
| 6781 |
self.do_test_exception(nargs="A...", metavar=tuple()) |
| 6782 |
|
| 6783 |
def test_nargs_parser_metavar_length1(self): |
| 6784 |
self.do_test_no_exception(nargs="A...", metavar=("1",)) |
| 6785 |
|
| 6786 |
def test_nargs_parser_metavar_length2(self): |
| 6787 |
self.do_test_exception(nargs="A...", metavar=("1", "2")) |
| 6788 |
|
| 6789 |
def test_nargs_parser_metavar_length3(self): |
| 6790 |
self.do_test_exception(nargs="A...", metavar=("1", "2", "3")) |
| 6791 |
|
| 6792 |
# Unit tests for different values of metavar when nargs=1 |
| 6793 |
|
| 6794 |
def test_nargs_1_metavar_string(self): |
| 6795 |
self.do_test_no_exception(nargs=1, metavar="1") |
| 6796 |
|
| 6797 |
def test_nargs_1_metavar_length0(self): |
| 6798 |
self.do_test_exception(nargs=1, metavar=tuple()) |
| 6799 |
|
| 6800 |
def test_nargs_1_metavar_length1(self): |
| 6801 |
self.do_test_no_exception(nargs=1, metavar=("1",)) |
| 6802 |
|
| 6803 |
def test_nargs_1_metavar_length2(self): |
| 6804 |
self.do_test_exception(nargs=1, metavar=("1", "2")) |
| 6805 |
|
| 6806 |
def test_nargs_1_metavar_length3(self): |
| 6807 |
self.do_test_exception(nargs=1, metavar=("1", "2", "3")) |
| 6808 |
|
| 6809 |
# Unit tests for different values of metavar when nargs=2 |
| 6810 |
|
| 6811 |
def test_nargs_2_metavar_string(self): |
| 6812 |
self.do_test_no_exception(nargs=2, metavar="1") |
| 6813 |
|
| 6814 |
def test_nargs_2_metavar_length0(self): |
| 6815 |
self.do_test_exception(nargs=2, metavar=tuple()) |
| 6816 |
|
| 6817 |
def test_nargs_2_metavar_length1(self): |
| 6818 |
self.do_test_exception(nargs=2, metavar=("1",)) |
| 6819 |
|
| 6820 |
def test_nargs_2_metavar_length2(self): |
| 6821 |
self.do_test_no_exception(nargs=2, metavar=("1", "2")) |
| 6822 |
|
| 6823 |
def test_nargs_2_metavar_length3(self): |
| 6824 |
self.do_test_exception(nargs=2, metavar=("1", "2", "3")) |
| 6825 |
|
| 6826 |
# Unit tests for different values of metavar when nargs=3 |
| 6827 |
|
| 6828 |
def test_nargs_3_metavar_string(self): |
| 6829 |
self.do_test_no_exception(nargs=3, metavar="1") |
| 6830 |
|
| 6831 |
def test_nargs_3_metavar_length0(self): |
| 6832 |
self.do_test_exception(nargs=3, metavar=tuple()) |
| 6833 |
|
| 6834 |
def test_nargs_3_metavar_length1(self): |
| 6835 |
self.do_test_exception(nargs=3, metavar=("1",)) |
| 6836 |
|
| 6837 |
def test_nargs_3_metavar_length2(self): |
| 6838 |
self.do_test_exception(nargs=3, metavar=("1", "2")) |
| 6839 |
|
| 6840 |
def test_nargs_3_metavar_length3(self): |
| 6841 |
self.do_test_no_exception(nargs=3, metavar=("1", "2", "3")) |
| 6842 |
|
| 6843 |
|
| 6844 |
class TestInvalidNargs(TestCase): |
| 6845 |
|
| 6846 |
EXPECTED_INVALID_MESSAGE = "invalid nargs value" |
| 6847 |
EXPECTED_RANGE_MESSAGE = ("nargs for store actions must be != 0; if you " |
| 6848 |
"have nothing to store, actions such as store " |
| 6849 |
"true or store const may be more appropriate") |
| 6850 |
|
| 6851 |
def do_test_range_exception(self, nargs): |
| 6852 |
parser = argparse.ArgumentParser() |
| 6853 |
with self.assertRaises(ValueError) as cm: |
| 6854 |
parser.add_argument("--foo", nargs=nargs) |
| 6855 |
self.assertEqual(cm.exception.args[0], self.EXPECTED_RANGE_MESSAGE) |
| 6856 |
|
| 6857 |
def do_test_invalid_exception(self, nargs): |
| 6858 |
parser = argparse.ArgumentParser() |
| 6859 |
with self.assertRaises(ValueError) as cm: |
| 6860 |
parser.add_argument("--foo", nargs=nargs) |
| 6861 |
self.assertEqual(cm.exception.args[0], self.EXPECTED_INVALID_MESSAGE) |
| 6862 |
|
| 6863 |
# Unit tests for different values of nargs |
| 6864 |
|
| 6865 |
def test_nargs_alphabetic(self): |
| 6866 |
self.do_test_invalid_exception(nargs='a') |
| 6867 |
self.do_test_invalid_exception(nargs="abcd") |
| 6868 |
|
| 6869 |
def test_nargs_zero(self): |
| 6870 |
self.do_test_range_exception(nargs=0) |
| 6871 |
|
| 6872 |
# ============================ |
| 6873 |
# from argparse import * tests |
| 6874 |
# ============================ |
| 6875 |
|
| 6876 |
class TestImportStar(TestCase): |
| 6877 |
|
| 6878 |
def test(self): |
| 6879 |
for name in argparse.__all__: |
| 6880 |
self.assertHasAttr(argparse, name) |
| 6881 |
|
| 6882 |
def test_all_exports_everything_but_modules(self): |
| 6883 |
items = [ |
| 6884 |
name |
| 6885 |
for name, value in vars(argparse).items() |
| 6886 |
if not (name.startswith("_") or name == 'ngettext') |
| 6887 |
if not inspect.ismodule(value) |
| 6888 |
] |
| 6889 |
self.assertEqual(sorted(items), sorted(argparse.__all__)) |
| 6890 |
|
| 6891 |
|
| 6892 |
class TestWrappingMetavar(TestCase): |
| 6893 |
|
| 6894 |
def setUp(self): |
| 6895 |
super().setUp() |
| 6896 |
self.parser = ErrorRaisingArgumentParser( |
| 6897 |
'this_is_spammy_prog_with_a_long_name_sorry_about_the_name' |
| 6898 |
) |
| 6899 |
# this metavar was triggering library assertion errors due to usage |
| 6900 |
# message formatting incorrectly splitting on the ] chars within |
| 6901 |
metavar = '<http[s]://example:1234>' |
| 6902 |
self.parser.add_argument('--proxy', metavar=metavar) |
| 6903 |
|
| 6904 |
@force_not_colorized |
| 6905 |
def test_help_with_metavar(self): |
| 6906 |
help_text = self.parser.format_help() |
| 6907 |
self.assertEqual(help_text, textwrap.dedent('''\ |
| 6908 |
usage: this_is_spammy_prog_with_a_long_name_sorry_about_the_name |
| 6909 |
[-h] [--proxy <http[s]://example:1234>] |
| 6910 |
|
| 6911 |
options: |
| 6912 |
-h, --help show this help message and exit |
| 6913 |
--proxy <http[s]://example:1234> |
| 6914 |
''')) |
| 6915 |
|
| 6916 |
|
| 6917 |
class TestExitOnError(TestCase): |
| 6918 |
|
| 6919 |
def setUp(self): |
| 6920 |
self.parser = argparse.ArgumentParser(exit_on_error=False, |
| 6921 |
fromfile_prefix_chars='@') |
| 6922 |
self.parser.add_argument('--integers', metavar='N', type=int) |
| 6923 |
|
| 6924 |
def test_exit_on_error_with_good_args(self): |
| 6925 |
ns = self.parser.parse_args('--integers 4'.split()) |
| 6926 |
self.assertEqual(ns, argparse.Namespace(integers=4)) |
| 6927 |
|
| 6928 |
def test_exit_on_error_with_bad_args(self): |
| 6929 |
with self.assertRaises(argparse.ArgumentError): |
| 6930 |
self.parser.parse_args('--integers a'.split()) |
| 6931 |
|
| 6932 |
def test_unrecognized_args(self): |
| 6933 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6934 |
'unrecognized arguments: --foo bar', |
| 6935 |
self.parser.parse_args, '--foo bar'.split()) |
| 6936 |
|
| 6937 |
def test_unrecognized_intermixed_args(self): |
| 6938 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6939 |
'unrecognized arguments: --foo bar', |
| 6940 |
self.parser.parse_intermixed_args, '--foo bar'.split()) |
| 6941 |
|
| 6942 |
def test_required_args(self): |
| 6943 |
self.parser.add_argument('bar') |
| 6944 |
self.parser.add_argument('baz') |
| 6945 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6946 |
'the following arguments are required: bar, baz$', |
| 6947 |
self.parser.parse_args, []) |
| 6948 |
|
| 6949 |
def test_required_args_with_metavar(self): |
| 6950 |
self.parser.add_argument('bar') |
| 6951 |
self.parser.add_argument('baz', metavar='BaZ') |
| 6952 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6953 |
'the following arguments are required: bar, BaZ$', |
| 6954 |
self.parser.parse_args, []) |
| 6955 |
|
| 6956 |
def test_required_args_n(self): |
| 6957 |
self.parser.add_argument('bar') |
| 6958 |
self.parser.add_argument('baz', nargs=3) |
| 6959 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6960 |
'the following arguments are required: bar, baz$', |
| 6961 |
self.parser.parse_args, []) |
| 6962 |
|
| 6963 |
def test_required_args_n_with_metavar(self): |
| 6964 |
self.parser.add_argument('bar') |
| 6965 |
self.parser.add_argument('baz', nargs=3, metavar=('B', 'A', 'Z')) |
| 6966 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6967 |
'the following arguments are required: bar, B, A, Z$', |
| 6968 |
self.parser.parse_args, []) |
| 6969 |
|
| 6970 |
def test_required_args_optional(self): |
| 6971 |
self.parser.add_argument('bar') |
| 6972 |
self.parser.add_argument('baz', nargs='?') |
| 6973 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6974 |
'the following arguments are required: bar$', |
| 6975 |
self.parser.parse_args, []) |
| 6976 |
|
| 6977 |
def test_required_args_zero_or_more(self): |
| 6978 |
self.parser.add_argument('bar') |
| 6979 |
self.parser.add_argument('baz', nargs='*') |
| 6980 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6981 |
'the following arguments are required: bar$', |
| 6982 |
self.parser.parse_args, []) |
| 6983 |
|
| 6984 |
def test_required_args_one_or_more(self): |
| 6985 |
self.parser.add_argument('bar') |
| 6986 |
self.parser.add_argument('baz', nargs='+') |
| 6987 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6988 |
'the following arguments are required: bar, baz$', |
| 6989 |
self.parser.parse_args, []) |
| 6990 |
|
| 6991 |
def test_required_args_one_or_more_with_metavar(self): |
| 6992 |
self.parser.add_argument('bar') |
| 6993 |
self.parser.add_argument('baz', nargs='+', metavar=('BaZ1', 'BaZ2')) |
| 6994 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 6995 |
r'the following arguments are required: bar, BaZ1\[, BaZ2]$', |
| 6996 |
self.parser.parse_args, []) |
| 6997 |
|
| 6998 |
def test_required_args_remainder(self): |
| 6999 |
self.parser.add_argument('bar') |
| 7000 |
self.parser.add_argument('baz', nargs='...') |
| 7001 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7002 |
'the following arguments are required: bar$', |
| 7003 |
self.parser.parse_args, []) |
| 7004 |
|
| 7005 |
def test_required_mutually_exclusive_args(self): |
| 7006 |
group = self.parser.add_mutually_exclusive_group(required=True) |
| 7007 |
group.add_argument('--bar') |
| 7008 |
group.add_argument('--baz') |
| 7009 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7010 |
'one of the arguments --bar --baz is required', |
| 7011 |
self.parser.parse_args, []) |
| 7012 |
|
| 7013 |
def test_conflicting_mutually_exclusive_args_optional_with_metavar(self): |
| 7014 |
group = self.parser.add_mutually_exclusive_group() |
| 7015 |
group.add_argument('--bar') |
| 7016 |
group.add_argument('baz', nargs='?', metavar='BaZ') |
| 7017 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7018 |
'argument BaZ: not allowed with argument --bar$', |
| 7019 |
self.parser.parse_args, ['--bar', 'a', 'b']) |
| 7020 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7021 |
'argument --bar: not allowed with argument BaZ$', |
| 7022 |
self.parser.parse_args, ['a', '--bar', 'b']) |
| 7023 |
|
| 7024 |
def test_conflicting_mutually_exclusive_args_zero_or_more_with_metavar1(self): |
| 7025 |
group = self.parser.add_mutually_exclusive_group() |
| 7026 |
group.add_argument('--bar') |
| 7027 |
group.add_argument('baz', nargs='*', metavar=('BAZ1',)) |
| 7028 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7029 |
'argument BAZ1: not allowed with argument --bar$', |
| 7030 |
self.parser.parse_args, ['--bar', 'a', 'b']) |
| 7031 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7032 |
'argument --bar: not allowed with argument BAZ1$', |
| 7033 |
self.parser.parse_args, ['a', '--bar', 'b']) |
| 7034 |
|
| 7035 |
def test_conflicting_mutually_exclusive_args_zero_or_more_with_metavar2(self): |
| 7036 |
group = self.parser.add_mutually_exclusive_group() |
| 7037 |
group.add_argument('--bar') |
| 7038 |
group.add_argument('baz', nargs='*', metavar=('BAZ1', 'BAZ2')) |
| 7039 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7040 |
r'argument BAZ1\[, BAZ2]: not allowed with argument --bar$', |
| 7041 |
self.parser.parse_args, ['--bar', 'a', 'b']) |
| 7042 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7043 |
r'argument --bar: not allowed with argument BAZ1\[, BAZ2]$', |
| 7044 |
self.parser.parse_args, ['a', '--bar', 'b']) |
| 7045 |
|
| 7046 |
def test_ambiguous_option(self): |
| 7047 |
self.parser.add_argument('--foobaz') |
| 7048 |
self.parser.add_argument('--fooble', action='store_true') |
| 7049 |
self.parser.add_argument('--foogle') |
| 7050 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7051 |
"ambiguous option: --foob could match --foobaz, --fooble", |
| 7052 |
self.parser.parse_args, ['--foob']) |
| 7053 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7054 |
"ambiguous option: --foob=1 could match --foobaz, --fooble$", |
| 7055 |
self.parser.parse_args, ['--foob=1']) |
| 7056 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7057 |
"ambiguous option: --foob could match --foobaz, --fooble$", |
| 7058 |
self.parser.parse_args, ['--foob', '1', '--foogle', '2']) |
| 7059 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7060 |
"ambiguous option: --foob=1 could match --foobaz, --fooble$", |
| 7061 |
self.parser.parse_args, ['--foob=1', '--foogle', '2']) |
| 7062 |
|
| 7063 |
def test_os_error(self): |
| 7064 |
self.parser.add_argument('file') |
| 7065 |
self.assertRaisesRegex(argparse.ArgumentError, |
| 7066 |
"No such file or directory: 'no-such-file'", |
| 7067 |
self.parser.parse_args, ['@no-such-file']) |
| 7068 |
|
| 7069 |
|
| 7070 |
@force_not_colorized_test_class |
| 7071 |
class TestProgName(TestCase): |
| 7072 |
source = textwrap.dedent('''\ |
| 7073 |
import argparse |
| 7074 |
parser = argparse.ArgumentParser() |
| 7075 |
parser.parse_args() |
| 7076 |
''') |
| 7077 |
|
| 7078 |
def setUp(self): |
| 7079 |
self.dirname = 'package' + os_helper.FS_NONASCII |
| 7080 |
self.addCleanup(os_helper.rmtree, self.dirname) |
| 7081 |
os.mkdir(self.dirname) |
| 7082 |
|
| 7083 |
def make_script(self, dirname, basename, *, compiled=False): |
| 7084 |
script_name = script_helper.make_script(dirname, basename, self.source) |
| 7085 |
if not compiled: |
| 7086 |
return script_name |
| 7087 |
py_compile.compile(script_name, doraise=True) |
| 7088 |
os.remove(script_name) |
| 7089 |
pyc_file = import_helper.make_legacy_pyc(script_name) |
| 7090 |
return pyc_file |
| 7091 |
|
| 7092 |
def make_zip_script(self, script_name, name_in_zip=None): |
| 7093 |
zip_name, _ = script_helper.make_zip_script(self.dirname, 'test_zip', |
| 7094 |
script_name, name_in_zip) |
| 7095 |
return zip_name |
| 7096 |
|
| 7097 |
def check_usage(self, expected, *args, **kwargs): |
| 7098 |
res = script_helper.assert_python_ok('-Xutf8', *args, '-h', **kwargs) |
| 7099 |
self.assertEqual(os.fsdecode(res.out.splitlines()[0]), |
| 7100 |
f'usage: {expected} [-h]') |
| 7101 |
|
| 7102 |
def test_script(self, compiled=False): |
| 7103 |
basename = os_helper.TESTFN |
| 7104 |
script_name = self.make_script(self.dirname, basename, compiled=compiled) |
| 7105 |
self.check_usage(os.path.basename(script_name), script_name, '-h') |
| 7106 |
|
| 7107 |
def test_script_compiled(self): |
| 7108 |
self.test_script(compiled=True) |
| 7109 |
|
| 7110 |
def test_directory(self, compiled=False): |
| 7111 |
dirname = os.path.join(self.dirname, os_helper.TESTFN) |
| 7112 |
os.mkdir(dirname) |
| 7113 |
self.make_script(dirname, '__main__', compiled=compiled) |
| 7114 |
self.check_usage(f'{py} {dirname}', dirname) |
| 7115 |
dirname2 = os.path.join(os.curdir, dirname) |
| 7116 |
self.check_usage(f'{py} {dirname2}', dirname2) |
| 7117 |
|
| 7118 |
def test_directory_compiled(self): |
| 7119 |
self.test_directory(compiled=True) |
| 7120 |
|
| 7121 |
def test_module(self, compiled=False): |
| 7122 |
basename = 'module' + os_helper.FS_NONASCII |
| 7123 |
modulename = f'{self.dirname}.{basename}' |
| 7124 |
self.make_script(self.dirname, basename, compiled=compiled) |
| 7125 |
self.check_usage(f'{py} -m {modulename}', |
| 7126 |
'-m', modulename, PYTHONPATH=os.curdir) |
| 7127 |
|
| 7128 |
def test_module_compiled(self): |
| 7129 |
self.test_module(compiled=True) |
| 7130 |
|
| 7131 |
def test_package(self, compiled=False): |
| 7132 |
basename = 'subpackage' + os_helper.FS_NONASCII |
| 7133 |
packagename = f'{self.dirname}.{basename}' |
| 7134 |
subdirname = os.path.join(self.dirname, basename) |
| 7135 |
os.mkdir(subdirname) |
| 7136 |
self.make_script(subdirname, '__main__', compiled=compiled) |
| 7137 |
self.check_usage(f'{py} -m {packagename}', |
| 7138 |
'-m', packagename, PYTHONPATH=os.curdir) |
| 7139 |
self.check_usage(f'{py} -m {packagename}', |
| 7140 |
'-m', packagename + '.__main__', PYTHONPATH=os.curdir) |
| 7141 |
|
| 7142 |
def test_package_compiled(self): |
| 7143 |
self.test_package(compiled=True) |
| 7144 |
|
| 7145 |
def test_zipfile(self, compiled=False): |
| 7146 |
script_name = self.make_script(self.dirname, '__main__', compiled=compiled) |
| 7147 |
zip_name = self.make_zip_script(script_name) |
| 7148 |
self.check_usage(f'{py} {zip_name}', zip_name) |
| 7149 |
|
| 7150 |
def test_zipfile_compiled(self): |
| 7151 |
self.test_zipfile(compiled=True) |
| 7152 |
|
| 7153 |
def test_directory_in_zipfile(self, compiled=False): |
| 7154 |
script_name = self.make_script(self.dirname, '__main__', compiled=compiled) |
| 7155 |
name_in_zip = 'package/subpackage/__main__' + ('.py', '.pyc')[compiled] |
| 7156 |
zip_name = self.make_zip_script(script_name, name_in_zip) |
| 7157 |
dirname = os.path.join(zip_name, 'package', 'subpackage') |
| 7158 |
self.check_usage(f'{py} {dirname}', dirname) |
| 7159 |
|
| 7160 |
def test_directory_in_zipfile_compiled(self): |
| 7161 |
self.test_directory_in_zipfile(compiled=True) |
| 7162 |
|
| 7163 |
# ================= |
| 7164 |
# Translation tests |
| 7165 |
# ================= |
| 7166 |
|
| 7167 |
class TestTranslations(TestTranslationsBase): |
| 7168 |
|
| 7169 |
def test_translations(self): |
| 7170 |
self.assertMsgidsEqual(argparse) |
| 7171 |
|
| 7172 |
|
| 7173 |
# =========== |
| 7174 |
# Color tests |
| 7175 |
# =========== |
| 7176 |
|
| 7177 |
|
| 7178 |
class TestColorized(TestCase): |
| 7179 |
maxDiff = None |
| 7180 |
|
| 7181 |
def setUp(self): |
| 7182 |
super().setUp() |
| 7183 |
# Ensure color even if ran with NO_COLOR=1 |
| 7184 |
self.enterContext(swap_attr(_colorize, 'can_colorize', |
| 7185 |
lambda *args, **kwargs: True)) |
| 7186 |
self.theme = _colorize.get_theme(force_color=True).argparse |
| 7187 |
|
| 7188 |
def test_argparse_color(self): |
| 7189 |
# Arrange: create a parser with a bit of everything |
| 7190 |
parser = argparse.ArgumentParser( |
| 7191 |
color=True, |
| 7192 |
description="Colorful help", |
| 7193 |
formatter_class=argparse.ArgumentDefaultsHelpFormatter, |
| 7194 |
prefix_chars="-+", |
| 7195 |
prog="PROG", |
| 7196 |
) |
| 7197 |
group = parser.add_mutually_exclusive_group() |
| 7198 |
group.add_argument( |
| 7199 |
"-v", "--verbose", action="store_true", help="more spam" |
| 7200 |
) |
| 7201 |
group.add_argument( |
| 7202 |
"-q", "--quiet", action="store_true", help="less spam" |
| 7203 |
) |
| 7204 |
parser.add_argument("x", type=int, help="the base") |
| 7205 |
parser.add_argument( |
| 7206 |
"y", type=int, help="the exponent", deprecated=True |
| 7207 |
) |
| 7208 |
parser.add_argument( |
| 7209 |
"this_indeed_is_a_very_long_action_name", |
| 7210 |
type=int, |
| 7211 |
help="the exponent", |
| 7212 |
) |
| 7213 |
parser.add_argument( |
| 7214 |
"-o", "--optional1", action="store_true", deprecated=True |
| 7215 |
) |
| 7216 |
parser.add_argument("--optional2", help="pick one") |
| 7217 |
parser.add_argument("--optional3", choices=("X", "Y", "Z")) |
| 7218 |
parser.add_argument( |
| 7219 |
"--optional4", choices=("X", "Y", "Z"), help="pick one" |
| 7220 |
) |
| 7221 |
parser.add_argument( |
| 7222 |
"--optional5", choices=("X", "Y", "Z"), help="pick one" |
| 7223 |
) |
| 7224 |
parser.add_argument( |
| 7225 |
"--optional6", choices=("X", "Y", "Z"), help="pick one" |
| 7226 |
) |
| 7227 |
parser.add_argument( |
| 7228 |
"-p", |
| 7229 |
"--optional7", |
| 7230 |
choices=("Aaaaa", "Bbbbb", "Ccccc", "Ddddd"), |
| 7231 |
help="pick one", |
| 7232 |
) |
| 7233 |
|
| 7234 |
parser.add_argument("+f") |
| 7235 |
parser.add_argument("++bar") |
| 7236 |
parser.add_argument("-+baz") |
| 7237 |
parser.add_argument("-c", "--count") |
| 7238 |
|
| 7239 |
subparsers = parser.add_subparsers( |
| 7240 |
title="subcommands", |
| 7241 |
description="valid subcommands", |
| 7242 |
help="additional help", |
| 7243 |
) |
| 7244 |
subparsers.add_parser("sub1", deprecated=True, help="sub1 help") |
| 7245 |
sub2 = subparsers.add_parser("sub2", deprecated=True, help="sub2 help") |
| 7246 |
sub2.add_argument("--baz", choices=("X", "Y", "Z"), help="baz help") |
| 7247 |
|
| 7248 |
prog = self.theme.prog |
| 7249 |
heading = self.theme.heading |
| 7250 |
long = self.theme.summary_long_option |
| 7251 |
short = self.theme.summary_short_option |
| 7252 |
label = self.theme.summary_label |
| 7253 |
pos = self.theme.summary_action |
| 7254 |
long_b = self.theme.long_option |
| 7255 |
short_b = self.theme.short_option |
| 7256 |
label_b = self.theme.label |
| 7257 |
pos_b = self.theme.action |
| 7258 |
reset = self.theme.reset |
| 7259 |
|
| 7260 |
# Act |
| 7261 |
help_text = parser.format_help() |
| 7262 |
|
| 7263 |
# Assert |
| 7264 |
self.assertEqual( |
| 7265 |
help_text, |
| 7266 |
textwrap.dedent( |
| 7267 |
f"""\ |
| 7268 |
{heading}usage: {reset}{prog}PROG{reset} [{short}-h{reset}] [{short}-v{reset} | {short}-q{reset}] [{short}-o{reset}] [{long}--optional2 {label}OPTIONAL2{reset}] [{long}--optional3 {label}{{X,Y,Z}}{reset}] |
| 7269 |
[{long}--optional4 {label}{{X,Y,Z}}{reset}] [{long}--optional5 {label}{{X,Y,Z}}{reset}] [{long}--optional6 {label}{{X,Y,Z}}{reset}] |
| 7270 |
[{short}-p {label}{{Aaaaa,Bbbbb,Ccccc,Ddddd}}{reset}] [{short}+f {label}F{reset}] [{long}++bar {label}BAR{reset}] [{long}-+baz {label}BAZ{reset}] |
| 7271 |
[{short}-c {label}COUNT{reset}] |
| 7272 |
{pos}x{reset} {pos}y{reset} {pos}this_indeed_is_a_very_long_action_name{reset} {pos}{{sub1,sub2}} ...{reset} |
| 7273 |
|
| 7274 |
Colorful help |
| 7275 |
|
| 7276 |
{heading}positional arguments:{reset} |
| 7277 |
{pos_b}x{reset} the base |
| 7278 |
{pos_b}y{reset} the exponent |
| 7279 |
{pos_b}this_indeed_is_a_very_long_action_name{reset} |
| 7280 |
the exponent |
| 7281 |
|
| 7282 |
{heading}options:{reset} |
| 7283 |
{short_b}-h{reset}, {long_b}--help{reset} show this help message and exit |
| 7284 |
{short_b}-v{reset}, {long_b}--verbose{reset} more spam (default: False) |
| 7285 |
{short_b}-q{reset}, {long_b}--quiet{reset} less spam (default: False) |
| 7286 |
{short_b}-o{reset}, {long_b}--optional1{reset} |
| 7287 |
{long_b}--optional2{reset} {label_b}OPTIONAL2{reset} |
| 7288 |
pick one (default: None) |
| 7289 |
{long_b}--optional3{reset} {label_b}{{X,Y,Z}}{reset} |
| 7290 |
{long_b}--optional4{reset} {label_b}{{X,Y,Z}}{reset} pick one (default: None) |
| 7291 |
{long_b}--optional5{reset} {label_b}{{X,Y,Z}}{reset} pick one (default: None) |
| 7292 |
{long_b}--optional6{reset} {label_b}{{X,Y,Z}}{reset} pick one (default: None) |
| 7293 |
{short_b}-p{reset}, {long_b}--optional7{reset} {label_b}{{Aaaaa,Bbbbb,Ccccc,Ddddd}}{reset} |
| 7294 |
pick one (default: None) |
| 7295 |
{short_b}+f{reset} {label_b}F{reset} |
| 7296 |
{long_b}++bar{reset} {label_b}BAR{reset} |
| 7297 |
{long_b}-+baz{reset} {label_b}BAZ{reset} |
| 7298 |
{short_b}-c{reset}, {long_b}--count{reset} {label_b}COUNT{reset} |
| 7299 |
|
| 7300 |
{heading}subcommands:{reset} |
| 7301 |
valid subcommands |
| 7302 |
|
| 7303 |
{pos_b}{{sub1,sub2}}{reset} additional help |
| 7304 |
{pos_b}sub1{reset} sub1 help |
| 7305 |
{pos_b}sub2{reset} sub2 help |
| 7306 |
""" |
| 7307 |
), |
| 7308 |
) |
| 7309 |
|
| 7310 |
def test_argparse_color_mutually_exclusive_group_usage(self): |
| 7311 |
parser = argparse.ArgumentParser(color=True, prog="PROG") |
| 7312 |
group = parser.add_mutually_exclusive_group() |
| 7313 |
group.add_argument('--foo', action='store_true', help='FOO') |
| 7314 |
group.add_argument('--spam', help='SPAM') |
| 7315 |
group.add_argument('badger', nargs='*', help='BADGER') |
| 7316 |
|
| 7317 |
prog = self.theme.prog |
| 7318 |
heading = self.theme.heading |
| 7319 |
long = self.theme.summary_long_option |
| 7320 |
short = self.theme.summary_short_option |
| 7321 |
label = self.theme.summary_label |
| 7322 |
pos = self.theme.summary_action |
| 7323 |
reset = self.theme.reset |
| 7324 |
|
| 7325 |
self.assertEqual(parser.format_usage(), |
| 7326 |
f"{heading}usage: {reset}{prog}PROG{reset} [{short}-h{reset}] " |
| 7327 |
f"[{long}--foo{reset} | " |
| 7328 |
f"{long}--spam {label}SPAM{reset} | " |
| 7329 |
f"{pos}badger ...{reset}]\n") |
| 7330 |
|
| 7331 |
def test_argparse_color_custom_usage(self): |
| 7332 |
# Arrange |
| 7333 |
parser = argparse.ArgumentParser( |
| 7334 |
add_help=False, |
| 7335 |
color=True, |
| 7336 |
description="Test prog and usage colors", |
| 7337 |
prog="PROG", |
| 7338 |
usage="[prefix] %(prog)s [suffix]", |
| 7339 |
) |
| 7340 |
heading = self.theme.heading |
| 7341 |
prog = self.theme.prog |
| 7342 |
reset = self.theme.reset |
| 7343 |
usage = self.theme.prog_extra |
| 7344 |
|
| 7345 |
# Act |
| 7346 |
help_text = parser.format_help() |
| 7347 |
|
| 7348 |
# Assert |
| 7349 |
self.assertEqual( |
| 7350 |
help_text, |
| 7351 |
textwrap.dedent( |
| 7352 |
f"""\ |
| 7353 |
{heading}usage: {reset}{usage}[prefix] {prog}PROG{reset}{usage} [suffix]{reset} |
| 7354 |
|
| 7355 |
Test prog and usage colors |
| 7356 |
""" |
| 7357 |
), |
| 7358 |
) |
| 7359 |
|
| 7360 |
def test_custom_formatter_function(self): |
| 7361 |
def custom_formatter(prog): |
| 7362 |
return argparse.RawTextHelpFormatter(prog, indent_increment=5) |
| 7363 |
|
| 7364 |
parser = argparse.ArgumentParser( |
| 7365 |
prog="PROG", |
| 7366 |
prefix_chars="-+", |
| 7367 |
formatter_class=custom_formatter, |
| 7368 |
color=True, |
| 7369 |
) |
| 7370 |
parser.add_argument('+f', '++foo', help="foo help") |
| 7371 |
parser.add_argument('spam', help="spam help") |
| 7372 |
|
| 7373 |
prog = self.theme.prog |
| 7374 |
heading = self.theme.heading |
| 7375 |
short = self.theme.summary_short_option |
| 7376 |
label = self.theme.summary_label |
| 7377 |
pos = self.theme.summary_action |
| 7378 |
long_b = self.theme.long_option |
| 7379 |
short_b = self.theme.short_option |
| 7380 |
label_b = self.theme.label |
| 7381 |
pos_b = self.theme.action |
| 7382 |
reset = self.theme.reset |
| 7383 |
|
| 7384 |
parser_help = parser.format_help() |
| 7385 |
self.assertEqual(parser_help, textwrap.dedent(f'''\ |
| 7386 |
{heading}usage: {reset}{prog}PROG{reset} [{short}-h{reset}] [{short}+f {label}FOO{reset}] {pos}spam{reset} |
| 7387 |
|
| 7388 |
{heading}positional arguments:{reset} |
| 7389 |
{pos_b}spam{reset} spam help |
| 7390 |
|
| 7391 |
{heading}options:{reset} |
| 7392 |
{short_b}-h{reset}, {long_b}--help{reset} show this help message and exit |
| 7393 |
{short_b}+f{reset}, {long_b}++foo{reset} {label_b}FOO{reset} foo help |
| 7394 |
''')) |
| 7395 |
|
| 7396 |
def test_custom_formatter_class(self): |
| 7397 |
class CustomFormatter(argparse.RawTextHelpFormatter): |
| 7398 |
def __init__(self, prog): |
| 7399 |
super().__init__(prog, indent_increment=5) |
| 7400 |
|
| 7401 |
parser = argparse.ArgumentParser( |
| 7402 |
prog="PROG", |
| 7403 |
prefix_chars="-+", |
| 7404 |
formatter_class=CustomFormatter, |
| 7405 |
color=True, |
| 7406 |
) |
| 7407 |
parser.add_argument('+f', '++foo', help="foo help") |
| 7408 |
parser.add_argument('spam', help="spam help") |
| 7409 |
|
| 7410 |
prog = self.theme.prog |
| 7411 |
heading = self.theme.heading |
| 7412 |
short = self.theme.summary_short_option |
| 7413 |
label = self.theme.summary_label |
| 7414 |
pos = self.theme.summary_action |
| 7415 |
long_b = self.theme.long_option |
| 7416 |
short_b = self.theme.short_option |
| 7417 |
label_b = self.theme.label |
| 7418 |
pos_b = self.theme.action |
| 7419 |
reset = self.theme.reset |
| 7420 |
|
| 7421 |
parser_help = parser.format_help() |
| 7422 |
self.assertEqual(parser_help, textwrap.dedent(f'''\ |
| 7423 |
{heading}usage: {reset}{prog}PROG{reset} [{short}-h{reset}] [{short}+f {label}FOO{reset}] {pos}spam{reset} |
| 7424 |
|
| 7425 |
{heading}positional arguments:{reset} |
| 7426 |
{pos_b}spam{reset} spam help |
| 7427 |
|
| 7428 |
{heading}options:{reset} |
| 7429 |
{short_b}-h{reset}, {long_b}--help{reset} show this help message and exit |
| 7430 |
{short_b}+f{reset}, {long_b}++foo{reset} {label_b}FOO{reset} foo help |
| 7431 |
''')) |
| 7432 |
|
| 7433 |
def test_subparser_prog_is_stored_without_color(self): |
| 7434 |
parser = argparse.ArgumentParser(prog='complex', color=True) |
| 7435 |
sub = parser.add_subparsers(dest='command') |
| 7436 |
demo_parser = sub.add_parser('demo') |
| 7437 |
|
| 7438 |
self.assertNotIn('\x1b[', demo_parser.prog) |
| 7439 |
|
| 7440 |
demo_parser.color = False |
| 7441 |
help_text = demo_parser.format_help() |
| 7442 |
self.assertNotIn('\x1b[', help_text) |
| 7443 |
|
| 7444 |
|
| 7445 |
def tearDownModule(): |
| 7446 |
# Remove global references to avoid looking like we have refleaks. |
| 7447 |
RFile.seen = {} |
| 7448 |
WFile.seen = set() |
| 7449 |
|
| 7450 |
|
| 7451 |
if __name__ == '__main__': |
| 7452 |
# To regenerate translation snapshots |
| 7453 |
if len(sys.argv) > 1 and sys.argv[1] == '--snapshot-update': |
| 7454 |
update_translation_snapshots(argparse) |
| 7455 |
sys.exit(0) |
| 7456 |
unittest.main() |