blob: 8486c79e8a985be0935566b89fbeff9f76fd7598 [file] [log] [blame]
Greg Ward55493222003-04-21 02:41:25 +00001#
2# Test suite for Optik. Supplied by Johannes Gijsbers
3# (taradino@softhome.net) -- translated from the original Optik
4# test suite to this PyUnit-based version.
5#
6# $Id$
7#
8
9import sys
10import os
Thomas Wouters477c8d52006-05-27 19:21:47 +000011import re
Greg Ward55493222003-04-21 02:41:25 +000012import copy
13import unittest
14
Guido van Rossum34d19282007-08-09 01:03:29 +000015from io import StringIO
Benjamin Petersonee8712c2008-05-20 21:35:26 +000016from test import support
Greg Ward55493222003-04-21 02:41:25 +000017
Thomas Wouters477c8d52006-05-27 19:21:47 +000018
Georg Brandl1b37e872010-03-14 10:45:50 +000019from optparse import make_option, Option, \
20 TitledHelpFormatter, OptionParser, OptionGroup, \
21 SUPPRESS_USAGE, OptionError, OptionConflictError, \
Thomas Wouters477c8d52006-05-27 19:21:47 +000022 BadOptionError, OptionValueError, Values
23from optparse import _match_abbrev
24from optparse import _parse_num
Greg Ward48aa84b2004-10-27 02:20:04 +000025
Thomas Wouters477c8d52006-05-27 19:21:47 +000026retype = type(re.compile(''))
Greg Ward48aa84b2004-10-27 02:20:04 +000027
28class InterceptedError(Exception):
29 def __init__(self,
30 error_message=None,
31 exit_status=None,
32 exit_message=None):
33 self.error_message = error_message
34 self.exit_status = exit_status
35 self.exit_message = exit_message
36
37 def __str__(self):
38 return self.error_message or self.exit_message or "intercepted error"
39
40class InterceptingOptionParser(OptionParser):
41 def exit(self, status=0, msg=None):
42 raise InterceptedError(exit_status=status, exit_message=msg)
43
44 def error(self, msg):
45 raise InterceptedError(error_message=msg)
46
Greg Ward55493222003-04-21 02:41:25 +000047
48class BaseTest(unittest.TestCase):
49 def assertParseOK(self, args, expected_opts, expected_positional_args):
50 """Assert the options are what we expected when parsing arguments.
51
52 Otherwise, fail with a nicely formatted message.
53
54 Keyword arguments:
55 args -- A list of arguments to parse with OptionParser.
56 expected_opts -- The options expected.
57 expected_positional_args -- The positional arguments expected.
58
59 Returns the options and positional args for further testing.
60 """
61
62 (options, positional_args) = self.parser.parse_args(args)
63 optdict = vars(options)
64
65 self.assertEqual(optdict, expected_opts,
66 """
67Options are %(optdict)s.
68Should be %(expected_opts)s.
69Args were %(args)s.""" % locals())
70
71 self.assertEqual(positional_args, expected_positional_args,
72 """
73Positional arguments are %(positional_args)s.
74Should be %(expected_positional_args)s.
75Args were %(args)s.""" % locals ())
76
77 return (options, positional_args)
78
Greg Wardeba20e62004-07-31 16:15:44 +000079 def assertRaises(self,
80 func,
81 args,
82 kwargs,
83 expected_exception,
Greg Ward48aa84b2004-10-27 02:20:04 +000084 expected_message):
85 """
86 Assert that the expected exception is raised when calling a
87 function, and that the right error message is included with
88 that exception.
Greg Ward55493222003-04-21 02:41:25 +000089
Greg Wardeba20e62004-07-31 16:15:44 +000090 Arguments:
91 func -- the function to call
92 args -- positional arguments to `func`
93 kwargs -- keyword arguments to `func`
94 expected_exception -- exception that should be raised
Thomas Wouters477c8d52006-05-27 19:21:47 +000095 expected_message -- expected exception message (or pattern
96 if a compiled regex object)
Greg Ward55493222003-04-21 02:41:25 +000097
98 Returns the exception raised for further testing.
99 """
Greg Wardeba20e62004-07-31 16:15:44 +0000100 if args is None:
101 args = ()
102 if kwargs is None:
103 kwargs = {}
Greg Ward55493222003-04-21 02:41:25 +0000104
105 try:
Greg Ward48aa84b2004-10-27 02:20:04 +0000106 func(*args, **kwargs)
Guido van Rossumb940e112007-01-10 16:19:56 +0000107 except expected_exception as err:
Greg Ward48aa84b2004-10-27 02:20:04 +0000108 actual_message = str(err)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000109 if isinstance(expected_message, retype):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000110 self.assertTrue(expected_message.search(actual_message),
Greg Ward48aa84b2004-10-27 02:20:04 +0000111 """\
Thomas Wouters477c8d52006-05-27 19:21:47 +0000112expected exception message pattern:
113/%s/
Greg Ward48aa84b2004-10-27 02:20:04 +0000114actual exception message:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000115'''%s'''
116""" % (expected_message.pattern, actual_message))
117 else:
118 self.assertEqual(actual_message,
119 expected_message,
120 """\
121expected exception message:
122'''%s'''
123actual exception message:
124'''%s'''
125""" % (expected_message, actual_message))
Greg Ward55493222003-04-21 02:41:25 +0000126
127 return err
128 else:
Greg Wardeba20e62004-07-31 16:15:44 +0000129 self.fail("""expected exception %(expected_exception)s not raised
130called %(func)r
131with args %(args)r
132and kwargs %(kwargs)r
133""" % locals ())
Greg Ward55493222003-04-21 02:41:25 +0000134
Greg Wardeba20e62004-07-31 16:15:44 +0000135
Greg Ward55493222003-04-21 02:41:25 +0000136 # -- Assertions used in more than one class --------------------
137
138 def assertParseFail(self, cmdline_args, expected_output):
Greg Ward48aa84b2004-10-27 02:20:04 +0000139 """
140 Assert the parser fails with the expected message. Caller
141 must ensure that self.parser is an InterceptingOptionParser.
142 """
Tim Peters579f7352004-07-31 21:14:28 +0000143 try:
Greg Ward48aa84b2004-10-27 02:20:04 +0000144 self.parser.parse_args(cmdline_args)
Guido van Rossumb940e112007-01-10 16:19:56 +0000145 except InterceptedError as err:
Greg Ward48aa84b2004-10-27 02:20:04 +0000146 self.assertEqual(err.error_message, expected_output)
147 else:
148 self.assertFalse("expected parse failure")
Greg Ward55493222003-04-21 02:41:25 +0000149
Greg Ward48aa84b2004-10-27 02:20:04 +0000150 def assertOutput(self,
151 cmdline_args,
152 expected_output,
153 expected_status=0,
154 expected_error=None):
Greg Ward55493222003-04-21 02:41:25 +0000155 """Assert the parser prints the expected output on stdout."""
Tim Peters579f7352004-07-31 21:14:28 +0000156 save_stdout = sys.stdout
157 try:
Greg Ward48aa84b2004-10-27 02:20:04 +0000158 try:
159 sys.stdout = StringIO()
160 self.parser.parse_args(cmdline_args)
161 finally:
162 output = sys.stdout.getvalue()
163 sys.stdout = save_stdout
Greg Ward55493222003-04-21 02:41:25 +0000164
Guido van Rossumb940e112007-01-10 16:19:56 +0000165 except InterceptedError as err:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000166 self.assertTrue(
Guido van Rossum13257902007-06-07 23:15:56 +0000167 isinstance(output, str),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000168 "expected output to be an ordinary string, not %r"
169 % type(output))
170
Thomas Wouters477c8d52006-05-27 19:21:47 +0000171 if output != expected_output:
172 self.fail("expected: \n'''\n" + expected_output +
173 "'''\nbut got \n'''\n" + output + "'''")
Greg Ward48aa84b2004-10-27 02:20:04 +0000174 self.assertEqual(err.exit_status, expected_status)
175 self.assertEqual(err.exit_message, expected_error)
176 else:
177 self.assertFalse("expected parser.exit()")
178
179 def assertTypeError(self, func, expected_message, *args):
180 """Assert that TypeError is raised when executing func."""
181 self.assertRaises(func, args, None, TypeError, expected_message)
Greg Wardeba20e62004-07-31 16:15:44 +0000182
183 def assertHelp(self, parser, expected_help):
184 actual_help = parser.format_help()
185 if actual_help != expected_help:
186 raise self.failureException(
187 'help text failure; expected:\n"' +
188 expected_help + '"; got:\n"' +
189 actual_help + '"\n')
Greg Ward55493222003-04-21 02:41:25 +0000190
191# -- Test make_option() aka Option -------------------------------------
192
Greg Ward48aa84b2004-10-27 02:20:04 +0000193# It's not necessary to test correct options here. All the tests in the
Greg Ward55493222003-04-21 02:41:25 +0000194# parser.parse_args() section deal with those, because they're needed
Greg Ward48aa84b2004-10-27 02:20:04 +0000195# there.
Greg Ward55493222003-04-21 02:41:25 +0000196
197class TestOptionChecks(BaseTest):
198 def setUp(self):
199 self.parser = OptionParser(usage=SUPPRESS_USAGE)
200
Greg Ward48aa84b2004-10-27 02:20:04 +0000201 def assertOptionError(self, expected_message, args=[], kwargs={}):
Greg Wardeba20e62004-07-31 16:15:44 +0000202 self.assertRaises(make_option, args, kwargs,
Greg Ward48aa84b2004-10-27 02:20:04 +0000203 OptionError, expected_message)
Greg Ward55493222003-04-21 02:41:25 +0000204
205 def test_opt_string_empty(self):
206 self.assertTypeError(make_option,
207 "at least one option string must be supplied")
208
209 def test_opt_string_too_short(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000210 self.assertOptionError(
211 "invalid option string 'b': must be at least two characters long",
212 ["b"])
Greg Ward55493222003-04-21 02:41:25 +0000213
214 def test_opt_string_short_invalid(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000215 self.assertOptionError(
216 "invalid short option string '--': must be "
217 "of the form -x, (x any non-dash char)",
218 ["--"])
Greg Ward55493222003-04-21 02:41:25 +0000219
220 def test_opt_string_long_invalid(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000221 self.assertOptionError(
222 "invalid long option string '---': "
223 "must start with --, followed by non-dash",
224 ["---"])
Greg Ward55493222003-04-21 02:41:25 +0000225
226 def test_attr_invalid(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000227 self.assertOptionError(
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000228 "option -b: invalid keyword arguments: bar, foo",
Greg Ward48aa84b2004-10-27 02:20:04 +0000229 ["-b"], {'foo': None, 'bar': None})
Greg Ward55493222003-04-21 02:41:25 +0000230
231 def test_action_invalid(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000232 self.assertOptionError(
233 "option -b: invalid action: 'foo'",
234 ["-b"], {'action': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000235
236 def test_type_invalid(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000237 self.assertOptionError(
238 "option -b: invalid option type: 'foo'",
239 ["-b"], {'type': 'foo'})
240 self.assertOptionError(
241 "option -b: invalid option type: 'tuple'",
242 ["-b"], {'type': tuple})
Greg Ward55493222003-04-21 02:41:25 +0000243
244 def test_no_type_for_action(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000245 self.assertOptionError(
246 "option -b: must not supply a type for action 'count'",
247 ["-b"], {'action': 'count', 'type': 'int'})
Greg Ward55493222003-04-21 02:41:25 +0000248
249 def test_no_choices_list(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000250 self.assertOptionError(
251 "option -b/--bad: must supply a list of "
252 "choices for type 'choice'",
253 ["-b", "--bad"], {'type': "choice"})
Greg Ward55493222003-04-21 02:41:25 +0000254
255 def test_bad_choices_list(self):
256 typename = type('').__name__
Greg Ward48aa84b2004-10-27 02:20:04 +0000257 self.assertOptionError(
258 "option -b/--bad: choices must be a list of "
259 "strings ('%s' supplied)" % typename,
260 ["-b", "--bad"],
261 {'type': "choice", 'choices':"bad choices"})
Greg Ward55493222003-04-21 02:41:25 +0000262
263 def test_no_choices_for_type(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000264 self.assertOptionError(
265 "option -b: must not supply choices for type 'int'",
266 ["-b"], {'type': 'int', 'choices':"bad"})
Greg Ward55493222003-04-21 02:41:25 +0000267
268 def test_no_const_for_action(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000269 self.assertOptionError(
270 "option -b: 'const' must not be supplied for action 'store'",
271 ["-b"], {'action': 'store', 'const': 1})
Greg Ward55493222003-04-21 02:41:25 +0000272
273 def test_no_nargs_for_action(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000274 self.assertOptionError(
275 "option -b: 'nargs' must not be supplied for action 'count'",
276 ["-b"], {'action': 'count', 'nargs': 2})
Greg Ward55493222003-04-21 02:41:25 +0000277
278 def test_callback_not_callable(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000279 self.assertOptionError(
280 "option -b: callback not callable: 'foo'",
281 ["-b"], {'action': 'callback',
282 'callback': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000283
284 def dummy(self):
285 pass
286
287 def test_callback_args_no_tuple(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000288 self.assertOptionError(
289 "option -b: callback_args, if supplied, "
290 "must be a tuple: not 'foo'",
291 ["-b"], {'action': 'callback',
292 'callback': self.dummy,
293 'callback_args': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000294
295 def test_callback_kwargs_no_dict(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000296 self.assertOptionError(
297 "option -b: callback_kwargs, if supplied, "
298 "must be a dict: not 'foo'",
299 ["-b"], {'action': 'callback',
300 'callback': self.dummy,
301 'callback_kwargs': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000302
303 def test_no_callback_for_action(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000304 self.assertOptionError(
305 "option -b: callback supplied ('foo') for non-callback option",
306 ["-b"], {'action': 'store',
307 'callback': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000308
309 def test_no_callback_args_for_action(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000310 self.assertOptionError(
311 "option -b: callback_args supplied for non-callback option",
312 ["-b"], {'action': 'store',
313 'callback_args': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000314
315 def test_no_callback_kwargs_for_action(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000316 self.assertOptionError(
317 "option -b: callback_kwargs supplied for non-callback option",
318 ["-b"], {'action': 'store',
319 'callback_kwargs': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000320
321class TestOptionParser(BaseTest):
322 def setUp(self):
323 self.parser = OptionParser()
324 self.parser.add_option("-v", "--verbose", "-n", "--noisy",
325 action="store_true", dest="verbose")
326 self.parser.add_option("-q", "--quiet", "--silent",
327 action="store_false", dest="verbose")
328
329 def test_add_option_no_Option(self):
330 self.assertTypeError(self.parser.add_option,
331 "not an Option instance: None", None)
332
333 def test_add_option_invalid_arguments(self):
334 self.assertTypeError(self.parser.add_option,
335 "invalid arguments", None, None)
336
337 def test_get_option(self):
338 opt1 = self.parser.get_option("-v")
Ezio Melottie9615932010-01-24 19:26:24 +0000339 self.assertIsInstance(opt1, Option)
Greg Ward55493222003-04-21 02:41:25 +0000340 self.assertEqual(opt1._short_opts, ["-v", "-n"])
341 self.assertEqual(opt1._long_opts, ["--verbose", "--noisy"])
342 self.assertEqual(opt1.action, "store_true")
343 self.assertEqual(opt1.dest, "verbose")
344
345 def test_get_option_equals(self):
346 opt1 = self.parser.get_option("-v")
347 opt2 = self.parser.get_option("--verbose")
348 opt3 = self.parser.get_option("-n")
349 opt4 = self.parser.get_option("--noisy")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000350 self.assertTrue(opt1 is opt2 is opt3 is opt4)
Greg Ward55493222003-04-21 02:41:25 +0000351
352 def test_has_option(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000353 self.assertTrue(self.parser.has_option("-v"))
354 self.assertTrue(self.parser.has_option("--verbose"))
Greg Ward55493222003-04-21 02:41:25 +0000355
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000356 def assertTrueremoved(self):
357 self.assertTrue(self.parser.get_option("-v") is None)
358 self.assertTrue(self.parser.get_option("--verbose") is None)
359 self.assertTrue(self.parser.get_option("-n") is None)
360 self.assertTrue(self.parser.get_option("--noisy") is None)
Greg Ward55493222003-04-21 02:41:25 +0000361
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000362 self.assertFalse(self.parser.has_option("-v"))
363 self.assertFalse(self.parser.has_option("--verbose"))
364 self.assertFalse(self.parser.has_option("-n"))
365 self.assertFalse(self.parser.has_option("--noisy"))
Greg Ward55493222003-04-21 02:41:25 +0000366
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000367 self.assertTrue(self.parser.has_option("-q"))
368 self.assertTrue(self.parser.has_option("--silent"))
Greg Ward55493222003-04-21 02:41:25 +0000369
370 def test_remove_short_opt(self):
371 self.parser.remove_option("-n")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000372 self.assertTrueremoved()
Greg Ward55493222003-04-21 02:41:25 +0000373
374 def test_remove_long_opt(self):
375 self.parser.remove_option("--verbose")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000376 self.assertTrueremoved()
Greg Ward55493222003-04-21 02:41:25 +0000377
378 def test_remove_nonexistent(self):
Greg Wardeba20e62004-07-31 16:15:44 +0000379 self.assertRaises(self.parser.remove_option, ('foo',), None,
380 ValueError, "no such option 'foo'")
381
Thomas Wouters477c8d52006-05-27 19:21:47 +0000382 def test_refleak(self):
383 # If an OptionParser is carrying around a reference to a large
384 # object, various cycles can prevent it from being GC'd in
385 # a timely fashion. destroy() breaks the cycles to ensure stuff
386 # can be cleaned up.
387 big_thing = [42]
388 refcount = sys.getrefcount(big_thing)
389 parser = OptionParser()
390 parser.add_option("-a", "--aaarggh")
391 parser.big_thing = big_thing
392
393 parser.destroy()
394 #self.assertEqual(refcount, sys.getrefcount(big_thing))
395 del parser
396 self.assertEqual(refcount, sys.getrefcount(big_thing))
397
398
Greg Ward48aa84b2004-10-27 02:20:04 +0000399class TestOptionValues(BaseTest):
400 def setUp(self):
401 pass
402
403 def test_basics(self):
404 values = Values()
405 self.assertEqual(vars(values), {})
406 self.assertEqual(values, {})
407 self.assertNotEqual(values, {"foo": "bar"})
408 self.assertNotEqual(values, "")
409
410 dict = {"foo": "bar", "baz": 42}
411 values = Values(defaults=dict)
412 self.assertEqual(vars(values), dict)
413 self.assertEqual(values, dict)
414 self.assertNotEqual(values, {"foo": "bar"})
415 self.assertNotEqual(values, {})
416 self.assertNotEqual(values, "")
417 self.assertNotEqual(values, [])
418
419
Greg Wardeba20e62004-07-31 16:15:44 +0000420class TestTypeAliases(BaseTest):
421 def setUp(self):
422 self.parser = OptionParser()
423
Thomas Wouters477c8d52006-05-27 19:21:47 +0000424 def test_str_aliases_string(self):
425 self.parser.add_option("-s", type="str")
Greg Wardeba20e62004-07-31 16:15:44 +0000426 self.assertEquals(self.parser.get_option("-s").type, "string")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000427
Guido van Rossum13257902007-06-07 23:15:56 +0000428 def test_type_object(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000429 self.parser.add_option("-s", type=str)
430 self.assertEquals(self.parser.get_option("-s").type, "string")
431 self.parser.add_option("-x", type=int)
432 self.assertEquals(self.parser.get_option("-x").type, "int")
433
Greg Wardeba20e62004-07-31 16:15:44 +0000434
435# Custom type for testing processing of default values.
436_time_units = { 's' : 1, 'm' : 60, 'h' : 60*60, 'd' : 60*60*24 }
437
438def _check_duration(option, opt, value):
439 try:
440 if value[-1].isdigit():
441 return int(value)
442 else:
443 return int(value[:-1]) * _time_units[value[-1]]
Georg Brandl89fad142010-03-14 10:23:39 +0000444 except (ValueError, IndexError):
Greg Wardeba20e62004-07-31 16:15:44 +0000445 raise OptionValueError(
446 'option %s: invalid duration: %r' % (opt, value))
447
448class DurationOption(Option):
449 TYPES = Option.TYPES + ('duration',)
450 TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
451 TYPE_CHECKER['duration'] = _check_duration
452
453class TestDefaultValues(BaseTest):
454 def setUp(self):
455 self.parser = OptionParser()
456 self.parser.add_option("-v", "--verbose", default=True)
457 self.parser.add_option("-q", "--quiet", dest='verbose')
458 self.parser.add_option("-n", type="int", default=37)
459 self.parser.add_option("-m", type="int")
460 self.parser.add_option("-s", default="foo")
461 self.parser.add_option("-t")
462 self.parser.add_option("-u", default=None)
463 self.expected = { 'verbose': True,
464 'n': 37,
465 'm': None,
466 's': "foo",
467 't': None,
468 'u': None }
469
470 def test_basic_defaults(self):
471 self.assertEqual(self.parser.get_default_values(), self.expected)
472
473 def test_mixed_defaults_post(self):
474 self.parser.set_defaults(n=42, m=-100)
475 self.expected.update({'n': 42, 'm': -100})
476 self.assertEqual(self.parser.get_default_values(), self.expected)
477
478 def test_mixed_defaults_pre(self):
479 self.parser.set_defaults(x="barf", y="blah")
480 self.parser.add_option("-x", default="frob")
481 self.parser.add_option("-y")
482
483 self.expected.update({'x': "frob", 'y': "blah"})
484 self.assertEqual(self.parser.get_default_values(), self.expected)
485
486 self.parser.remove_option("-y")
487 self.parser.add_option("-y", default=None)
488 self.expected.update({'y': None})
489 self.assertEqual(self.parser.get_default_values(), self.expected)
490
491 def test_process_default(self):
492 self.parser.option_class = DurationOption
493 self.parser.add_option("-d", type="duration", default=300)
494 self.parser.add_option("-e", type="duration", default="6m")
495 self.parser.set_defaults(n="42")
496 self.expected.update({'d': 300, 'e': 360, 'n': 42})
497 self.assertEqual(self.parser.get_default_values(), self.expected)
498
499 self.parser.set_process_default_values(False)
500 self.expected.update({'d': 300, 'e': "6m", 'n': "42"})
501 self.assertEqual(self.parser.get_default_values(), self.expected)
502
503
504class TestProgName(BaseTest):
505 """
506 Test that %prog expands to the right thing in usage, version,
507 and help strings.
508 """
509
510 def assertUsage(self, parser, expected_usage):
511 self.assertEqual(parser.get_usage(), expected_usage)
512
513 def assertVersion(self, parser, expected_version):
514 self.assertEqual(parser.get_version(), expected_version)
515
516
517 def test_default_progname(self):
518 # Make sure that program name taken from sys.argv[0] by default.
Tim Peters579f7352004-07-31 21:14:28 +0000519 save_argv = sys.argv[:]
520 try:
Greg Ward48aa84b2004-10-27 02:20:04 +0000521 sys.argv[0] = os.path.join("foo", "bar", "baz.py")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000522 parser = OptionParser("%prog ...", version="%prog 1.2")
523 expected_usage = "Usage: baz.py ...\n"
Tim Peters579f7352004-07-31 21:14:28 +0000524 self.assertUsage(parser, expected_usage)
525 self.assertVersion(parser, "baz.py 1.2")
526 self.assertHelp(parser,
Greg Ward48aa84b2004-10-27 02:20:04 +0000527 expected_usage + "\n" +
Thomas Wouters477c8d52006-05-27 19:21:47 +0000528 "Options:\n"
Greg Ward48aa84b2004-10-27 02:20:04 +0000529 " --version show program's version number and exit\n"
530 " -h, --help show this help message and exit\n")
Tim Peters579f7352004-07-31 21:14:28 +0000531 finally:
532 sys.argv[:] = save_argv
Greg Wardeba20e62004-07-31 16:15:44 +0000533
534 def test_custom_progname(self):
535 parser = OptionParser(prog="thingy",
536 version="%prog 0.1",
537 usage="%prog arg arg")
538 parser.remove_option("-h")
539 parser.remove_option("--version")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000540 expected_usage = "Usage: thingy arg arg\n"
Greg Wardeba20e62004-07-31 16:15:44 +0000541 self.assertUsage(parser, expected_usage)
542 self.assertVersion(parser, "thingy 0.1")
543 self.assertHelp(parser, expected_usage + "\n")
544
545
546class TestExpandDefaults(BaseTest):
547 def setUp(self):
548 self.parser = OptionParser(prog="test")
549 self.help_prefix = """\
Thomas Wouters477c8d52006-05-27 19:21:47 +0000550Usage: test [options]
Greg Wardeba20e62004-07-31 16:15:44 +0000551
Thomas Wouters477c8d52006-05-27 19:21:47 +0000552Options:
Greg Wardeba20e62004-07-31 16:15:44 +0000553 -h, --help show this help message and exit
554"""
555 self.file_help = "read from FILE [default: %default]"
556 self.expected_help_file = self.help_prefix + \
557 " -f FILE, --file=FILE read from FILE [default: foo.txt]\n"
558 self.expected_help_none = self.help_prefix + \
559 " -f FILE, --file=FILE read from FILE [default: none]\n"
560
561 def test_option_default(self):
562 self.parser.add_option("-f", "--file",
563 default="foo.txt",
564 help=self.file_help)
565 self.assertHelp(self.parser, self.expected_help_file)
566
567 def test_parser_default_1(self):
568 self.parser.add_option("-f", "--file",
569 help=self.file_help)
570 self.parser.set_default('file', "foo.txt")
571 self.assertHelp(self.parser, self.expected_help_file)
572
573 def test_parser_default_2(self):
574 self.parser.add_option("-f", "--file",
575 help=self.file_help)
576 self.parser.set_defaults(file="foo.txt")
577 self.assertHelp(self.parser, self.expected_help_file)
578
579 def test_no_default(self):
580 self.parser.add_option("-f", "--file",
581 help=self.file_help)
582 self.assertHelp(self.parser, self.expected_help_none)
583
584 def test_default_none_1(self):
585 self.parser.add_option("-f", "--file",
586 default=None,
587 help=self.file_help)
588 self.assertHelp(self.parser, self.expected_help_none)
Tim Peters10d59f32004-10-27 02:43:25 +0000589
Greg Wardeba20e62004-07-31 16:15:44 +0000590 def test_default_none_2(self):
591 self.parser.add_option("-f", "--file",
592 help=self.file_help)
593 self.parser.set_defaults(file=None)
594 self.assertHelp(self.parser, self.expected_help_none)
595
596 def test_float_default(self):
597 self.parser.add_option(
598 "-p", "--prob",
599 help="blow up with probability PROB [default: %default]")
600 self.parser.set_defaults(prob=0.43)
601 expected_help = self.help_prefix + \
602 " -p PROB, --prob=PROB blow up with probability PROB [default: 0.43]\n"
603 self.assertHelp(self.parser, expected_help)
604
605 def test_alt_expand(self):
606 self.parser.add_option("-f", "--file",
607 default="foo.txt",
608 help="read from FILE [default: *DEFAULT*]")
609 self.parser.formatter.default_tag = "*DEFAULT*"
610 self.assertHelp(self.parser, self.expected_help_file)
611
612 def test_no_expand(self):
613 self.parser.add_option("-f", "--file",
614 default="foo.txt",
615 help="read from %default file")
616 self.parser.formatter.default_tag = None
617 expected_help = self.help_prefix + \
618 " -f FILE, --file=FILE read from %default file\n"
619 self.assertHelp(self.parser, expected_help)
620
Greg Ward55493222003-04-21 02:41:25 +0000621
622# -- Test parser.parse_args() ------------------------------------------
623
624class TestStandard(BaseTest):
625 def setUp(self):
626 options = [make_option("-a", type="string"),
627 make_option("-b", "--boo", type="int", dest='boo'),
628 make_option("--foo", action="append")]
629
Greg Ward48aa84b2004-10-27 02:20:04 +0000630 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
631 option_list=options)
Greg Ward55493222003-04-21 02:41:25 +0000632
633 def test_required_value(self):
Greg Wardeba20e62004-07-31 16:15:44 +0000634 self.assertParseFail(["-a"], "-a option requires an argument")
Greg Ward55493222003-04-21 02:41:25 +0000635
636 def test_invalid_integer(self):
637 self.assertParseFail(["-b", "5x"],
638 "option -b: invalid integer value: '5x'")
639
640 def test_no_such_option(self):
641 self.assertParseFail(["--boo13"], "no such option: --boo13")
642
643 def test_long_invalid_integer(self):
644 self.assertParseFail(["--boo=x5"],
645 "option --boo: invalid integer value: 'x5'")
646
647 def test_empty(self):
648 self.assertParseOK([], {'a': None, 'boo': None, 'foo': None}, [])
649
650 def test_shortopt_empty_longopt_append(self):
651 self.assertParseOK(["-a", "", "--foo=blah", "--foo="],
652 {'a': "", 'boo': None, 'foo': ["blah", ""]},
653 [])
654
655 def test_long_option_append(self):
656 self.assertParseOK(["--foo", "bar", "--foo", "", "--foo=x"],
657 {'a': None,
658 'boo': None,
659 'foo': ["bar", "", "x"]},
660 [])
661
662 def test_option_argument_joined(self):
663 self.assertParseOK(["-abc"],
664 {'a': "bc", 'boo': None, 'foo': None},
665 [])
666
667 def test_option_argument_split(self):
668 self.assertParseOK(["-a", "34"],
669 {'a': "34", 'boo': None, 'foo': None},
670 [])
671
672 def test_option_argument_joined_integer(self):
673 self.assertParseOK(["-b34"],
674 {'a': None, 'boo': 34, 'foo': None},
675 [])
676
677 def test_option_argument_split_negative_integer(self):
678 self.assertParseOK(["-b", "-5"],
679 {'a': None, 'boo': -5, 'foo': None},
680 [])
681
682 def test_long_option_argument_joined(self):
683 self.assertParseOK(["--boo=13"],
684 {'a': None, 'boo': 13, 'foo': None},
685 [])
686
687 def test_long_option_argument_split(self):
688 self.assertParseOK(["--boo", "111"],
689 {'a': None, 'boo': 111, 'foo': None},
690 [])
691
692 def test_long_option_short_option(self):
693 self.assertParseOK(["--foo=bar", "-axyz"],
694 {'a': 'xyz', 'boo': None, 'foo': ["bar"]},
695 [])
696
697 def test_abbrev_long_option(self):
698 self.assertParseOK(["--f=bar", "-axyz"],
699 {'a': 'xyz', 'boo': None, 'foo': ["bar"]},
700 [])
701
702 def test_defaults(self):
703 (options, args) = self.parser.parse_args([])
704 defaults = self.parser.get_default_values()
705 self.assertEqual(vars(defaults), vars(options))
706
707 def test_ambiguous_option(self):
708 self.parser.add_option("--foz", action="store",
709 type="string", dest="foo")
Greg Ward55493222003-04-21 02:41:25 +0000710 self.assertParseFail(["--f=bar"],
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000711 "ambiguous option: --f (--foo, --foz?)")
Greg Ward55493222003-04-21 02:41:25 +0000712
713
714 def test_short_and_long_option_split(self):
715 self.assertParseOK(["-a", "xyz", "--foo", "bar"],
716 {'a': 'xyz', 'boo': None, 'foo': ["bar"]},
717 []),
718
719 def test_short_option_split_long_option_append(self):
720 self.assertParseOK(["--foo=bar", "-b", "123", "--foo", "baz"],
721 {'a': None, 'boo': 123, 'foo': ["bar", "baz"]},
722 [])
723
724 def test_short_option_split_one_positional_arg(self):
725 self.assertParseOK(["-a", "foo", "bar"],
726 {'a': "foo", 'boo': None, 'foo': None},
727 ["bar"]),
728
729 def test_short_option_consumes_separator(self):
730 self.assertParseOK(["-a", "--", "foo", "bar"],
731 {'a': "--", 'boo': None, 'foo': None},
732 ["foo", "bar"]),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000733 self.assertParseOK(["-a", "--", "--foo", "bar"],
734 {'a': "--", 'boo': None, 'foo': ["bar"]},
735 []),
Greg Ward55493222003-04-21 02:41:25 +0000736
737 def test_short_option_joined_and_separator(self):
738 self.assertParseOK(["-ab", "--", "--foo", "bar"],
739 {'a': "b", 'boo': None, 'foo': None},
740 ["--foo", "bar"]),
741
Thomas Wouters477c8d52006-05-27 19:21:47 +0000742 def test_hyphen_becomes_positional_arg(self):
Greg Ward55493222003-04-21 02:41:25 +0000743 self.assertParseOK(["-ab", "-", "--foo", "bar"],
744 {'a': "b", 'boo': None, 'foo': ["bar"]},
745 ["-"])
746
747 def test_no_append_versus_append(self):
748 self.assertParseOK(["-b3", "-b", "5", "--foo=bar", "--foo", "baz"],
749 {'a': None, 'boo': 5, 'foo': ["bar", "baz"]},
750 [])
751
752 def test_option_consumes_optionlike_string(self):
753 self.assertParseOK(["-a", "-b3"],
754 {'a': "-b3", 'boo': None, 'foo': None},
755 [])
756
757class TestBool(BaseTest):
758 def setUp(self):
759 options = [make_option("-v",
760 "--verbose",
761 action="store_true",
762 dest="verbose",
763 default=''),
764 make_option("-q",
765 "--quiet",
766 action="store_false",
767 dest="verbose")]
768 self.parser = OptionParser(option_list = options)
769
770 def test_bool_default(self):
771 self.assertParseOK([],
772 {'verbose': ''},
773 [])
774
775 def test_bool_false(self):
776 (options, args) = self.assertParseOK(["-q"],
777 {'verbose': 0},
778 [])
779 if hasattr(__builtins__, 'False'):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000780 self.assertTrue(options.verbose is False)
Greg Ward55493222003-04-21 02:41:25 +0000781
782 def test_bool_true(self):
783 (options, args) = self.assertParseOK(["-v"],
784 {'verbose': 1},
785 [])
786 if hasattr(__builtins__, 'True'):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000787 self.assertTrue(options.verbose is True)
Greg Ward55493222003-04-21 02:41:25 +0000788
789 def test_bool_flicker_on_and_off(self):
790 self.assertParseOK(["-qvq", "-q", "-v"],
791 {'verbose': 1},
792 [])
793
794class TestChoice(BaseTest):
795 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000796 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000797 self.parser.add_option("-c", action="store", type="choice",
798 dest="choice", choices=["one", "two", "three"])
799
800 def test_valid_choice(self):
801 self.assertParseOK(["-c", "one", "xyz"],
802 {'choice': 'one'},
803 ["xyz"])
804
805 def test_invalid_choice(self):
806 self.assertParseFail(["-c", "four", "abc"],
807 "option -c: invalid choice: 'four' "
808 "(choose from 'one', 'two', 'three')")
809
810 def test_add_choice_option(self):
811 self.parser.add_option("-d", "--default",
812 choices=["four", "five", "six"])
813 opt = self.parser.get_option("-d")
814 self.assertEqual(opt.type, "choice")
815 self.assertEqual(opt.action, "store")
816
817class TestCount(BaseTest):
818 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000819 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000820 self.v_opt = make_option("-v", action="count", dest="verbose")
821 self.parser.add_option(self.v_opt)
822 self.parser.add_option("--verbose", type="int", dest="verbose")
823 self.parser.add_option("-q", "--quiet",
824 action="store_const", dest="verbose", const=0)
825
826 def test_empty(self):
827 self.assertParseOK([], {'verbose': None}, [])
828
829 def test_count_one(self):
830 self.assertParseOK(["-v"], {'verbose': 1}, [])
831
832 def test_count_three(self):
833 self.assertParseOK(["-vvv"], {'verbose': 3}, [])
834
835 def test_count_three_apart(self):
836 self.assertParseOK(["-v", "-v", "-v"], {'verbose': 3}, [])
837
838 def test_count_override_amount(self):
839 self.assertParseOK(["-vvv", "--verbose=2"], {'verbose': 2}, [])
840
841 def test_count_override_quiet(self):
842 self.assertParseOK(["-vvv", "--verbose=2", "-q"], {'verbose': 0}, [])
843
844 def test_count_overriding(self):
845 self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"],
846 {'verbose': 1}, [])
847
848 def test_count_interspersed_args(self):
849 self.assertParseOK(["--quiet", "3", "-v"],
850 {'verbose': 1},
851 ["3"])
852
853 def test_count_no_interspersed_args(self):
854 self.parser.disable_interspersed_args()
855 self.assertParseOK(["--quiet", "3", "-v"],
856 {'verbose': 0},
857 ["3", "-v"])
858
859 def test_count_no_such_option(self):
860 self.assertParseFail(["-q3", "-v"], "no such option: -3")
861
862 def test_count_option_no_value(self):
863 self.assertParseFail(["--quiet=3", "-v"],
864 "--quiet option does not take a value")
865
866 def test_count_with_default(self):
867 self.parser.set_default('verbose', 0)
868 self.assertParseOK([], {'verbose':0}, [])
869
870 def test_count_overriding_default(self):
871 self.parser.set_default('verbose', 0)
872 self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"],
873 {'verbose': 1}, [])
874
Greg Ward48aa84b2004-10-27 02:20:04 +0000875class TestMultipleArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +0000876 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000877 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000878 self.parser.add_option("-p", "--point",
879 action="store", nargs=3, type="float", dest="point")
880
881 def test_nargs_with_positional_args(self):
882 self.assertParseOK(["foo", "-p", "1", "2.5", "-4.3", "xyz"],
883 {'point': (1.0, 2.5, -4.3)},
884 ["foo", "xyz"])
885
886 def test_nargs_long_opt(self):
887 self.assertParseOK(["--point", "-1", "2.5", "-0", "xyz"],
888 {'point': (-1.0, 2.5, -0.0)},
889 ["xyz"])
890
891 def test_nargs_invalid_float_value(self):
892 self.assertParseFail(["-p", "1.0", "2x", "3.5"],
893 "option -p: "
894 "invalid floating-point value: '2x'")
895
896 def test_nargs_required_values(self):
897 self.assertParseFail(["--point", "1.0", "3.5"],
Greg Wardeba20e62004-07-31 16:15:44 +0000898 "--point option requires 3 arguments")
Greg Ward55493222003-04-21 02:41:25 +0000899
Greg Ward48aa84b2004-10-27 02:20:04 +0000900class TestMultipleArgsAppend(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +0000901 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000902 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000903 self.parser.add_option("-p", "--point", action="store", nargs=3,
904 type="float", dest="point")
905 self.parser.add_option("-f", "--foo", action="append", nargs=2,
906 type="int", dest="foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000907 self.parser.add_option("-z", "--zero", action="append_const",
908 dest="foo", const=(0, 0))
Greg Ward55493222003-04-21 02:41:25 +0000909
910 def test_nargs_append(self):
911 self.assertParseOK(["-f", "4", "-3", "blah", "--foo", "1", "666"],
912 {'point': None, 'foo': [(4, -3), (1, 666)]},
913 ["blah"])
914
915 def test_nargs_append_required_values(self):
916 self.assertParseFail(["-f4,3"],
Greg Wardeba20e62004-07-31 16:15:44 +0000917 "-f option requires 2 arguments")
Greg Ward55493222003-04-21 02:41:25 +0000918
919 def test_nargs_append_simple(self):
920 self.assertParseOK(["--foo=3", "4"],
921 {'point': None, 'foo':[(3, 4)]},
922 [])
923
Thomas Wouters477c8d52006-05-27 19:21:47 +0000924 def test_nargs_append_const(self):
925 self.assertParseOK(["--zero", "--foo", "3", "4", "-z"],
926 {'point': None, 'foo':[(0, 0), (3, 4), (0, 0)]},
927 [])
928
Greg Ward55493222003-04-21 02:41:25 +0000929class TestVersion(BaseTest):
930 def test_version(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000931 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
932 version="%prog 0.1")
933 save_argv = sys.argv[:]
934 try:
935 sys.argv[0] = os.path.join(os.curdir, "foo", "bar")
936 self.assertOutput(["--version"], "bar 0.1\n")
937 finally:
938 sys.argv[:] = save_argv
Greg Ward55493222003-04-21 02:41:25 +0000939
940 def test_no_version(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000941 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000942 self.assertParseFail(["--version"],
943 "no such option: --version")
944
945# -- Test conflicting default values and parser.parse_args() -----------
946
947class TestConflictingDefaults(BaseTest):
948 """Conflicting default values: the last one should win."""
949 def setUp(self):
950 self.parser = OptionParser(option_list=[
951 make_option("-v", action="store_true", dest="verbose", default=1)])
952
953 def test_conflict_default(self):
954 self.parser.add_option("-q", action="store_false", dest="verbose",
955 default=0)
956 self.assertParseOK([], {'verbose': 0}, [])
957
958 def test_conflict_default_none(self):
959 self.parser.add_option("-q", action="store_false", dest="verbose",
960 default=None)
961 self.assertParseOK([], {'verbose': None}, [])
962
963class TestOptionGroup(BaseTest):
964 def setUp(self):
965 self.parser = OptionParser(usage=SUPPRESS_USAGE)
966
967 def test_option_group_create_instance(self):
968 group = OptionGroup(self.parser, "Spam")
969 self.parser.add_option_group(group)
970 group.add_option("--spam", action="store_true",
971 help="spam spam spam spam")
972 self.assertParseOK(["--spam"], {'spam': 1}, [])
973
974 def test_add_group_no_group(self):
975 self.assertTypeError(self.parser.add_option_group,
976 "not an OptionGroup instance: None", None)
977
978 def test_add_group_invalid_arguments(self):
979 self.assertTypeError(self.parser.add_option_group,
980 "invalid arguments", None, None)
981
982 def test_add_group_wrong_parser(self):
983 group = OptionGroup(self.parser, "Spam")
984 group.parser = OptionParser()
Greg Wardeba20e62004-07-31 16:15:44 +0000985 self.assertRaises(self.parser.add_option_group, (group,), None,
986 ValueError, "invalid OptionGroup (wrong parser)")
Greg Ward55493222003-04-21 02:41:25 +0000987
988 def test_group_manipulate(self):
989 group = self.parser.add_option_group("Group 2",
990 description="Some more options")
991 group.set_title("Bacon")
992 group.add_option("--bacon", type="int")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000993 self.assertTrue(self.parser.get_option_group("--bacon"), group)
Greg Ward55493222003-04-21 02:41:25 +0000994
995# -- Test extending and parser.parse_args() ----------------------------
996
997class TestExtendAddTypes(BaseTest):
998 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000999 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
1000 option_class=self.MyOption)
Greg Ward55493222003-04-21 02:41:25 +00001001 self.parser.add_option("-a", None, type="string", dest="a")
1002 self.parser.add_option("-f", "--file", type="file", dest="file")
1003
Thomas Wouters477c8d52006-05-27 19:21:47 +00001004 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001005 if os.path.isdir(support.TESTFN):
1006 os.rmdir(support.TESTFN)
1007 elif os.path.isfile(support.TESTFN):
1008 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001009
Greg Ward55493222003-04-21 02:41:25 +00001010 class MyOption (Option):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001011 def check_file(option, opt, value):
Greg Ward55493222003-04-21 02:41:25 +00001012 if not os.path.exists(value):
1013 raise OptionValueError("%s: file does not exist" % value)
1014 elif not os.path.isfile(value):
1015 raise OptionValueError("%s: not a regular file" % value)
1016 return value
1017
1018 TYPES = Option.TYPES + ("file",)
1019 TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
1020 TYPE_CHECKER["file"] = check_file
1021
Thomas Wouters477c8d52006-05-27 19:21:47 +00001022 def test_filetype_ok(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001023 open(support.TESTFN, "w").close()
1024 self.assertParseOK(["--file", support.TESTFN, "-afoo"],
1025 {'file': support.TESTFN, 'a': 'foo'},
Greg Ward55493222003-04-21 02:41:25 +00001026 [])
1027
Thomas Wouters477c8d52006-05-27 19:21:47 +00001028 def test_filetype_noexist(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001029 self.assertParseFail(["--file", support.TESTFN, "-afoo"],
Greg Ward55493222003-04-21 02:41:25 +00001030 "%s: file does not exist" %
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001031 support.TESTFN)
Greg Ward55493222003-04-21 02:41:25 +00001032
Thomas Wouters477c8d52006-05-27 19:21:47 +00001033 def test_filetype_notfile(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001034 os.mkdir(support.TESTFN)
1035 self.assertParseFail(["--file", support.TESTFN, "-afoo"],
Greg Ward55493222003-04-21 02:41:25 +00001036 "%s: not a regular file" %
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001037 support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001038
Greg Ward55493222003-04-21 02:41:25 +00001039
1040class TestExtendAddActions(BaseTest):
1041 def setUp(self):
1042 options = [self.MyOption("-a", "--apple", action="extend",
1043 type="string", dest="apple")]
1044 self.parser = OptionParser(option_list=options)
1045
1046 class MyOption (Option):
1047 ACTIONS = Option.ACTIONS + ("extend",)
1048 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1049 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1050
Thomas Wouters477c8d52006-05-27 19:21:47 +00001051 def take_action(self, action, dest, opt, value, values, parser):
Greg Ward55493222003-04-21 02:41:25 +00001052 if action == "extend":
1053 lvalue = value.split(",")
1054 values.ensure_value(dest, []).extend(lvalue)
1055 else:
1056 Option.take_action(self, action, dest, opt, parser, value,
1057 values)
1058
1059 def test_extend_add_action(self):
1060 self.assertParseOK(["-afoo,bar", "--apple=blah"],
1061 {'apple': ["foo", "bar", "blah"]},
1062 [])
1063
1064 def test_extend_add_action_normal(self):
1065 self.assertParseOK(["-a", "foo", "-abar", "--apple=x,y"],
1066 {'apple': ["foo", "bar", "x", "y"]},
1067 [])
1068
1069# -- Test callbacks and parser.parse_args() ----------------------------
1070
1071class TestCallback(BaseTest):
1072 def setUp(self):
1073 options = [make_option("-x",
1074 None,
1075 action="callback",
1076 callback=self.process_opt),
1077 make_option("-f",
1078 "--file",
1079 action="callback",
1080 callback=self.process_opt,
1081 type="string",
1082 dest="filename")]
1083 self.parser = OptionParser(option_list=options)
1084
1085 def process_opt(self, option, opt, value, parser_):
1086 if opt == "-x":
1087 self.assertEqual(option._short_opts, ["-x"])
1088 self.assertEqual(option._long_opts, [])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001089 self.assertTrue(parser_ is self.parser)
1090 self.assertTrue(value is None)
Greg Ward55493222003-04-21 02:41:25 +00001091 self.assertEqual(vars(parser_.values), {'filename': None})
1092
1093 parser_.values.x = 42
1094 elif opt == "--file":
1095 self.assertEqual(option._short_opts, ["-f"])
1096 self.assertEqual(option._long_opts, ["--file"])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001097 self.assertTrue(parser_ is self.parser)
Greg Ward55493222003-04-21 02:41:25 +00001098 self.assertEqual(value, "foo")
1099 self.assertEqual(vars(parser_.values), {'filename': None, 'x': 42})
1100
1101 setattr(parser_.values, option.dest, value)
1102 else:
1103 self.fail("Unknown option %r in process_opt." % opt)
1104
1105 def test_callback(self):
1106 self.assertParseOK(["-x", "--file=foo"],
1107 {'filename': "foo", 'x': 42},
1108 [])
1109
Greg Wardeba20e62004-07-31 16:15:44 +00001110 def test_callback_help(self):
1111 # This test was prompted by SF bug #960515 -- the point is
1112 # not to inspect the help text, just to make sure that
1113 # format_help() doesn't crash.
1114 parser = OptionParser(usage=SUPPRESS_USAGE)
1115 parser.remove_option("-h")
1116 parser.add_option("-t", "--test", action="callback",
1117 callback=lambda: None, type="string",
1118 help="foo")
1119
Thomas Wouters477c8d52006-05-27 19:21:47 +00001120 expected_help = ("Options:\n"
Greg Wardeba20e62004-07-31 16:15:44 +00001121 " -t TEST, --test=TEST foo\n")
1122 self.assertHelp(parser, expected_help)
1123
1124
1125class TestCallbackExtraArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001126 def setUp(self):
1127 options = [make_option("-p", "--point", action="callback",
1128 callback=self.process_tuple,
1129 callback_args=(3, int), type="string",
1130 dest="points", default=[])]
1131 self.parser = OptionParser(option_list=options)
1132
Thomas Wouters477c8d52006-05-27 19:21:47 +00001133 def process_tuple(self, option, opt, value, parser_, len, type):
Greg Ward55493222003-04-21 02:41:25 +00001134 self.assertEqual(len, 3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001135 self.assertTrue(type is int)
Greg Ward55493222003-04-21 02:41:25 +00001136
1137 if opt == "-p":
1138 self.assertEqual(value, "1,2,3")
1139 elif opt == "--point":
1140 self.assertEqual(value, "4,5,6")
1141
1142 value = tuple(map(type, value.split(",")))
1143 getattr(parser_.values, option.dest).append(value)
1144
1145 def test_callback_extra_args(self):
1146 self.assertParseOK(["-p1,2,3", "--point", "4,5,6"],
1147 {'points': [(1,2,3), (4,5,6)]},
1148 [])
1149
Greg Wardeba20e62004-07-31 16:15:44 +00001150class TestCallbackMeddleArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001151 def setUp(self):
1152 options = [make_option(str(x), action="callback",
1153 callback=self.process_n, dest='things')
1154 for x in range(-1, -6, -1)]
1155 self.parser = OptionParser(option_list=options)
1156
1157 # Callback that meddles in rargs, largs
Thomas Wouters477c8d52006-05-27 19:21:47 +00001158 def process_n(self, option, opt, value, parser_):
Greg Ward55493222003-04-21 02:41:25 +00001159 # option is -3, -5, etc.
1160 nargs = int(opt[1:])
1161 rargs = parser_.rargs
1162 if len(rargs) < nargs:
1163 self.fail("Expected %d arguments for %s option." % (nargs, opt))
1164 dest = parser_.values.ensure_value(option.dest, [])
1165 dest.append(tuple(rargs[0:nargs]))
1166 parser_.largs.append(nargs)
1167 del rargs[0:nargs]
1168
1169 def test_callback_meddle_args(self):
1170 self.assertParseOK(["-1", "foo", "-3", "bar", "baz", "qux"],
1171 {'things': [("foo",), ("bar", "baz", "qux")]},
1172 [1, 3])
1173
1174 def test_callback_meddle_args_separator(self):
1175 self.assertParseOK(["-2", "foo", "--"],
1176 {'things': [('foo', '--')]},
1177 [2])
1178
Greg Wardeba20e62004-07-31 16:15:44 +00001179class TestCallbackManyArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001180 def setUp(self):
1181 options = [make_option("-a", "--apple", action="callback", nargs=2,
1182 callback=self.process_many, type="string"),
1183 make_option("-b", "--bob", action="callback", nargs=3,
1184 callback=self.process_many, type="int")]
1185 self.parser = OptionParser(option_list=options)
1186
Thomas Wouters477c8d52006-05-27 19:21:47 +00001187 def process_many(self, option, opt, value, parser_):
Greg Ward55493222003-04-21 02:41:25 +00001188 if opt == "-a":
1189 self.assertEqual(value, ("foo", "bar"))
1190 elif opt == "--apple":
1191 self.assertEqual(value, ("ding", "dong"))
1192 elif opt == "-b":
1193 self.assertEqual(value, (1, 2, 3))
1194 elif opt == "--bob":
1195 self.assertEqual(value, (-666, 42, 0))
1196
1197 def test_many_args(self):
1198 self.assertParseOK(["-a", "foo", "bar", "--apple", "ding", "dong",
1199 "-b", "1", "2", "3", "--bob", "-666", "42",
1200 "0"],
Greg Wardeba20e62004-07-31 16:15:44 +00001201 {"apple": None, "bob": None},
Greg Ward55493222003-04-21 02:41:25 +00001202 [])
1203
Greg Wardeba20e62004-07-31 16:15:44 +00001204class TestCallbackCheckAbbrev(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001205 def setUp(self):
1206 self.parser = OptionParser()
1207 self.parser.add_option("--foo-bar", action="callback",
1208 callback=self.check_abbrev)
1209
Thomas Wouters477c8d52006-05-27 19:21:47 +00001210 def check_abbrev(self, option, opt, value, parser):
Greg Ward55493222003-04-21 02:41:25 +00001211 self.assertEqual(opt, "--foo-bar")
1212
1213 def test_abbrev_callback_expansion(self):
1214 self.assertParseOK(["--foo"], {}, [])
1215
Greg Wardeba20e62004-07-31 16:15:44 +00001216class TestCallbackVarArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001217 def setUp(self):
1218 options = [make_option("-a", type="int", nargs=2, dest="a"),
1219 make_option("-b", action="store_true", dest="b"),
1220 make_option("-c", "--callback", action="callback",
1221 callback=self.variable_args, dest="c")]
Greg Ward48aa84b2004-10-27 02:20:04 +00001222 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
1223 option_list=options)
Greg Ward55493222003-04-21 02:41:25 +00001224
Thomas Wouters477c8d52006-05-27 19:21:47 +00001225 def variable_args(self, option, opt, value, parser):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001226 self.assertTrue(value is None)
Greg Ward55493222003-04-21 02:41:25 +00001227 value = []
1228 rargs = parser.rargs
1229 while rargs:
1230 arg = rargs[0]
1231 if ((arg[:2] == "--" and len(arg) > 2) or
1232 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1233 break
1234 else:
1235 value.append(arg)
1236 del rargs[0]
1237 setattr(parser.values, option.dest, value)
1238
1239 def test_variable_args(self):
1240 self.assertParseOK(["-a3", "-5", "--callback", "foo", "bar"],
1241 {'a': (3, -5), 'b': None, 'c': ["foo", "bar"]},
1242 [])
1243
1244 def test_consume_separator_stop_at_option(self):
1245 self.assertParseOK(["-c", "37", "--", "xxx", "-b", "hello"],
1246 {'a': None,
1247 'b': True,
1248 'c': ["37", "--", "xxx"]},
1249 ["hello"])
1250
1251 def test_positional_arg_and_variable_args(self):
1252 self.assertParseOK(["hello", "-c", "foo", "-", "bar"],
1253 {'a': None,
1254 'b': None,
1255 'c':["foo", "-", "bar"]},
1256 ["hello"])
1257
1258 def test_stop_at_option(self):
1259 self.assertParseOK(["-c", "foo", "-b"],
1260 {'a': None, 'b': True, 'c': ["foo"]},
1261 [])
1262
1263 def test_stop_at_invalid_option(self):
1264 self.assertParseFail(["-c", "3", "-5", "-a"], "no such option: -5")
1265
1266
1267# -- Test conflict handling and parser.parse_args() --------------------
1268
1269class ConflictBase(BaseTest):
1270 def setUp(self):
1271 options = [make_option("-v", "--verbose", action="count",
1272 dest="verbose", help="increment verbosity")]
Greg Ward48aa84b2004-10-27 02:20:04 +00001273 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
1274 option_list=options)
Greg Ward55493222003-04-21 02:41:25 +00001275
Thomas Wouters477c8d52006-05-27 19:21:47 +00001276 def show_version(self, option, opt, value, parser):
Greg Ward55493222003-04-21 02:41:25 +00001277 parser.values.show_version = 1
1278
1279class TestConflict(ConflictBase):
1280 """Use the default conflict resolution for Optik 1.2: error."""
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001281 def assertTrueconflict_error(self, func):
Greg Wardeba20e62004-07-31 16:15:44 +00001282 err = self.assertRaises(
1283 func, ("-v", "--version"), {'action' : "callback",
1284 'callback' : self.show_version,
1285 'help' : "show version"},
1286 OptionConflictError,
1287 "option -v/--version: conflicting option string(s): -v")
Greg Ward55493222003-04-21 02:41:25 +00001288
1289 self.assertEqual(err.msg, "conflicting option string(s): -v")
1290 self.assertEqual(err.option_id, "-v/--version")
1291
1292 def test_conflict_error(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001293 self.assertTrueconflict_error(self.parser.add_option)
Greg Ward55493222003-04-21 02:41:25 +00001294
1295 def test_conflict_error_group(self):
1296 group = OptionGroup(self.parser, "Group 1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001297 self.assertTrueconflict_error(group.add_option)
Greg Ward55493222003-04-21 02:41:25 +00001298
1299 def test_no_such_conflict_handler(self):
Greg Wardeba20e62004-07-31 16:15:44 +00001300 self.assertRaises(
1301 self.parser.set_conflict_handler, ('foo',), None,
1302 ValueError, "invalid conflict_resolution value 'foo'")
Greg Ward55493222003-04-21 02:41:25 +00001303
1304
Greg Ward55493222003-04-21 02:41:25 +00001305class TestConflictResolve(ConflictBase):
1306 def setUp(self):
1307 ConflictBase.setUp(self)
1308 self.parser.set_conflict_handler("resolve")
1309 self.parser.add_option("-v", "--version", action="callback",
1310 callback=self.show_version, help="show version")
1311
1312 def test_conflict_resolve(self):
1313 v_opt = self.parser.get_option("-v")
1314 verbose_opt = self.parser.get_option("--verbose")
1315 version_opt = self.parser.get_option("--version")
1316
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001317 self.assertTrue(v_opt is version_opt)
1318 self.assertTrue(v_opt is not verbose_opt)
Greg Ward55493222003-04-21 02:41:25 +00001319 self.assertEqual(v_opt._long_opts, ["--version"])
1320 self.assertEqual(version_opt._short_opts, ["-v"])
1321 self.assertEqual(version_opt._long_opts, ["--version"])
1322 self.assertEqual(verbose_opt._short_opts, [])
1323 self.assertEqual(verbose_opt._long_opts, ["--verbose"])
1324
1325 def test_conflict_resolve_help(self):
Greg Ward48aa84b2004-10-27 02:20:04 +00001326 self.assertOutput(["-h"], """\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001327Options:
Greg Ward55493222003-04-21 02:41:25 +00001328 --verbose increment verbosity
1329 -h, --help show this help message and exit
1330 -v, --version show version
1331""")
1332
1333 def test_conflict_resolve_short_opt(self):
1334 self.assertParseOK(["-v"],
1335 {'verbose': None, 'show_version': 1},
1336 [])
1337
1338 def test_conflict_resolve_long_opt(self):
1339 self.assertParseOK(["--verbose"],
1340 {'verbose': 1},
1341 [])
1342
1343 def test_conflict_resolve_long_opts(self):
1344 self.assertParseOK(["--verbose", "--version"],
1345 {'verbose': 1, 'show_version': 1},
1346 [])
1347
1348class TestConflictOverride(BaseTest):
1349 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +00001350 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +00001351 self.parser.set_conflict_handler("resolve")
1352 self.parser.add_option("-n", "--dry-run",
1353 action="store_true", dest="dry_run",
1354 help="don't do anything")
1355 self.parser.add_option("--dry-run", "-n",
1356 action="store_const", const=42, dest="dry_run",
1357 help="dry run mode")
1358
1359 def test_conflict_override_opts(self):
1360 opt = self.parser.get_option("--dry-run")
1361 self.assertEqual(opt._short_opts, ["-n"])
1362 self.assertEqual(opt._long_opts, ["--dry-run"])
1363
1364 def test_conflict_override_help(self):
Greg Ward48aa84b2004-10-27 02:20:04 +00001365 self.assertOutput(["-h"], """\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001366Options:
Greg Ward55493222003-04-21 02:41:25 +00001367 -h, --help show this help message and exit
1368 -n, --dry-run dry run mode
1369""")
1370
1371 def test_conflict_override_args(self):
1372 self.assertParseOK(["-n"],
1373 {'dry_run': 42},
1374 [])
1375
1376# -- Other testing. ----------------------------------------------------
1377
Greg Wardeba20e62004-07-31 16:15:44 +00001378_expected_help_basic = """\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001379Usage: bar.py [options]
Greg Wardeba20e62004-07-31 16:15:44 +00001380
Thomas Wouters477c8d52006-05-27 19:21:47 +00001381Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001382 -a APPLE throw APPLEs at basket
1383 -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the
1384 evil spirits that cause trouble and mayhem)
1385 --foo=FOO store FOO in the foo list for later fooing
1386 -h, --help show this help message and exit
1387"""
1388
1389_expected_help_long_opts_first = """\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001390Usage: bar.py [options]
Greg Wardeba20e62004-07-31 16:15:44 +00001391
Thomas Wouters477c8d52006-05-27 19:21:47 +00001392Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001393 -a APPLE throw APPLEs at basket
1394 --boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the
1395 evil spirits that cause trouble and mayhem)
1396 --foo=FOO store FOO in the foo list for later fooing
1397 --help, -h show this help message and exit
1398"""
1399
1400_expected_help_title_formatter = """\
1401Usage
1402=====
1403 bar.py [options]
1404
Thomas Wouters477c8d52006-05-27 19:21:47 +00001405Options
Greg Wardeba20e62004-07-31 16:15:44 +00001406=======
1407-a APPLE throw APPLEs at basket
1408--boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the
1409 evil spirits that cause trouble and mayhem)
1410--foo=FOO store FOO in the foo list for later fooing
1411--help, -h show this help message and exit
1412"""
1413
1414_expected_help_short_lines = """\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001415Usage: bar.py [options]
Greg Wardeba20e62004-07-31 16:15:44 +00001416
Thomas Wouters477c8d52006-05-27 19:21:47 +00001417Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001418 -a APPLE throw APPLEs at basket
1419 -b NUM, --boo=NUM shout "boo!" NUM times (in order to
1420 frighten away all the evil spirits
1421 that cause trouble and mayhem)
1422 --foo=FOO store FOO in the foo list for later
1423 fooing
1424 -h, --help show this help message and exit
1425"""
1426
Greg Ward55493222003-04-21 02:41:25 +00001427class TestHelp(BaseTest):
1428 def setUp(self):
Greg Wardeba20e62004-07-31 16:15:44 +00001429 self.parser = self.make_parser(80)
1430
1431 def make_parser(self, columns):
Greg Ward55493222003-04-21 02:41:25 +00001432 options = [
1433 make_option("-a", type="string", dest='a',
1434 metavar="APPLE", help="throw APPLEs at basket"),
1435 make_option("-b", "--boo", type="int", dest='boo',
1436 metavar="NUM",
1437 help=
1438 "shout \"boo!\" NUM times (in order to frighten away "
1439 "all the evil spirits that cause trouble and mayhem)"),
1440 make_option("--foo", action="append", type="string", dest='foo',
1441 help="store FOO in the foo list for later fooing"),
1442 ]
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001443
1444 # We need to set COLUMNS for the OptionParser constructor, but
1445 # we must restore its original value -- otherwise, this test
1446 # screws things up for other tests when it's part of the Python
1447 # test suite.
Hirokazu Yamamoto71959632009-04-27 01:44:28 +00001448 with support.EnvironmentVarGuard() as env:
Walter Dörwald155374d2009-05-01 19:58:58 +00001449 env['COLUMNS'] = str(columns)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001450 return InterceptingOptionParser(option_list=options)
Greg Ward55493222003-04-21 02:41:25 +00001451
1452 def assertHelpEquals(self, expected_output):
Greg Ward48aa84b2004-10-27 02:20:04 +00001453 save_argv = sys.argv[:]
1454 try:
1455 # Make optparse believe bar.py is being executed.
1456 sys.argv[0] = os.path.join("foo", "bar.py")
1457 self.assertOutput(["-h"], expected_output)
1458 finally:
1459 sys.argv[:] = save_argv
Greg Ward55493222003-04-21 02:41:25 +00001460
1461 def test_help(self):
Greg Wardeba20e62004-07-31 16:15:44 +00001462 self.assertHelpEquals(_expected_help_basic)
Greg Ward55493222003-04-21 02:41:25 +00001463
1464 def test_help_old_usage(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001465 self.parser.set_usage("Usage: %prog [options]")
Greg Wardeba20e62004-07-31 16:15:44 +00001466 self.assertHelpEquals(_expected_help_basic)
Greg Ward55493222003-04-21 02:41:25 +00001467
1468 def test_help_long_opts_first(self):
1469 self.parser.formatter.short_first = 0
Greg Wardeba20e62004-07-31 16:15:44 +00001470 self.assertHelpEquals(_expected_help_long_opts_first)
Greg Ward55493222003-04-21 02:41:25 +00001471
1472 def test_help_title_formatter(self):
Hirokazu Yamamoto71959632009-04-27 01:44:28 +00001473 with support.EnvironmentVarGuard() as env:
Walter Dörwald155374d2009-05-01 19:58:58 +00001474 env["COLUMNS"] = "80"
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001475 self.parser.formatter = TitledHelpFormatter()
1476 self.assertHelpEquals(_expected_help_title_formatter)
Greg Ward55493222003-04-21 02:41:25 +00001477
Greg Wardeba20e62004-07-31 16:15:44 +00001478 def test_wrap_columns(self):
1479 # Ensure that wrapping respects $COLUMNS environment variable.
1480 # Need to reconstruct the parser, since that's the only time
1481 # we look at $COLUMNS.
1482 self.parser = self.make_parser(60)
1483 self.assertHelpEquals(_expected_help_short_lines)
Greg Ward55493222003-04-21 02:41:25 +00001484
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001485 def test_help_unicode(self):
1486 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001487 self.parser.add_option("-a", action="store_true", help="ol\u00E9!")
1488 expect = """\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001489Options:
1490 -h, --help show this help message and exit
1491 -a ol\u00E9!
1492"""
1493 self.assertHelpEquals(expect)
1494
1495 def test_help_unicode_description(self):
1496 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001497 description="ol\u00E9!")
1498 expect = """\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001499ol\u00E9!
1500
1501Options:
1502 -h, --help show this help message and exit
1503"""
1504 self.assertHelpEquals(expect)
1505
Greg Ward55493222003-04-21 02:41:25 +00001506 def test_help_description_groups(self):
1507 self.parser.set_description(
Greg Wardeba20e62004-07-31 16:15:44 +00001508 "This is the program description for %prog. %prog has "
Greg Ward55493222003-04-21 02:41:25 +00001509 "an option group as well as single options.")
1510
1511 group = OptionGroup(
1512 self.parser, "Dangerous Options",
1513 "Caution: use of these options is at your own risk. "
1514 "It is believed that some of them bite.")
1515 group.add_option("-g", action="store_true", help="Group option.")
1516 self.parser.add_option_group(group)
1517
Thomas Wouters477c8d52006-05-27 19:21:47 +00001518 expect = """\
1519Usage: bar.py [options]
Greg Ward55493222003-04-21 02:41:25 +00001520
Greg Wardeba20e62004-07-31 16:15:44 +00001521This is the program description for bar.py. bar.py has an option group as
1522well as single options.
1523
Thomas Wouters477c8d52006-05-27 19:21:47 +00001524Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001525 -a APPLE throw APPLEs at basket
1526 -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the
1527 evil spirits that cause trouble and mayhem)
1528 --foo=FOO store FOO in the foo list for later fooing
1529 -h, --help show this help message and exit
Greg Ward55493222003-04-21 02:41:25 +00001530
1531 Dangerous Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001532 Caution: use of these options is at your own risk. It is believed
1533 that some of them bite.
1534
1535 -g Group option.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001536"""
Greg Ward55493222003-04-21 02:41:25 +00001537
Thomas Wouters477c8d52006-05-27 19:21:47 +00001538 self.assertHelpEquals(expect)
Greg Wardeba20e62004-07-31 16:15:44 +00001539
Thomas Wouters477c8d52006-05-27 19:21:47 +00001540 self.parser.epilog = "Please report bugs to /dev/null."
1541 self.assertHelpEquals(expect + "\nPlease report bugs to /dev/null.\n")
Tim Peters10d59f32004-10-27 02:43:25 +00001542
Greg Wardeba20e62004-07-31 16:15:44 +00001543
Greg Ward55493222003-04-21 02:41:25 +00001544class TestMatchAbbrev(BaseTest):
1545 def test_match_abbrev(self):
1546 self.assertEqual(_match_abbrev("--f",
1547 {"--foz": None,
1548 "--foo": None,
1549 "--fie": None,
1550 "--f": None}),
1551 "--f")
1552
1553 def test_match_abbrev_error(self):
1554 s = "--f"
1555 wordmap = {"--foz": None, "--foo": None, "--fie": None}
Greg Wardeba20e62004-07-31 16:15:44 +00001556 self.assertRaises(
1557 _match_abbrev, (s, wordmap), None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001558 BadOptionError, "ambiguous option: --f (--fie, --foo, --foz?)")
Greg Wardeba20e62004-07-31 16:15:44 +00001559
1560
Thomas Wouters477c8d52006-05-27 19:21:47 +00001561class TestParseNumber(BaseTest):
1562 def setUp(self):
1563 self.parser = InterceptingOptionParser()
1564 self.parser.add_option("-n", type=int)
Guido van Rossume2a383d2007-01-15 16:59:06 +00001565 self.parser.add_option("-l", type=int)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001566
1567 def test_parse_num_fail(self):
1568 self.assertRaises(
1569 _parse_num, ("", int), {},
1570 ValueError,
1571 re.compile(r"invalid literal for int().*: '?'?"))
1572 self.assertRaises(
Guido van Rossume2a383d2007-01-15 16:59:06 +00001573 _parse_num, ("0xOoops", int), {},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001574 ValueError,
Guido van Rossumb4e87e32007-07-09 10:08:42 +00001575 re.compile(r"invalid literal for int().*: s?'?0xOoops'?"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001576
1577 def test_parse_num_ok(self):
1578 self.assertEqual(_parse_num("0", int), 0)
1579 self.assertEqual(_parse_num("0x10", int), 16)
Guido van Rossume2a383d2007-01-15 16:59:06 +00001580 self.assertEqual(_parse_num("0XA", int), 10)
1581 self.assertEqual(_parse_num("010", int), 8)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001582 self.assertEqual(_parse_num("0b11", int), 3)
Guido van Rossume2a383d2007-01-15 16:59:06 +00001583 self.assertEqual(_parse_num("0b", int), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001584
1585 def test_numeric_options(self):
1586 self.assertParseOK(["-n", "42", "-l", "0x20"],
1587 { "n": 42, "l": 0x20 }, [])
1588 self.assertParseOK(["-n", "0b0101", "-l010"],
1589 { "n": 5, "l": 8 }, [])
1590 self.assertParseFail(["-n008"],
1591 "option -n: invalid integer value: '008'")
1592 self.assertParseFail(["-l0b0123"],
Guido van Rossumddefaf32007-01-14 03:31:43 +00001593 "option -l: invalid integer value: '0b0123'")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001594 self.assertParseFail(["-l", "0x12x"],
Guido van Rossumddefaf32007-01-14 03:31:43 +00001595 "option -l: invalid integer value: '0x12x'")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001596
1597
Greg Ward55493222003-04-21 02:41:25 +00001598def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001599 support.run_unittest(__name__)
Greg Ward55493222003-04-21 02:41:25 +00001600
1601if __name__ == '__main__':
Guido van Rossumd8faa362007-04-27 19:54:29 +00001602 test_main()