PageRenderTime 62ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/test/test_argparse.py

https://bitbucket.org/dac_io/pypy
Python | 4646 lines | 4639 code | 6 blank | 1 comment | 2 complexity | f31dd679868b0aab7953a6b7fab8a988 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. # Author: Steven J. Bethard <steven.bethard@gmail.com>.
  2. import codecs
  3. import inspect
  4. import os
  5. import shutil
  6. import stat
  7. import sys
  8. import textwrap
  9. import tempfile
  10. import unittest
  11. import argparse
  12. from StringIO import StringIO
  13. class StdIOBuffer(StringIO):
  14. pass
  15. from test import test_support
  16. class TestCase(unittest.TestCase):
  17. def assertEqual(self, obj1, obj2):
  18. if obj1 != obj2:
  19. print('')
  20. print(repr(obj1))
  21. print(repr(obj2))
  22. print(obj1)
  23. print(obj2)
  24. super(TestCase, self).assertEqual(obj1, obj2)
  25. def setUp(self):
  26. # The tests assume that line wrapping occurs at 80 columns, but this
  27. # behaviour can be overridden by setting the COLUMNS environment
  28. # variable. To ensure that this assumption is true, unset COLUMNS.
  29. env = test_support.EnvironmentVarGuard()
  30. env.unset("COLUMNS")
  31. self.addCleanup(env.__exit__)
  32. class TempDirMixin(object):
  33. def setUp(self):
  34. self.temp_dir = tempfile.mkdtemp()
  35. self.old_dir = os.getcwd()
  36. os.chdir(self.temp_dir)
  37. def tearDown(self):
  38. os.chdir(self.old_dir)
  39. shutil.rmtree(self.temp_dir, True)
  40. def create_readonly_file(self, filename):
  41. file_path = os.path.join(self.temp_dir, filename)
  42. with open(file_path, 'w') as file:
  43. file.write(filename)
  44. os.chmod(file_path, stat.S_IREAD)
  45. class Sig(object):
  46. def __init__(self, *args, **kwargs):
  47. self.args = args
  48. self.kwargs = kwargs
  49. class NS(object):
  50. def __init__(self, **kwargs):
  51. self.__dict__.update(kwargs)
  52. def __repr__(self):
  53. sorted_items = sorted(self.__dict__.items())
  54. kwarg_str = ', '.join(['%s=%r' % tup for tup in sorted_items])
  55. return '%s(%s)' % (type(self).__name__, kwarg_str)
  56. __hash__ = None
  57. def __eq__(self, other):
  58. return vars(self) == vars(other)
  59. def __ne__(self, other):
  60. return not (self == other)
  61. class ArgumentParserError(Exception):
  62. def __init__(self, message, stdout=None, stderr=None, error_code=None):
  63. Exception.__init__(self, message, stdout, stderr)
  64. self.message = message
  65. self.stdout = stdout
  66. self.stderr = stderr
  67. self.error_code = error_code
  68. def stderr_to_parser_error(parse_args, *args, **kwargs):
  69. # if this is being called recursively and stderr or stdout is already being
  70. # redirected, simply call the function and let the enclosing function
  71. # catch the exception
  72. if isinstance(sys.stderr, StdIOBuffer) or isinstance(sys.stdout, StdIOBuffer):
  73. return parse_args(*args, **kwargs)
  74. # if this is not being called recursively, redirect stderr and
  75. # use it as the ArgumentParserError message
  76. old_stdout = sys.stdout
  77. old_stderr = sys.stderr
  78. sys.stdout = StdIOBuffer()
  79. sys.stderr = StdIOBuffer()
  80. try:
  81. try:
  82. result = parse_args(*args, **kwargs)
  83. for key in list(vars(result)):
  84. if getattr(result, key) is sys.stdout:
  85. setattr(result, key, old_stdout)
  86. if getattr(result, key) is sys.stderr:
  87. setattr(result, key, old_stderr)
  88. return result
  89. except SystemExit:
  90. code = sys.exc_info()[1].code
  91. stdout = sys.stdout.getvalue()
  92. stderr = sys.stderr.getvalue()
  93. raise ArgumentParserError("SystemExit", stdout, stderr, code)
  94. finally:
  95. sys.stdout = old_stdout
  96. sys.stderr = old_stderr
  97. class ErrorRaisingArgumentParser(argparse.ArgumentParser):
  98. def parse_args(self, *args, **kwargs):
  99. parse_args = super(ErrorRaisingArgumentParser, self).parse_args
  100. return stderr_to_parser_error(parse_args, *args, **kwargs)
  101. def exit(self, *args, **kwargs):
  102. exit = super(ErrorRaisingArgumentParser, self).exit
  103. return stderr_to_parser_error(exit, *args, **kwargs)
  104. def error(self, *args, **kwargs):
  105. error = super(ErrorRaisingArgumentParser, self).error
  106. return stderr_to_parser_error(error, *args, **kwargs)
  107. class ParserTesterMetaclass(type):
  108. """Adds parser tests using the class attributes.
  109. Classes of this type should specify the following attributes:
  110. argument_signatures -- a list of Sig objects which specify
  111. the signatures of Argument objects to be created
  112. failures -- a list of args lists that should cause the parser
  113. to fail
  114. successes -- a list of (initial_args, options, remaining_args) tuples
  115. where initial_args specifies the string args to be parsed,
  116. options is a dict that should match the vars() of the options
  117. parsed out of initial_args, and remaining_args should be any
  118. remaining unparsed arguments
  119. """
  120. def __init__(cls, name, bases, bodydict):
  121. if name == 'ParserTestCase':
  122. return
  123. # default parser signature is empty
  124. if not hasattr(cls, 'parser_signature'):
  125. cls.parser_signature = Sig()
  126. if not hasattr(cls, 'parser_class'):
  127. cls.parser_class = ErrorRaisingArgumentParser
  128. # ---------------------------------------
  129. # functions for adding optional arguments
  130. # ---------------------------------------
  131. def no_groups(parser, argument_signatures):
  132. """Add all arguments directly to the parser"""
  133. for sig in argument_signatures:
  134. parser.add_argument(*sig.args, **sig.kwargs)
  135. def one_group(parser, argument_signatures):
  136. """Add all arguments under a single group in the parser"""
  137. group = parser.add_argument_group('foo')
  138. for sig in argument_signatures:
  139. group.add_argument(*sig.args, **sig.kwargs)
  140. def many_groups(parser, argument_signatures):
  141. """Add each argument in its own group to the parser"""
  142. for i, sig in enumerate(argument_signatures):
  143. group = parser.add_argument_group('foo:%i' % i)
  144. group.add_argument(*sig.args, **sig.kwargs)
  145. # --------------------------
  146. # functions for parsing args
  147. # --------------------------
  148. def listargs(parser, args):
  149. """Parse the args by passing in a list"""
  150. return parser.parse_args(args)
  151. def sysargs(parser, args):
  152. """Parse the args by defaulting to sys.argv"""
  153. old_sys_argv = sys.argv
  154. sys.argv = [old_sys_argv[0]] + args
  155. try:
  156. return parser.parse_args()
  157. finally:
  158. sys.argv = old_sys_argv
  159. # class that holds the combination of one optional argument
  160. # addition method and one arg parsing method
  161. class AddTests(object):
  162. def __init__(self, tester_cls, add_arguments, parse_args):
  163. self._add_arguments = add_arguments
  164. self._parse_args = parse_args
  165. add_arguments_name = self._add_arguments.__name__
  166. parse_args_name = self._parse_args.__name__
  167. for test_func in [self.test_failures, self.test_successes]:
  168. func_name = test_func.__name__
  169. names = func_name, add_arguments_name, parse_args_name
  170. test_name = '_'.join(names)
  171. def wrapper(self, test_func=test_func):
  172. test_func(self)
  173. try:
  174. wrapper.__name__ = test_name
  175. except TypeError:
  176. pass
  177. setattr(tester_cls, test_name, wrapper)
  178. def _get_parser(self, tester):
  179. args = tester.parser_signature.args
  180. kwargs = tester.parser_signature.kwargs
  181. parser = tester.parser_class(*args, **kwargs)
  182. self._add_arguments(parser, tester.argument_signatures)
  183. return parser
  184. def test_failures(self, tester):
  185. parser = self._get_parser(tester)
  186. for args_str in tester.failures:
  187. args = args_str.split()
  188. raises = tester.assertRaises
  189. raises(ArgumentParserError, parser.parse_args, args)
  190. def test_successes(self, tester):
  191. parser = self._get_parser(tester)
  192. for args, expected_ns in tester.successes:
  193. if isinstance(args, str):
  194. args = args.split()
  195. result_ns = self._parse_args(parser, args)
  196. tester.assertEqual(expected_ns, result_ns)
  197. # add tests for each combination of an optionals adding method
  198. # and an arg parsing method
  199. for add_arguments in [no_groups, one_group, many_groups]:
  200. for parse_args in [listargs, sysargs]:
  201. AddTests(cls, add_arguments, parse_args)
  202. bases = TestCase,
  203. ParserTestCase = ParserTesterMetaclass('ParserTestCase', bases, {})
  204. # ===============
  205. # Optionals tests
  206. # ===============
  207. class TestOptionalsSingleDash(ParserTestCase):
  208. """Test an Optional with a single-dash option string"""
  209. argument_signatures = [Sig('-x')]
  210. failures = ['-x', 'a', '--foo', '-x --foo', '-x -y']
  211. successes = [
  212. ('', NS(x=None)),
  213. ('-x a', NS(x='a')),
  214. ('-xa', NS(x='a')),
  215. ('-x -1', NS(x='-1')),
  216. ('-x-1', NS(x='-1')),
  217. ]
  218. class TestOptionalsSingleDashCombined(ParserTestCase):
  219. """Test an Optional with a single-dash option string"""
  220. argument_signatures = [
  221. Sig('-x', action='store_true'),
  222. Sig('-yyy', action='store_const', const=42),
  223. Sig('-z'),
  224. ]
  225. failures = ['a', '--foo', '-xa', '-x --foo', '-x -z', '-z -x',
  226. '-yx', '-yz a', '-yyyx', '-yyyza', '-xyza']
  227. successes = [
  228. ('', NS(x=False, yyy=None, z=None)),
  229. ('-x', NS(x=True, yyy=None, z=None)),
  230. ('-za', NS(x=False, yyy=None, z='a')),
  231. ('-z a', NS(x=False, yyy=None, z='a')),
  232. ('-xza', NS(x=True, yyy=None, z='a')),
  233. ('-xz a', NS(x=True, yyy=None, z='a')),
  234. ('-x -za', NS(x=True, yyy=None, z='a')),
  235. ('-x -z a', NS(x=True, yyy=None, z='a')),
  236. ('-y', NS(x=False, yyy=42, z=None)),
  237. ('-yyy', NS(x=False, yyy=42, z=None)),
  238. ('-x -yyy -za', NS(x=True, yyy=42, z='a')),
  239. ('-x -yyy -z a', NS(x=True, yyy=42, z='a')),
  240. ]
  241. class TestOptionalsSingleDashLong(ParserTestCase):
  242. """Test an Optional with a multi-character single-dash option string"""
  243. argument_signatures = [Sig('-foo')]
  244. failures = ['-foo', 'a', '--foo', '-foo --foo', '-foo -y', '-fooa']
  245. successes = [
  246. ('', NS(foo=None)),
  247. ('-foo a', NS(foo='a')),
  248. ('-foo -1', NS(foo='-1')),
  249. ('-fo a', NS(foo='a')),
  250. ('-f a', NS(foo='a')),
  251. ]
  252. class TestOptionalsSingleDashSubsetAmbiguous(ParserTestCase):
  253. """Test Optionals where option strings are subsets of each other"""
  254. argument_signatures = [Sig('-f'), Sig('-foobar'), Sig('-foorab')]
  255. failures = ['-f', '-foo', '-fo', '-foo b', '-foob', '-fooba', '-foora']
  256. successes = [
  257. ('', NS(f=None, foobar=None, foorab=None)),
  258. ('-f a', NS(f='a', foobar=None, foorab=None)),
  259. ('-fa', NS(f='a', foobar=None, foorab=None)),
  260. ('-foa', NS(f='oa', foobar=None, foorab=None)),
  261. ('-fooa', NS(f='ooa', foobar=None, foorab=None)),
  262. ('-foobar a', NS(f=None, foobar='a', foorab=None)),
  263. ('-foorab a', NS(f=None, foobar=None, foorab='a')),
  264. ]
  265. class TestOptionalsSingleDashAmbiguous(ParserTestCase):
  266. """Test Optionals that partially match but are not subsets"""
  267. argument_signatures = [Sig('-foobar'), Sig('-foorab')]
  268. failures = ['-f', '-f a', '-fa', '-foa', '-foo', '-fo', '-foo b']
  269. successes = [
  270. ('', NS(foobar=None, foorab=None)),
  271. ('-foob a', NS(foobar='a', foorab=None)),
  272. ('-foor a', NS(foobar=None, foorab='a')),
  273. ('-fooba a', NS(foobar='a', foorab=None)),
  274. ('-foora a', NS(foobar=None, foorab='a')),
  275. ('-foobar a', NS(foobar='a', foorab=None)),
  276. ('-foorab a', NS(foobar=None, foorab='a')),
  277. ]
  278. class TestOptionalsNumeric(ParserTestCase):
  279. """Test an Optional with a short opt string"""
  280. argument_signatures = [Sig('-1', dest='one')]
  281. failures = ['-1', 'a', '-1 --foo', '-1 -y', '-1 -1', '-1 -2']
  282. successes = [
  283. ('', NS(one=None)),
  284. ('-1 a', NS(one='a')),
  285. ('-1a', NS(one='a')),
  286. ('-1-2', NS(one='-2')),
  287. ]
  288. class TestOptionalsDoubleDash(ParserTestCase):
  289. """Test an Optional with a double-dash option string"""
  290. argument_signatures = [Sig('--foo')]
  291. failures = ['--foo', '-f', '-f a', 'a', '--foo -x', '--foo --bar']
  292. successes = [
  293. ('', NS(foo=None)),
  294. ('--foo a', NS(foo='a')),
  295. ('--foo=a', NS(foo='a')),
  296. ('--foo -2.5', NS(foo='-2.5')),
  297. ('--foo=-2.5', NS(foo='-2.5')),
  298. ]
  299. class TestOptionalsDoubleDashPartialMatch(ParserTestCase):
  300. """Tests partial matching with a double-dash option string"""
  301. argument_signatures = [
  302. Sig('--badger', action='store_true'),
  303. Sig('--bat'),
  304. ]
  305. failures = ['--bar', '--b', '--ba', '--b=2', '--ba=4', '--badge 5']
  306. successes = [
  307. ('', NS(badger=False, bat=None)),
  308. ('--bat X', NS(badger=False, bat='X')),
  309. ('--bad', NS(badger=True, bat=None)),
  310. ('--badg', NS(badger=True, bat=None)),
  311. ('--badge', NS(badger=True, bat=None)),
  312. ('--badger', NS(badger=True, bat=None)),
  313. ]
  314. class TestOptionalsDoubleDashPrefixMatch(ParserTestCase):
  315. """Tests when one double-dash option string is a prefix of another"""
  316. argument_signatures = [
  317. Sig('--badger', action='store_true'),
  318. Sig('--ba'),
  319. ]
  320. failures = ['--bar', '--b', '--ba', '--b=2', '--badge 5']
  321. successes = [
  322. ('', NS(badger=False, ba=None)),
  323. ('--ba X', NS(badger=False, ba='X')),
  324. ('--ba=X', NS(badger=False, ba='X')),
  325. ('--bad', NS(badger=True, ba=None)),
  326. ('--badg', NS(badger=True, ba=None)),
  327. ('--badge', NS(badger=True, ba=None)),
  328. ('--badger', NS(badger=True, ba=None)),
  329. ]
  330. class TestOptionalsSingleDoubleDash(ParserTestCase):
  331. """Test an Optional with single- and double-dash option strings"""
  332. argument_signatures = [
  333. Sig('-f', action='store_true'),
  334. Sig('--bar'),
  335. Sig('-baz', action='store_const', const=42),
  336. ]
  337. failures = ['--bar', '-fbar', '-fbaz', '-bazf', '-b B', 'B']
  338. successes = [
  339. ('', NS(f=False, bar=None, baz=None)),
  340. ('-f', NS(f=True, bar=None, baz=None)),
  341. ('--ba B', NS(f=False, bar='B', baz=None)),
  342. ('-f --bar B', NS(f=True, bar='B', baz=None)),
  343. ('-f -b', NS(f=True, bar=None, baz=42)),
  344. ('-ba -f', NS(f=True, bar=None, baz=42)),
  345. ]
  346. class TestOptionalsAlternatePrefixChars(ParserTestCase):
  347. """Test an Optional with option strings with custom prefixes"""
  348. parser_signature = Sig(prefix_chars='+:/', add_help=False)
  349. argument_signatures = [
  350. Sig('+f', action='store_true'),
  351. Sig('::bar'),
  352. Sig('/baz', action='store_const', const=42),
  353. ]
  354. failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz', '-h', '--help', '+h', '::help', '/help']
  355. successes = [
  356. ('', NS(f=False, bar=None, baz=None)),
  357. ('+f', NS(f=True, bar=None, baz=None)),
  358. ('::ba B', NS(f=False, bar='B', baz=None)),
  359. ('+f ::bar B', NS(f=True, bar='B', baz=None)),
  360. ('+f /b', NS(f=True, bar=None, baz=42)),
  361. ('/ba +f', NS(f=True, bar=None, baz=42)),
  362. ]
  363. class TestOptionalsAlternatePrefixCharsAddedHelp(ParserTestCase):
  364. """When ``-`` not in prefix_chars, default operators created for help
  365. should use the prefix_chars in use rather than - or --
  366. http://bugs.python.org/issue9444"""
  367. parser_signature = Sig(prefix_chars='+:/', add_help=True)
  368. argument_signatures = [
  369. Sig('+f', action='store_true'),
  370. Sig('::bar'),
  371. Sig('/baz', action='store_const', const=42),
  372. ]
  373. failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz']
  374. successes = [
  375. ('', NS(f=False, bar=None, baz=None)),
  376. ('+f', NS(f=True, bar=None, baz=None)),
  377. ('::ba B', NS(f=False, bar='B', baz=None)),
  378. ('+f ::bar B', NS(f=True, bar='B', baz=None)),
  379. ('+f /b', NS(f=True, bar=None, baz=42)),
  380. ('/ba +f', NS(f=True, bar=None, baz=42))
  381. ]
  382. class TestOptionalsAlternatePrefixCharsMultipleShortArgs(ParserTestCase):
  383. """Verify that Optionals must be called with their defined prefixes"""
  384. parser_signature = Sig(prefix_chars='+-', add_help=False)
  385. argument_signatures = [
  386. Sig('-x', action='store_true'),
  387. Sig('+y', action='store_true'),
  388. Sig('+z', action='store_true'),
  389. ]
  390. failures = ['-w',
  391. '-xyz',
  392. '+x',
  393. '-y',
  394. '+xyz',
  395. ]
  396. successes = [
  397. ('', NS(x=False, y=False, z=False)),
  398. ('-x', NS(x=True, y=False, z=False)),
  399. ('+y -x', NS(x=True, y=True, z=False)),
  400. ('+yz -x', NS(x=True, y=True, z=True)),
  401. ]
  402. class TestOptionalsShortLong(ParserTestCase):
  403. """Test a combination of single- and double-dash option strings"""
  404. argument_signatures = [
  405. Sig('-v', '--verbose', '-n', '--noisy', action='store_true'),
  406. ]
  407. failures = ['--x --verbose', '-N', 'a', '-v x']
  408. successes = [
  409. ('', NS(verbose=False)),
  410. ('-v', NS(verbose=True)),
  411. ('--verbose', NS(verbose=True)),
  412. ('-n', NS(verbose=True)),
  413. ('--noisy', NS(verbose=True)),
  414. ]
  415. class TestOptionalsDest(ParserTestCase):
  416. """Tests various means of setting destination"""
  417. argument_signatures = [Sig('--foo-bar'), Sig('--baz', dest='zabbaz')]
  418. failures = ['a']
  419. successes = [
  420. ('--foo-bar f', NS(foo_bar='f', zabbaz=None)),
  421. ('--baz g', NS(foo_bar=None, zabbaz='g')),
  422. ('--foo-bar h --baz i', NS(foo_bar='h', zabbaz='i')),
  423. ('--baz j --foo-bar k', NS(foo_bar='k', zabbaz='j')),
  424. ]
  425. class TestOptionalsDefault(ParserTestCase):
  426. """Tests specifying a default for an Optional"""
  427. argument_signatures = [Sig('-x'), Sig('-y', default=42)]
  428. failures = ['a']
  429. successes = [
  430. ('', NS(x=None, y=42)),
  431. ('-xx', NS(x='x', y=42)),
  432. ('-yy', NS(x=None, y='y')),
  433. ]
  434. class TestOptionalsNargsDefault(ParserTestCase):
  435. """Tests not specifying the number of args for an Optional"""
  436. argument_signatures = [Sig('-x')]
  437. failures = ['a', '-x']
  438. successes = [
  439. ('', NS(x=None)),
  440. ('-x a', NS(x='a')),
  441. ]
  442. class TestOptionalsNargs1(ParserTestCase):
  443. """Tests specifying the 1 arg for an Optional"""
  444. argument_signatures = [Sig('-x', nargs=1)]
  445. failures = ['a', '-x']
  446. successes = [
  447. ('', NS(x=None)),
  448. ('-x a', NS(x=['a'])),
  449. ]
  450. class TestOptionalsNargs3(ParserTestCase):
  451. """Tests specifying the 3 args for an Optional"""
  452. argument_signatures = [Sig('-x', nargs=3)]
  453. failures = ['a', '-x', '-x a', '-x a b', 'a -x', 'a -x b']
  454. successes = [
  455. ('', NS(x=None)),
  456. ('-x a b c', NS(x=['a', 'b', 'c'])),
  457. ]
  458. class TestOptionalsNargsOptional(ParserTestCase):
  459. """Tests specifying an Optional arg for an Optional"""
  460. argument_signatures = [
  461. Sig('-w', nargs='?'),
  462. Sig('-x', nargs='?', const=42),
  463. Sig('-y', nargs='?', default='spam'),
  464. Sig('-z', nargs='?', type=int, const='42', default='84'),
  465. ]
  466. failures = ['2']
  467. successes = [
  468. ('', NS(w=None, x=None, y='spam', z=84)),
  469. ('-w', NS(w=None, x=None, y='spam', z=84)),
  470. ('-w 2', NS(w='2', x=None, y='spam', z=84)),
  471. ('-x', NS(w=None, x=42, y='spam', z=84)),
  472. ('-x 2', NS(w=None, x='2', y='spam', z=84)),
  473. ('-y', NS(w=None, x=None, y=None, z=84)),
  474. ('-y 2', NS(w=None, x=None, y='2', z=84)),
  475. ('-z', NS(w=None, x=None, y='spam', z=42)),
  476. ('-z 2', NS(w=None, x=None, y='spam', z=2)),
  477. ]
  478. class TestOptionalsNargsZeroOrMore(ParserTestCase):
  479. """Tests specifying an args for an Optional that accepts zero or more"""
  480. argument_signatures = [
  481. Sig('-x', nargs='*'),
  482. Sig('-y', nargs='*', default='spam'),
  483. ]
  484. failures = ['a']
  485. successes = [
  486. ('', NS(x=None, y='spam')),
  487. ('-x', NS(x=[], y='spam')),
  488. ('-x a', NS(x=['a'], y='spam')),
  489. ('-x a b', NS(x=['a', 'b'], y='spam')),
  490. ('-y', NS(x=None, y=[])),
  491. ('-y a', NS(x=None, y=['a'])),
  492. ('-y a b', NS(x=None, y=['a', 'b'])),
  493. ]
  494. class TestOptionalsNargsOneOrMore(ParserTestCase):
  495. """Tests specifying an args for an Optional that accepts one or more"""
  496. argument_signatures = [
  497. Sig('-x', nargs='+'),
  498. Sig('-y', nargs='+', default='spam'),
  499. ]
  500. failures = ['a', '-x', '-y', 'a -x', 'a -y b']
  501. successes = [
  502. ('', NS(x=None, y='spam')),
  503. ('-x a', NS(x=['a'], y='spam')),
  504. ('-x a b', NS(x=['a', 'b'], y='spam')),
  505. ('-y a', NS(x=None, y=['a'])),
  506. ('-y a b', NS(x=None, y=['a', 'b'])),
  507. ]
  508. class TestOptionalsChoices(ParserTestCase):
  509. """Tests specifying the choices for an Optional"""
  510. argument_signatures = [
  511. Sig('-f', choices='abc'),
  512. Sig('-g', type=int, choices=range(5))]
  513. failures = ['a', '-f d', '-fad', '-ga', '-g 6']
  514. successes = [
  515. ('', NS(f=None, g=None)),
  516. ('-f a', NS(f='a', g=None)),
  517. ('-f c', NS(f='c', g=None)),
  518. ('-g 0', NS(f=None, g=0)),
  519. ('-g 03', NS(f=None, g=3)),
  520. ('-fb -g4', NS(f='b', g=4)),
  521. ]
  522. class TestOptionalsRequired(ParserTestCase):
  523. """Tests the an optional action that is required"""
  524. argument_signatures = [
  525. Sig('-x', type=int, required=True),
  526. ]
  527. failures = ['a', '']
  528. successes = [
  529. ('-x 1', NS(x=1)),
  530. ('-x42', NS(x=42)),
  531. ]
  532. class TestOptionalsActionStore(ParserTestCase):
  533. """Tests the store action for an Optional"""
  534. argument_signatures = [Sig('-x', action='store')]
  535. failures = ['a', 'a -x']
  536. successes = [
  537. ('', NS(x=None)),
  538. ('-xfoo', NS(x='foo')),
  539. ]
  540. class TestOptionalsActionStoreConst(ParserTestCase):
  541. """Tests the store_const action for an Optional"""
  542. argument_signatures = [Sig('-y', action='store_const', const=object)]
  543. failures = ['a']
  544. successes = [
  545. ('', NS(y=None)),
  546. ('-y', NS(y=object)),
  547. ]
  548. class TestOptionalsActionStoreFalse(ParserTestCase):
  549. """Tests the store_false action for an Optional"""
  550. argument_signatures = [Sig('-z', action='store_false')]
  551. failures = ['a', '-za', '-z a']
  552. successes = [
  553. ('', NS(z=True)),
  554. ('-z', NS(z=False)),
  555. ]
  556. class TestOptionalsActionStoreTrue(ParserTestCase):
  557. """Tests the store_true action for an Optional"""
  558. argument_signatures = [Sig('--apple', action='store_true')]
  559. failures = ['a', '--apple=b', '--apple b']
  560. successes = [
  561. ('', NS(apple=False)),
  562. ('--apple', NS(apple=True)),
  563. ]
  564. class TestOptionalsActionAppend(ParserTestCase):
  565. """Tests the append action for an Optional"""
  566. argument_signatures = [Sig('--baz', action='append')]
  567. failures = ['a', '--baz', 'a --baz', '--baz a b']
  568. successes = [
  569. ('', NS(baz=None)),
  570. ('--baz a', NS(baz=['a'])),
  571. ('--baz a --baz b', NS(baz=['a', 'b'])),
  572. ]
  573. class TestOptionalsActionAppendWithDefault(ParserTestCase):
  574. """Tests the append action for an Optional"""
  575. argument_signatures = [Sig('--baz', action='append', default=['X'])]
  576. failures = ['a', '--baz', 'a --baz', '--baz a b']
  577. successes = [
  578. ('', NS(baz=['X'])),
  579. ('--baz a', NS(baz=['X', 'a'])),
  580. ('--baz a --baz b', NS(baz=['X', 'a', 'b'])),
  581. ]
  582. class TestOptionalsActionAppendConst(ParserTestCase):
  583. """Tests the append_const action for an Optional"""
  584. argument_signatures = [
  585. Sig('-b', action='append_const', const=Exception),
  586. Sig('-c', action='append', dest='b'),
  587. ]
  588. failures = ['a', '-c', 'a -c', '-bx', '-b x']
  589. successes = [
  590. ('', NS(b=None)),
  591. ('-b', NS(b=[Exception])),
  592. ('-b -cx -b -cyz', NS(b=[Exception, 'x', Exception, 'yz'])),
  593. ]
  594. class TestOptionalsActionAppendConstWithDefault(ParserTestCase):
  595. """Tests the append_const action for an Optional"""
  596. argument_signatures = [
  597. Sig('-b', action='append_const', const=Exception, default=['X']),
  598. Sig('-c', action='append', dest='b'),
  599. ]
  600. failures = ['a', '-c', 'a -c', '-bx', '-b x']
  601. successes = [
  602. ('', NS(b=['X'])),
  603. ('-b', NS(b=['X', Exception])),
  604. ('-b -cx -b -cyz', NS(b=['X', Exception, 'x', Exception, 'yz'])),
  605. ]
  606. class TestOptionalsActionCount(ParserTestCase):
  607. """Tests the count action for an Optional"""
  608. argument_signatures = [Sig('-x', action='count')]
  609. failures = ['a', '-x a', '-x b', '-x a -x b']
  610. successes = [
  611. ('', NS(x=None)),
  612. ('-x', NS(x=1)),
  613. ]
  614. # ================
  615. # Positional tests
  616. # ================
  617. class TestPositionalsNargsNone(ParserTestCase):
  618. """Test a Positional that doesn't specify nargs"""
  619. argument_signatures = [Sig('foo')]
  620. failures = ['', '-x', 'a b']
  621. successes = [
  622. ('a', NS(foo='a')),
  623. ]
  624. class TestPositionalsNargs1(ParserTestCase):
  625. """Test a Positional that specifies an nargs of 1"""
  626. argument_signatures = [Sig('foo', nargs=1)]
  627. failures = ['', '-x', 'a b']
  628. successes = [
  629. ('a', NS(foo=['a'])),
  630. ]
  631. class TestPositionalsNargs2(ParserTestCase):
  632. """Test a Positional that specifies an nargs of 2"""
  633. argument_signatures = [Sig('foo', nargs=2)]
  634. failures = ['', 'a', '-x', 'a b c']
  635. successes = [
  636. ('a b', NS(foo=['a', 'b'])),
  637. ]
  638. class TestPositionalsNargsZeroOrMore(ParserTestCase):
  639. """Test a Positional that specifies unlimited nargs"""
  640. argument_signatures = [Sig('foo', nargs='*')]
  641. failures = ['-x']
  642. successes = [
  643. ('', NS(foo=[])),
  644. ('a', NS(foo=['a'])),
  645. ('a b', NS(foo=['a', 'b'])),
  646. ]
  647. class TestPositionalsNargsZeroOrMoreDefault(ParserTestCase):
  648. """Test a Positional that specifies unlimited nargs and a default"""
  649. argument_signatures = [Sig('foo', nargs='*', default='bar')]
  650. failures = ['-x']
  651. successes = [
  652. ('', NS(foo='bar')),
  653. ('a', NS(foo=['a'])),
  654. ('a b', NS(foo=['a', 'b'])),
  655. ]
  656. class TestPositionalsNargsOneOrMore(ParserTestCase):
  657. """Test a Positional that specifies one or more nargs"""
  658. argument_signatures = [Sig('foo', nargs='+')]
  659. failures = ['', '-x']
  660. successes = [
  661. ('a', NS(foo=['a'])),
  662. ('a b', NS(foo=['a', 'b'])),
  663. ]
  664. class TestPositionalsNargsOptional(ParserTestCase):
  665. """Tests an Optional Positional"""
  666. argument_signatures = [Sig('foo', nargs='?')]
  667. failures = ['-x', 'a b']
  668. successes = [
  669. ('', NS(foo=None)),
  670. ('a', NS(foo='a')),
  671. ]
  672. class TestPositionalsNargsOptionalDefault(ParserTestCase):
  673. """Tests an Optional Positional with a default value"""
  674. argument_signatures = [Sig('foo', nargs='?', default=42)]
  675. failures = ['-x', 'a b']
  676. successes = [
  677. ('', NS(foo=42)),
  678. ('a', NS(foo='a')),
  679. ]
  680. class TestPositionalsNargsOptionalConvertedDefault(ParserTestCase):
  681. """Tests an Optional Positional with a default value
  682. that needs to be converted to the appropriate type.
  683. """
  684. argument_signatures = [
  685. Sig('foo', nargs='?', type=int, default='42'),
  686. ]
  687. failures = ['-x', 'a b', '1 2']
  688. successes = [
  689. ('', NS(foo=42)),
  690. ('1', NS(foo=1)),
  691. ]
  692. class TestPositionalsNargsNoneNone(ParserTestCase):
  693. """Test two Positionals that don't specify nargs"""
  694. argument_signatures = [Sig('foo'), Sig('bar')]
  695. failures = ['', '-x', 'a', 'a b c']
  696. successes = [
  697. ('a b', NS(foo='a', bar='b')),
  698. ]
  699. class TestPositionalsNargsNone1(ParserTestCase):
  700. """Test a Positional with no nargs followed by one with 1"""
  701. argument_signatures = [Sig('foo'), Sig('bar', nargs=1)]
  702. failures = ['', '--foo', 'a', 'a b c']
  703. successes = [
  704. ('a b', NS(foo='a', bar=['b'])),
  705. ]
  706. class TestPositionalsNargs2None(ParserTestCase):
  707. """Test a Positional with 2 nargs followed by one with none"""
  708. argument_signatures = [Sig('foo', nargs=2), Sig('bar')]
  709. failures = ['', '--foo', 'a', 'a b', 'a b c d']
  710. successes = [
  711. ('a b c', NS(foo=['a', 'b'], bar='c')),
  712. ]
  713. class TestPositionalsNargsNoneZeroOrMore(ParserTestCase):
  714. """Test a Positional with no nargs followed by one with unlimited"""
  715. argument_signatures = [Sig('foo'), Sig('bar', nargs='*')]
  716. failures = ['', '--foo']
  717. successes = [
  718. ('a', NS(foo='a', bar=[])),
  719. ('a b', NS(foo='a', bar=['b'])),
  720. ('a b c', NS(foo='a', bar=['b', 'c'])),
  721. ]
  722. class TestPositionalsNargsNoneOneOrMore(ParserTestCase):
  723. """Test a Positional with no nargs followed by one with one or more"""
  724. argument_signatures = [Sig('foo'), Sig('bar', nargs='+')]
  725. failures = ['', '--foo', 'a']
  726. successes = [
  727. ('a b', NS(foo='a', bar=['b'])),
  728. ('a b c', NS(foo='a', bar=['b', 'c'])),
  729. ]
  730. class TestPositionalsNargsNoneOptional(ParserTestCase):
  731. """Test a Positional with no nargs followed by one with an Optional"""
  732. argument_signatures = [Sig('foo'), Sig('bar', nargs='?')]
  733. failures = ['', '--foo', 'a b c']
  734. successes = [
  735. ('a', NS(foo='a', bar=None)),
  736. ('a b', NS(foo='a', bar='b')),
  737. ]
  738. class TestPositionalsNargsZeroOrMoreNone(ParserTestCase):
  739. """Test a Positional with unlimited nargs followed by one with none"""
  740. argument_signatures = [Sig('foo', nargs='*'), Sig('bar')]
  741. failures = ['', '--foo']
  742. successes = [
  743. ('a', NS(foo=[], bar='a')),
  744. ('a b', NS(foo=['a'], bar='b')),
  745. ('a b c', NS(foo=['a', 'b'], bar='c')),
  746. ]
  747. class TestPositionalsNargsOneOrMoreNone(ParserTestCase):
  748. """Test a Positional with one or more nargs followed by one with none"""
  749. argument_signatures = [Sig('foo', nargs='+'), Sig('bar')]
  750. failures = ['', '--foo', 'a']
  751. successes = [
  752. ('a b', NS(foo=['a'], bar='b')),
  753. ('a b c', NS(foo=['a', 'b'], bar='c')),
  754. ]
  755. class TestPositionalsNargsOptionalNone(ParserTestCase):
  756. """Test a Positional with an Optional nargs followed by one with none"""
  757. argument_signatures = [Sig('foo', nargs='?', default=42), Sig('bar')]
  758. failures = ['', '--foo', 'a b c']
  759. successes = [
  760. ('a', NS(foo=42, bar='a')),
  761. ('a b', NS(foo='a', bar='b')),
  762. ]
  763. class TestPositionalsNargs2ZeroOrMore(ParserTestCase):
  764. """Test a Positional with 2 nargs followed by one with unlimited"""
  765. argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='*')]
  766. failures = ['', '--foo', 'a']
  767. successes = [
  768. ('a b', NS(foo=['a', 'b'], bar=[])),
  769. ('a b c', NS(foo=['a', 'b'], bar=['c'])),
  770. ]
  771. class TestPositionalsNargs2OneOrMore(ParserTestCase):
  772. """Test a Positional with 2 nargs followed by one with one or more"""
  773. argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='+')]
  774. failures = ['', '--foo', 'a', 'a b']
  775. successes = [
  776. ('a b c', NS(foo=['a', 'b'], bar=['c'])),
  777. ]
  778. class TestPositionalsNargs2Optional(ParserTestCase):
  779. """Test a Positional with 2 nargs followed by one optional"""
  780. argument_signatures = [Sig('foo', nargs=2), Sig('bar', nargs='?')]
  781. failures = ['', '--foo', 'a', 'a b c d']
  782. successes = [
  783. ('a b', NS(foo=['a', 'b'], bar=None)),
  784. ('a b c', NS(foo=['a', 'b'], bar='c')),
  785. ]
  786. class TestPositionalsNargsZeroOrMore1(ParserTestCase):
  787. """Test a Positional with unlimited nargs followed by one with 1"""
  788. argument_signatures = [Sig('foo', nargs='*'), Sig('bar', nargs=1)]
  789. failures = ['', '--foo', ]
  790. successes = [
  791. ('a', NS(foo=[], bar=['a'])),
  792. ('a b', NS(foo=['a'], bar=['b'])),
  793. ('a b c', NS(foo=['a', 'b'], bar=['c'])),
  794. ]
  795. class TestPositionalsNargsOneOrMore1(ParserTestCase):
  796. """Test a Positional with one or more nargs followed by one with 1"""
  797. argument_signatures = [Sig('foo', nargs='+'), Sig('bar', nargs=1)]
  798. failures = ['', '--foo', 'a']
  799. successes = [
  800. ('a b', NS(foo=['a'], bar=['b'])),
  801. ('a b c', NS(foo=['a', 'b'], bar=['c'])),
  802. ]
  803. class TestPositionalsNargsOptional1(ParserTestCase):
  804. """Test a Positional with an Optional nargs followed by one with 1"""
  805. argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs=1)]
  806. failures = ['', '--foo', 'a b c']
  807. successes = [
  808. ('a', NS(foo=None, bar=['a'])),
  809. ('a b', NS(foo='a', bar=['b'])),
  810. ]
  811. class TestPositionalsNargsNoneZeroOrMore1(ParserTestCase):
  812. """Test three Positionals: no nargs, unlimited nargs and 1 nargs"""
  813. argument_signatures = [
  814. Sig('foo'),
  815. Sig('bar', nargs='*'),
  816. Sig('baz', nargs=1),
  817. ]
  818. failures = ['', '--foo', 'a']
  819. successes = [
  820. ('a b', NS(foo='a', bar=[], baz=['b'])),
  821. ('a b c', NS(foo='a', bar=['b'], baz=['c'])),
  822. ]
  823. class TestPositionalsNargsNoneOneOrMore1(ParserTestCase):
  824. """Test three Positionals: no nargs, one or more nargs and 1 nargs"""
  825. argument_signatures = [
  826. Sig('foo'),
  827. Sig('bar', nargs='+'),
  828. Sig('baz', nargs=1),
  829. ]
  830. failures = ['', '--foo', 'a', 'b']
  831. successes = [
  832. ('a b c', NS(foo='a', bar=['b'], baz=['c'])),
  833. ('a b c d', NS(foo='a', bar=['b', 'c'], baz=['d'])),
  834. ]
  835. class TestPositionalsNargsNoneOptional1(ParserTestCase):
  836. """Test three Positionals: no nargs, optional narg and 1 nargs"""
  837. argument_signatures = [
  838. Sig('foo'),
  839. Sig('bar', nargs='?', default=0.625),
  840. Sig('baz', nargs=1),
  841. ]
  842. failures = ['', '--foo', 'a']
  843. successes = [
  844. ('a b', NS(foo='a', bar=0.625, baz=['b'])),
  845. ('a b c', NS(foo='a', bar='b', baz=['c'])),
  846. ]
  847. class TestPositionalsNargsOptionalOptional(ParserTestCase):
  848. """Test two optional nargs"""
  849. argument_signatures = [
  850. Sig('foo', nargs='?'),
  851. Sig('bar', nargs='?', default=42),
  852. ]
  853. failures = ['--foo', 'a b c']
  854. successes = [
  855. ('', NS(foo=None, bar=42)),
  856. ('a', NS(foo='a', bar=42)),
  857. ('a b', NS(foo='a', bar='b')),
  858. ]
  859. class TestPositionalsNargsOptionalZeroOrMore(ParserTestCase):
  860. """Test an Optional narg followed by unlimited nargs"""
  861. argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs='*')]
  862. failures = ['--foo']
  863. successes = [
  864. ('', NS(foo=None, bar=[])),
  865. ('a', NS(foo='a', bar=[])),
  866. ('a b', NS(foo='a', bar=['b'])),
  867. ('a b c', NS(foo='a', bar=['b', 'c'])),
  868. ]
  869. class TestPositionalsNargsOptionalOneOrMore(ParserTestCase):
  870. """Test an Optional narg followed by one or more nargs"""
  871. argument_signatures = [Sig('foo', nargs='?'), Sig('bar', nargs='+')]
  872. failures = ['', '--foo']
  873. successes = [
  874. ('a', NS(foo=None, bar=['a'])),
  875. ('a b', NS(foo='a', bar=['b'])),
  876. ('a b c', NS(foo='a', bar=['b', 'c'])),
  877. ]
  878. class TestPositionalsChoicesString(ParserTestCase):
  879. """Test a set of single-character choices"""
  880. argument_signatures = [Sig('spam', choices=set('abcdefg'))]
  881. failures = ['', '--foo', 'h', '42', 'ef']
  882. successes = [
  883. ('a', NS(spam='a')),
  884. ('g', NS(spam='g')),
  885. ]
  886. class TestPositionalsChoicesInt(ParserTestCase):
  887. """Test a set of integer choices"""
  888. argument_signatures = [Sig('spam', type=int, choices=range(20))]
  889. failures = ['', '--foo', 'h', '42', 'ef']
  890. successes = [
  891. ('4', NS(spam=4)),
  892. ('15', NS(spam=15)),
  893. ]
  894. class TestPositionalsActionAppend(ParserTestCase):
  895. """Test the 'append' action"""
  896. argument_signatures = [
  897. Sig('spam', action='append'),
  898. Sig('spam', action='append', nargs=2),
  899. ]
  900. failures = ['', '--foo', 'a', 'a b', 'a b c d']
  901. successes = [
  902. ('a b c', NS(spam=['a', ['b', 'c']])),
  903. ]
  904. # ========================================
  905. # Combined optionals and positionals tests
  906. # ========================================
  907. class TestOptionalsNumericAndPositionals(ParserTestCase):
  908. """Tests negative number args when numeric options are present"""
  909. argument_signatures = [
  910. Sig('x', nargs='?'),
  911. Sig('-4', dest='y', action='store_true'),
  912. ]
  913. failures = ['-2', '-315']
  914. successes = [
  915. ('', NS(x=None, y=False)),
  916. ('a', NS(x='a', y=False)),
  917. ('-4', NS(x=None, y=True)),
  918. ('-4 a', NS(x='a', y=True)),
  919. ]
  920. class TestOptionalsAlmostNumericAndPositionals(ParserTestCase):
  921. """Tests negative number args when almost numeric options are present"""
  922. argument_signatures = [
  923. Sig('x', nargs='?'),
  924. Sig('-k4', dest='y', action='store_true'),
  925. ]
  926. failures = ['-k3']
  927. successes = [
  928. ('', NS(x=None, y=False)),
  929. ('-2', NS(x='-2', y=False)),
  930. ('a', NS(x='a', y=False)),
  931. ('-k4', NS(x=None, y=True)),
  932. ('-k4 a', NS(x='a', y=True)),
  933. ]
  934. class TestEmptyAndSpaceContainingArguments(ParserTestCase):
  935. argument_signatures = [
  936. Sig('x', nargs='?'),
  937. Sig('-y', '--yyy', dest='y'),
  938. ]
  939. failures = ['-y']
  940. successes = [
  941. ([''], NS(x='', y=None)),
  942. (['a badger'], NS(x='a badger', y=None)),
  943. (['-a badger'], NS(x='-a badger', y=None)),
  944. (['-y', ''], NS(x=None, y='')),
  945. (['-y', 'a badger'], NS(x=None, y='a badger')),
  946. (['-y', '-a badger'], NS(x=None, y='-a badger')),
  947. (['--yyy=a badger'], NS(x=None, y='a badger')),
  948. (['--yyy=-a badger'], NS(x=None, y='-a badger')),
  949. ]
  950. class TestPrefixCharacterOnlyArguments(ParserTestCase):
  951. parser_signature = Sig(prefix_chars='-+')
  952. argument_signatures = [
  953. Sig('-', dest='x', nargs='?', const='badger'),
  954. Sig('+', dest='y', type=int, default=42),
  955. Sig('-+-', dest='z', action='store_true'),
  956. ]
  957. failures = ['-y', '+ -']
  958. successes = [
  959. ('', NS(x=None, y=42, z=False)),
  960. ('-', NS(x='badger', y=42, z=False)),
  961. ('- X', NS(x='X', y=42, z=False)),
  962. ('+ -3', NS(x=None, y=-3, z=False)),
  963. ('-+-', NS(x=None, y=42, z=True)),
  964. ('- ===', NS(x='===', y=42, z=False)),
  965. ]
  966. class TestNargsZeroOrMore(ParserTestCase):
  967. """Tests specifying an args for an Optional that accepts zero or more"""
  968. argument_signatures = [Sig('-x', nargs='*'), Sig('y', nargs='*')]
  969. failures = []
  970. successes = [
  971. ('', NS(x=None, y=[])),
  972. ('-x', NS(x=[], y=[])),
  973. ('-x a', NS(x=['a'], y=[])),
  974. ('-x a -- b', NS(x=['a'], y=['b'])),
  975. ('a', NS(x=None, y=['a'])),
  976. ('a -x', NS(x=[], y=['a'])),
  977. ('a -x b', NS(x=['b'], y=['a'])),
  978. ]
  979. class TestNargsRemainder(ParserTestCase):
  980. """Tests specifying a positional with nargs=REMAINDER"""
  981. argument_signatures = [Sig('x'), Sig('y', nargs='...'), Sig('-z')]
  982. failures = ['', '-z', '-z Z']
  983. successes = [
  984. ('X', NS(x='X', y=[], z=None)),
  985. ('-z Z X', NS(x='X', y=[], z='Z')),
  986. ('X A B -z Z', NS(x='X', y=['A', 'B', '-z', 'Z'], z=None)),
  987. ('X Y --foo', NS(x='X', y=['Y', '--foo'], z=None)),
  988. ]
  989. class TestOptionLike(ParserTestCase):
  990. """Tests options that may or may not be arguments"""
  991. argument_signatures = [
  992. Sig('-x', type=float),
  993. Sig('-3', type=float, dest='y'),
  994. Sig('z', nargs='*'),
  995. ]
  996. failures = ['-x', '-y2.5', '-xa', '-x -a',
  997. '-x -3', '-x -3.5', '-3 -3.5',
  998. '-x -2.5', '-x -2.5 a', '-3 -.5',
  999. 'a x -1', '-x -1 a', '-3 -1 a']
  1000. successes = [
  1001. ('', NS(x=None, y=None, z=[])),
  1002. ('-x 2.5', NS(x=2.5, y=None, z=[])),
  1003. ('-x 2.5 a', NS(x=2.5, y=None, z=['a'])),
  1004. ('-3.5', NS(x=None, y=0.5, z=[])),
  1005. ('-3-.5', NS(x=None, y=-0.5, z=[])),
  1006. ('-3 .5', NS(x=None, y=0.5, z=[])),
  1007. ('a -3.5', NS(x=None, y=0.5, z=['a'])),
  1008. ('a', NS(x=None, y=None, z=['a'])),
  1009. ('a -x 1', NS(x=1.0, y=None, z=['a'])),
  1010. ('-x 1 a', NS(x=1.0, y=None, z=['a'])),
  1011. ('-3 1 a', NS(x=None, y=1.0, z=['a'])),
  1012. ]
  1013. class TestDefaultSuppress(ParserTestCase):
  1014. """Test actions with suppressed defaults"""
  1015. argument_signatures = [
  1016. Sig('foo', nargs='?', default=argparse.SUPPRESS),
  1017. Sig('bar', nargs='*', default=argparse.SUPPRESS),
  1018. Sig('--baz', action='store_true', default=argparse.SUPPRESS),
  1019. ]
  1020. failures = ['-x']
  1021. successes = [
  1022. ('', NS()),
  1023. ('a', NS(foo='a')),
  1024. ('a b', NS(foo='a', bar=['b'])),
  1025. ('--baz', NS(baz=True)),
  1026. ('a --baz', NS(foo='a', baz=True)),
  1027. ('--baz a b', NS(foo='a', bar=['b'], baz=True)),
  1028. ]
  1029. class TestParserDefaultSuppress(ParserTestCase):
  1030. """Test actions with a parser-level default of SUPPRESS"""
  1031. parser_signature = Sig(argument_default=argparse.SUPPRESS)
  1032. argument_signatures = [
  1033. Sig('foo', nargs='?'),
  1034. Sig('bar', nargs='*'),
  1035. Sig('--baz', action='store_true'),
  1036. ]
  1037. failures = ['-x']
  1038. successes = [
  1039. ('', NS()),
  1040. ('a', NS(foo='a')),
  1041. ('a b', NS(foo='a', bar=['b'])),
  1042. ('--baz', NS(baz=True)),
  1043. ('a --baz', NS(foo='a', baz=True)),
  1044. ('--baz a b', NS(foo='a', bar=['b'], baz=True)),
  1045. ]
  1046. class TestParserDefault42(ParserTestCase):
  1047. """Test actions with a parser-level default of 42"""
  1048. parser_signature = Sig(argument_default=42, version='1.0')
  1049. argument_signatures = [
  1050. Sig('foo', nargs='?'),
  1051. Sig('bar', nargs='*'),
  1052. Sig('--baz', action='store_true'),
  1053. ]
  1054. failures = ['-x']
  1055. successes = [
  1056. ('', NS(foo=42, bar=42, baz=42)),
  1057. ('a', NS(foo='a', bar=42, baz=42)),
  1058. ('a b', NS(foo='a', bar=['b'], baz=42)),
  1059. ('--baz', NS(foo=42, bar=42, baz=True)),
  1060. ('a --baz', NS(foo='a', bar=42, baz=True)),
  1061. ('--baz a b', NS(foo='a', bar=['b'], baz=True)),
  1062. ]
  1063. class TestArgumentsFromFile(TempDirMixin, ParserTestCase):
  1064. """Test reading arguments from a file"""
  1065. def setUp(self):
  1066. super(TestArgumentsFromFile, self).setUp()
  1067. file_texts = [
  1068. ('hello', 'hello world!\n'),
  1069. ('recursive', '-a\n'
  1070. 'A\n'
  1071. '@hello'),
  1072. ('invalid', '@no-such-path\n'),
  1073. ]
  1074. for path, text in file_texts:
  1075. file = open(path, 'w')
  1076. file.write(text)
  1077. file.close()
  1078. parser_signature = Sig(fromfile_prefix_chars='@')
  1079. argument_signatures = [
  1080. Sig('-a'),
  1081. Sig('x'),
  1082. Sig('y', nargs='+'),
  1083. ]
  1084. failures = ['', '-b', 'X', '@invalid', '@missing']
  1085. successes = [
  1086. ('X Y', NS(a=None, x='X', y=['Y'])),
  1087. ('X -a A Y Z', NS(a='A', x='X', y=['Y', 'Z'])),
  1088. ('@hello X', NS(a=None, x='hello world!', y=['X'])),
  1089. ('X @hello', NS(a=None, x='X', y=['hello world!'])),
  1090. ('-a B @recursive Y Z', NS(a='A', x='hello world!', y=['Y', 'Z'])),
  1091. ('X @recursive Z -a B', NS(a='B', x='X', y=['hello world!', 'Z'])),
  1092. ]
  1093. class TestArgumentsFromFileConverter(TempDirMixin, ParserTestCase):
  1094. """Test reading arguments from a file"""
  1095. def setUp(self):
  1096. super(TestArgumentsFromFileConverter, self).setUp()
  1097. file_texts = [
  1098. ('hello', 'hello world!\n'),
  1099. ]
  1100. for path, text in file_texts:
  1101. file = open(path, 'w')
  1102. file.write(text)
  1103. file.close()
  1104. class FromFileConverterArgumentParser(ErrorRaisingArgumentParser):
  1105. def convert_arg_line_to_args(self, arg_line):
  1106. for arg in arg_line.split():
  1107. if not arg.strip():
  1108. continue
  1109. yield arg
  1110. parser_class = FromFileConverterArgumentParser
  1111. parser_signature = Sig(fromfile_prefix_chars='@')
  1112. argument_signatures = [
  1113. Sig('y', nargs='+'),
  1114. ]
  1115. failures = []
  1116. successes = [
  1117. ('@hello X', NS(y=['hello', 'world!', 'X'])),
  1118. ]
  1119. # =====================
  1120. # Type conversion tests
  1121. # =====================
  1122. class TestFileTypeRepr(TestCase):
  1123. def test_r(self):
  1124. type = argparse.FileType('r')
  1125. self.assertEqual("FileType('r')", repr(type))
  1126. def test_wb_1(self):
  1127. type = argparse.FileType('wb', 1)
  1128. self.assertEqual("FileType('wb', 1)", repr(type))
  1129. class RFile(object):
  1130. seen = {}
  1131. def __init__(self, name):
  1132. self.name = name
  1133. __hash__ = None
  1134. def __eq__(self, other):
  1135. if other in self.seen:
  1136. text = self.seen[other]
  1137. else:
  1138. text = self.seen[other] = other.read()
  1139. other.close()
  1140. if not isinstance(text, str):
  1141. text = text.decode('ascii')
  1142. return self.name == other.name == text
  1143. class TestFileTypeR(TempDirMixin, ParserTestCase):
  1144. """Test the FileType option/argument type for reading files"""
  1145. def setUp(self):
  1146. super(TestFileTypeR, self).setUp()
  1147. for file_name in ['foo', 'bar']:
  1148. file = open(os.path.join(self.temp_dir, file_name), 'w')
  1149. file.write(file_name)
  1150. file.close()
  1151. self.create_readonly_file('readonly')
  1152. argument_signatures = [
  1153. Sig('-x', type=argparse.FileType()),
  1154. Sig('spam', type=argparse.FileType('r')),
  1155. ]
  1156. failures = ['-x', '-x bar', 'non-existent-file.txt']
  1157. successes = [
  1158. ('foo', NS(x=None, spam=RFile('foo'))),
  1159. ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
  1160. ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
  1161. ('-x - -', NS(x=sys.stdin, spam=sys.stdin)),
  1162. ('readonly', NS(x=None, spam=RFile('readonly'))),
  1163. ]
  1164. class TestFileTypeRB(TempDirMixin, ParserTestCase):
  1165. """Test the FileType option/argument type for reading files"""
  1166. def setUp(self):
  1167. super(TestFileTypeRB, self).setUp()
  1168. for file_name in ['foo', 'bar']:
  1169. file = open(os.path.join(self.temp_dir, file_name), 'w')
  1170. file.write(file_name)
  1171. file.close()
  1172. argument_signatures = [
  1173. Sig('-x', type=argparse.FileType('rb')),
  1174. Sig('spam', type=argparse.FileType('rb')),
  1175. ]
  1176. failures = ['-x', '-x bar']
  1177. successes = [
  1178. ('foo', NS(x=None, spam=RFile('foo'))),
  1179. ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
  1180. ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
  1181. ('-x - -', NS(x=sys.stdin, spam=sys.stdin)),
  1182. ]
  1183. class WFile(object):
  1184. seen = set()
  1185. def __init__(self, name):
  1186. self.name = name
  1187. __hash__ = None
  1188. def __eq__(self, other):
  1189. if other not in self.seen:
  1190. text = 'Check that file is writable.'
  1191. if 'b' in other.mode:
  1192. text = text.encode('ascii')
  1193. other.write(text)
  1194. other.close()
  1195. self.seen.add(other)
  1196. return self.name == other.name
  1197. class TestFileTypeW(TempDirMixin, ParserTestCase):
  1198. """Test the FileType option/argument type for writing files"""
  1199. def setUp(self):
  1200. super(TestFileTypeW, self).setUp()
  1201. self.create_readonly_file('readonly')
  1202. argument_signatures = [
  1203. Sig('-x', type=argparse.FileType('w')),
  1204. Sig('spam', type=argparse.FileType('w')),
  1205. ]
  1206. failures = ['-x', '-x bar']
  1207. failures = ['-x', '-x bar', 'readonly']
  1208. successes = [
  1209. ('foo', NS(x=None, spam=WFile('foo'))),
  1210. ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
  1211. ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))),
  1212. ('-x - -', NS(x=sys.stdout, spam=sys.stdout)),
  1213. ]
  1214. class TestFileTypeWB(TempDirMixin, ParserTestCase):
  1215. argument_signatures = [
  1216. Sig('-x', type=argparse.FileType('wb')),
  1217. Sig('spam', type=argparse.FileType('wb')),
  1218. ]
  1219. failures = ['-x', '-x bar']
  1220. successes = [
  1221. ('foo', NS(x=None, spam=WFile('foo'))),
  1222. ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
  1223. ('bar -x foo', NS(x=WFile('foo'), spam=WFile('bar'))),
  1224. ('-x - -', NS(x=sys.stdout, spam=sys.stdout)),
  1225. ]
  1226. class TestTypeCallable(ParserTestCase):
  1227. """Test some callables as option/argument types"""
  1228. argument_signatures = [
  1229. Sig('--eggs', type=complex),
  1230. Sig('spam', type=float),
  1231. ]
  1232. failures = ['a', '42j', '--eggs a', '--eggs 2i']
  1233. successes = [
  1234. ('--eggs=42 42', NS(eggs=42, spam=42.0)),
  1235. ('--eggs 2j -- -1.5', NS(eggs=2j, spam=-1.5)),
  1236. ('1024.675', NS(eggs=None, spam=1024.675)),
  1237. ]
  1238. class TestTypeUserDefined(ParserTestCase):
  1239. """Test a user-defined option/argument type"""
  1240. class MyType(TestCase):
  1241. def __init__(self, value):
  1242. self.value = value
  1243. __hash__ = None
  1244. def __eq__(self, other):
  1245. return (type(self), self.value) == (type(other), other.value)
  1246. argument_signatures = [
  1247. Sig('-x', type=MyType),
  1248. Sig('spam', type=MyType),
  1249. ]
  1250. failures = []
  1251. successes = [
  1252. ('a -x b', NS(x=MyType('b'), spam=MyType('a'))),
  1253. ('-xf g', NS(x=MyType('f'), spam=MyType('g'))),
  1254. ]
  1255. class TestTypeClassicClass(ParserTestCase):
  1256. """Test a classic class type"""
  1257. class C:
  1258. def __init__(self, value):
  1259. self.value = value
  1260. __hash__ = None
  1261. def __eq__(self, other):
  1262. return (type(self), self.value) == (type(other), other.value)
  1263. argument_signatures = [
  1264. Sig('-x', type=C),
  1265. Sig('spam', type=C),
  1266. ]
  1267. failures = []
  1268. successes = [
  1269. ('a -x b', NS(x=C('b'), spam=C('a'))),
  1270. ('-xf g', NS(x=C('f'), spam=C('g'))),
  1271. ]
  1272. class TestTypeRegistration(TestCase):
  1273. """Test a user-defined type by registering it"""
  1274. def test(self):
  1275. def get_my_type(string):
  1276. return '…

Large files files are truncated, but you can click here to view the full file