blob: 641f37d67085199b73d0ae17d04d80734b3887c4 [file] [log] [blame]
Greg Ward55493222003-04-21 02:41:25 +00001#!/usr/bin/python
2
3#
4# Test suite for Optik. Supplied by Johannes Gijsbers
5# (taradino@softhome.net) -- translated from the original Optik
6# test suite to this PyUnit-based version.
7#
8# $Id$
9#
10
11import sys
12import os
Greg Wardab05edc2006-04-23 03:47:58 +000013import re
Greg Ward55493222003-04-21 02:41:25 +000014import copy
Greg Wardab05edc2006-04-23 03:47:58 +000015import types
Greg Ward55493222003-04-21 02:41:25 +000016import unittest
17
Greg Ward0e0c9f42006-06-11 16:24:11 +000018from StringIO import StringIO
Greg Ward55493222003-04-21 02:41:25 +000019from test import test_support
20
Greg Wardab05edc2006-04-23 03:47:58 +000021
Greg Ward48aa84b2004-10-27 02:20:04 +000022from optparse import make_option, Option, IndentedHelpFormatter, \
23 TitledHelpFormatter, OptionParser, OptionContainer, OptionGroup, \
24 SUPPRESS_HELP, SUPPRESS_USAGE, OptionError, OptionConflictError, \
Greg Wardab05edc2006-04-23 03:47:58 +000025 BadOptionError, OptionValueError, Values
26from optparse import _match_abbrev
27from optparse import _parse_num
Greg Ward48aa84b2004-10-27 02:20:04 +000028
29# Do the right thing with boolean values for all known Python versions.
30try:
31 True, False
32except NameError:
33 (True, False) = (1, 0)
34
Greg Wardab05edc2006-04-23 03:47:58 +000035retype = type(re.compile(''))
Greg Ward48aa84b2004-10-27 02:20:04 +000036
37class InterceptedError(Exception):
38 def __init__(self,
39 error_message=None,
40 exit_status=None,
41 exit_message=None):
42 self.error_message = error_message
43 self.exit_status = exit_status
44 self.exit_message = exit_message
45
46 def __str__(self):
47 return self.error_message or self.exit_message or "intercepted error"
48
49class InterceptingOptionParser(OptionParser):
50 def exit(self, status=0, msg=None):
51 raise InterceptedError(exit_status=status, exit_message=msg)
52
53 def error(self, msg):
54 raise InterceptedError(error_message=msg)
55
Greg Ward55493222003-04-21 02:41:25 +000056
57class BaseTest(unittest.TestCase):
58 def assertParseOK(self, args, expected_opts, expected_positional_args):
59 """Assert the options are what we expected when parsing arguments.
60
61 Otherwise, fail with a nicely formatted message.
62
63 Keyword arguments:
64 args -- A list of arguments to parse with OptionParser.
65 expected_opts -- The options expected.
66 expected_positional_args -- The positional arguments expected.
67
68 Returns the options and positional args for further testing.
69 """
70
71 (options, positional_args) = self.parser.parse_args(args)
72 optdict = vars(options)
73
74 self.assertEqual(optdict, expected_opts,
75 """
76Options are %(optdict)s.
77Should be %(expected_opts)s.
78Args were %(args)s.""" % locals())
79
80 self.assertEqual(positional_args, expected_positional_args,
81 """
82Positional arguments are %(positional_args)s.
83Should be %(expected_positional_args)s.
84Args were %(args)s.""" % locals ())
85
86 return (options, positional_args)
87
Greg Wardeba20e62004-07-31 16:15:44 +000088 def assertRaises(self,
89 func,
90 args,
91 kwargs,
92 expected_exception,
Greg Ward48aa84b2004-10-27 02:20:04 +000093 expected_message):
94 """
95 Assert that the expected exception is raised when calling a
96 function, and that the right error message is included with
97 that exception.
Greg Ward55493222003-04-21 02:41:25 +000098
Greg Wardeba20e62004-07-31 16:15:44 +000099 Arguments:
100 func -- the function to call
101 args -- positional arguments to `func`
102 kwargs -- keyword arguments to `func`
103 expected_exception -- exception that should be raised
Greg Wardab05edc2006-04-23 03:47:58 +0000104 expected_message -- expected exception message (or pattern
105 if a compiled regex object)
Greg Ward55493222003-04-21 02:41:25 +0000106
107 Returns the exception raised for further testing.
108 """
Greg Wardeba20e62004-07-31 16:15:44 +0000109 if args is None:
110 args = ()
111 if kwargs is None:
112 kwargs = {}
Greg Ward55493222003-04-21 02:41:25 +0000113
114 try:
Greg Ward48aa84b2004-10-27 02:20:04 +0000115 func(*args, **kwargs)
Greg Ward55493222003-04-21 02:41:25 +0000116 except expected_exception, err:
Greg Ward48aa84b2004-10-27 02:20:04 +0000117 actual_message = str(err)
Greg Wardab05edc2006-04-23 03:47:58 +0000118 if isinstance(expected_message, retype):
119 self.assert_(expected_message.search(actual_message),
Greg Ward48aa84b2004-10-27 02:20:04 +0000120 """\
Greg Wardab05edc2006-04-23 03:47:58 +0000121expected exception message pattern:
122/%s/
Greg Ward48aa84b2004-10-27 02:20:04 +0000123actual exception message:
Greg Wardab05edc2006-04-23 03:47:58 +0000124'''%s'''
125""" % (expected_message.pattern, actual_message))
126 else:
127 self.assertEqual(actual_message,
128 expected_message,
129 """\
130expected exception message:
131'''%s'''
132actual exception message:
133'''%s'''
134""" % (expected_message, actual_message))
Greg Ward55493222003-04-21 02:41:25 +0000135
136 return err
137 else:
Greg Wardeba20e62004-07-31 16:15:44 +0000138 self.fail("""expected exception %(expected_exception)s not raised
139called %(func)r
140with args %(args)r
141and kwargs %(kwargs)r
142""" % locals ())
Greg Ward55493222003-04-21 02:41:25 +0000143
Greg Wardeba20e62004-07-31 16:15:44 +0000144
Greg Ward55493222003-04-21 02:41:25 +0000145 # -- Assertions used in more than one class --------------------
146
147 def assertParseFail(self, cmdline_args, expected_output):
Greg Ward48aa84b2004-10-27 02:20:04 +0000148 """
149 Assert the parser fails with the expected message. Caller
150 must ensure that self.parser is an InterceptingOptionParser.
151 """
Tim Peters579f7352004-07-31 21:14:28 +0000152 try:
Greg Ward48aa84b2004-10-27 02:20:04 +0000153 self.parser.parse_args(cmdline_args)
154 except InterceptedError, err:
155 self.assertEqual(err.error_message, expected_output)
156 else:
157 self.assertFalse("expected parse failure")
Greg Ward55493222003-04-21 02:41:25 +0000158
Greg Ward48aa84b2004-10-27 02:20:04 +0000159 def assertOutput(self,
160 cmdline_args,
161 expected_output,
162 expected_status=0,
163 expected_error=None):
Greg Ward55493222003-04-21 02:41:25 +0000164 """Assert the parser prints the expected output on stdout."""
Tim Peters579f7352004-07-31 21:14:28 +0000165 save_stdout = sys.stdout
Greg Ward0e0c9f42006-06-11 16:24:11 +0000166 encoding = getattr(save_stdout, 'encoding', None)
Tim Peters579f7352004-07-31 21:14:28 +0000167 try:
Greg Ward48aa84b2004-10-27 02:20:04 +0000168 try:
169 sys.stdout = StringIO()
Greg Ward0e0c9f42006-06-11 16:24:11 +0000170 if encoding:
171 sys.stdout.encoding = encoding
Greg Ward48aa84b2004-10-27 02:20:04 +0000172 self.parser.parse_args(cmdline_args)
173 finally:
174 output = sys.stdout.getvalue()
175 sys.stdout = save_stdout
Greg Ward55493222003-04-21 02:41:25 +0000176
Greg Ward48aa84b2004-10-27 02:20:04 +0000177 except InterceptedError, err:
Greg Ward0e0c9f42006-06-11 16:24:11 +0000178 self.assert_(
179 type(output) is types.StringType,
180 "expected output to be an ordinary string, not %r"
181 % type(output))
182
Greg Wardab05edc2006-04-23 03:47:58 +0000183 if output != expected_output:
184 self.fail("expected: \n'''\n" + expected_output +
185 "'''\nbut got \n'''\n" + output + "'''")
Greg Ward48aa84b2004-10-27 02:20:04 +0000186 self.assertEqual(err.exit_status, expected_status)
187 self.assertEqual(err.exit_message, expected_error)
188 else:
189 self.assertFalse("expected parser.exit()")
190
191 def assertTypeError(self, func, expected_message, *args):
192 """Assert that TypeError is raised when executing func."""
193 self.assertRaises(func, args, None, TypeError, expected_message)
Greg Wardeba20e62004-07-31 16:15:44 +0000194
195 def assertHelp(self, parser, expected_help):
196 actual_help = parser.format_help()
197 if actual_help != expected_help:
198 raise self.failureException(
199 'help text failure; expected:\n"' +
200 expected_help + '"; got:\n"' +
201 actual_help + '"\n')
Greg Ward55493222003-04-21 02:41:25 +0000202
203# -- Test make_option() aka Option -------------------------------------
204
Greg Ward48aa84b2004-10-27 02:20:04 +0000205# It's not necessary to test correct options here. All the tests in the
Greg Ward55493222003-04-21 02:41:25 +0000206# parser.parse_args() section deal with those, because they're needed
Greg Ward48aa84b2004-10-27 02:20:04 +0000207# there.
Greg Ward55493222003-04-21 02:41:25 +0000208
209class TestOptionChecks(BaseTest):
210 def setUp(self):
211 self.parser = OptionParser(usage=SUPPRESS_USAGE)
212
Greg Ward48aa84b2004-10-27 02:20:04 +0000213 def assertOptionError(self, expected_message, args=[], kwargs={}):
Greg Wardeba20e62004-07-31 16:15:44 +0000214 self.assertRaises(make_option, args, kwargs,
Greg Ward48aa84b2004-10-27 02:20:04 +0000215 OptionError, expected_message)
Greg Ward55493222003-04-21 02:41:25 +0000216
217 def test_opt_string_empty(self):
218 self.assertTypeError(make_option,
219 "at least one option string must be supplied")
220
221 def test_opt_string_too_short(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000222 self.assertOptionError(
223 "invalid option string 'b': must be at least two characters long",
224 ["b"])
Greg Ward55493222003-04-21 02:41:25 +0000225
226 def test_opt_string_short_invalid(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000227 self.assertOptionError(
228 "invalid short option string '--': must be "
229 "of the form -x, (x any non-dash char)",
230 ["--"])
Greg Ward55493222003-04-21 02:41:25 +0000231
232 def test_opt_string_long_invalid(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000233 self.assertOptionError(
234 "invalid long option string '---': "
235 "must start with --, followed by non-dash",
236 ["---"])
Greg Ward55493222003-04-21 02:41:25 +0000237
238 def test_attr_invalid(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000239 self.assertOptionError(
Armin Rigoa3f09272006-05-28 19:13:17 +0000240 "option -b: invalid keyword arguments: bar, foo",
Greg Ward48aa84b2004-10-27 02:20:04 +0000241 ["-b"], {'foo': None, 'bar': None})
Greg Ward55493222003-04-21 02:41:25 +0000242
243 def test_action_invalid(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000244 self.assertOptionError(
245 "option -b: invalid action: 'foo'",
246 ["-b"], {'action': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000247
248 def test_type_invalid(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000249 self.assertOptionError(
250 "option -b: invalid option type: 'foo'",
251 ["-b"], {'type': 'foo'})
252 self.assertOptionError(
253 "option -b: invalid option type: 'tuple'",
254 ["-b"], {'type': tuple})
Greg Ward55493222003-04-21 02:41:25 +0000255
256 def test_no_type_for_action(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000257 self.assertOptionError(
258 "option -b: must not supply a type for action 'count'",
259 ["-b"], {'action': 'count', 'type': 'int'})
Greg Ward55493222003-04-21 02:41:25 +0000260
261 def test_no_choices_list(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000262 self.assertOptionError(
263 "option -b/--bad: must supply a list of "
264 "choices for type 'choice'",
265 ["-b", "--bad"], {'type': "choice"})
Greg Ward55493222003-04-21 02:41:25 +0000266
267 def test_bad_choices_list(self):
268 typename = type('').__name__
Greg Ward48aa84b2004-10-27 02:20:04 +0000269 self.assertOptionError(
270 "option -b/--bad: choices must be a list of "
271 "strings ('%s' supplied)" % typename,
272 ["-b", "--bad"],
273 {'type': "choice", 'choices':"bad choices"})
Greg Ward55493222003-04-21 02:41:25 +0000274
275 def test_no_choices_for_type(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000276 self.assertOptionError(
277 "option -b: must not supply choices for type 'int'",
278 ["-b"], {'type': 'int', 'choices':"bad"})
Greg Ward55493222003-04-21 02:41:25 +0000279
280 def test_no_const_for_action(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000281 self.assertOptionError(
282 "option -b: 'const' must not be supplied for action 'store'",
283 ["-b"], {'action': 'store', 'const': 1})
Greg Ward55493222003-04-21 02:41:25 +0000284
285 def test_no_nargs_for_action(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000286 self.assertOptionError(
287 "option -b: 'nargs' must not be supplied for action 'count'",
288 ["-b"], {'action': 'count', 'nargs': 2})
Greg Ward55493222003-04-21 02:41:25 +0000289
290 def test_callback_not_callable(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000291 self.assertOptionError(
292 "option -b: callback not callable: 'foo'",
293 ["-b"], {'action': 'callback',
294 'callback': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000295
296 def dummy(self):
297 pass
298
299 def test_callback_args_no_tuple(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000300 self.assertOptionError(
301 "option -b: callback_args, if supplied, "
302 "must be a tuple: not 'foo'",
303 ["-b"], {'action': 'callback',
304 'callback': self.dummy,
305 'callback_args': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000306
307 def test_callback_kwargs_no_dict(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000308 self.assertOptionError(
309 "option -b: callback_kwargs, if supplied, "
310 "must be a dict: not 'foo'",
311 ["-b"], {'action': 'callback',
312 'callback': self.dummy,
313 'callback_kwargs': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000314
315 def test_no_callback_for_action(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000316 self.assertOptionError(
317 "option -b: callback supplied ('foo') for non-callback option",
318 ["-b"], {'action': 'store',
319 'callback': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000320
321 def test_no_callback_args_for_action(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000322 self.assertOptionError(
323 "option -b: callback_args supplied for non-callback option",
324 ["-b"], {'action': 'store',
325 'callback_args': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000326
327 def test_no_callback_kwargs_for_action(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000328 self.assertOptionError(
329 "option -b: callback_kwargs supplied for non-callback option",
330 ["-b"], {'action': 'store',
331 'callback_kwargs': 'foo'})
Greg Ward55493222003-04-21 02:41:25 +0000332
333class TestOptionParser(BaseTest):
334 def setUp(self):
335 self.parser = OptionParser()
336 self.parser.add_option("-v", "--verbose", "-n", "--noisy",
337 action="store_true", dest="verbose")
338 self.parser.add_option("-q", "--quiet", "--silent",
339 action="store_false", dest="verbose")
340
341 def test_add_option_no_Option(self):
342 self.assertTypeError(self.parser.add_option,
343 "not an Option instance: None", None)
344
345 def test_add_option_invalid_arguments(self):
346 self.assertTypeError(self.parser.add_option,
347 "invalid arguments", None, None)
348
349 def test_get_option(self):
350 opt1 = self.parser.get_option("-v")
351 self.assert_(isinstance(opt1, Option))
352 self.assertEqual(opt1._short_opts, ["-v", "-n"])
353 self.assertEqual(opt1._long_opts, ["--verbose", "--noisy"])
354 self.assertEqual(opt1.action, "store_true")
355 self.assertEqual(opt1.dest, "verbose")
356
357 def test_get_option_equals(self):
358 opt1 = self.parser.get_option("-v")
359 opt2 = self.parser.get_option("--verbose")
360 opt3 = self.parser.get_option("-n")
361 opt4 = self.parser.get_option("--noisy")
362 self.assert_(opt1 is opt2 is opt3 is opt4)
363
364 def test_has_option(self):
365 self.assert_(self.parser.has_option("-v"))
366 self.assert_(self.parser.has_option("--verbose"))
367
368 def assert_removed(self):
369 self.assert_(self.parser.get_option("-v") is None)
370 self.assert_(self.parser.get_option("--verbose") is None)
371 self.assert_(self.parser.get_option("-n") is None)
372 self.assert_(self.parser.get_option("--noisy") is None)
373
374 self.failIf(self.parser.has_option("-v"))
375 self.failIf(self.parser.has_option("--verbose"))
376 self.failIf(self.parser.has_option("-n"))
377 self.failIf(self.parser.has_option("--noisy"))
378
379 self.assert_(self.parser.has_option("-q"))
380 self.assert_(self.parser.has_option("--silent"))
381
382 def test_remove_short_opt(self):
383 self.parser.remove_option("-n")
384 self.assert_removed()
385
386 def test_remove_long_opt(self):
387 self.parser.remove_option("--verbose")
388 self.assert_removed()
389
390 def test_remove_nonexistent(self):
Greg Wardeba20e62004-07-31 16:15:44 +0000391 self.assertRaises(self.parser.remove_option, ('foo',), None,
392 ValueError, "no such option 'foo'")
393
Greg Wardab05edc2006-04-23 03:47:58 +0000394 def test_refleak(self):
395 # If an OptionParser is carrying around a reference to a large
396 # object, various cycles can prevent it from being GC'd in
397 # a timely fashion. destroy() breaks the cycles to ensure stuff
398 # can be cleaned up.
399 big_thing = [42]
400 refcount = sys.getrefcount(big_thing)
401 parser = OptionParser()
402 parser.add_option("-a", "--aaarggh")
403 parser.big_thing = big_thing
404
405 parser.destroy()
406 #self.assertEqual(refcount, sys.getrefcount(big_thing))
407 del parser
408 self.assertEqual(refcount, sys.getrefcount(big_thing))
409
410
Greg Ward48aa84b2004-10-27 02:20:04 +0000411class TestOptionValues(BaseTest):
412 def setUp(self):
413 pass
414
415 def test_basics(self):
416 values = Values()
417 self.assertEqual(vars(values), {})
418 self.assertEqual(values, {})
419 self.assertNotEqual(values, {"foo": "bar"})
420 self.assertNotEqual(values, "")
421
422 dict = {"foo": "bar", "baz": 42}
423 values = Values(defaults=dict)
424 self.assertEqual(vars(values), dict)
425 self.assertEqual(values, dict)
426 self.assertNotEqual(values, {"foo": "bar"})
427 self.assertNotEqual(values, {})
428 self.assertNotEqual(values, "")
429 self.assertNotEqual(values, [])
430
431
Greg Wardeba20e62004-07-31 16:15:44 +0000432class TestTypeAliases(BaseTest):
433 def setUp(self):
434 self.parser = OptionParser()
435
Greg Wardab05edc2006-04-23 03:47:58 +0000436 def test_str_aliases_string(self):
437 self.parser.add_option("-s", type="str")
Greg Wardeba20e62004-07-31 16:15:44 +0000438 self.assertEquals(self.parser.get_option("-s").type, "string")
Greg Wardab05edc2006-04-23 03:47:58 +0000439
440 def test_new_type_object(self):
441 self.parser.add_option("-s", type=str)
442 self.assertEquals(self.parser.get_option("-s").type, "string")
443 self.parser.add_option("-x", type=int)
444 self.assertEquals(self.parser.get_option("-x").type, "int")
445
446 def test_old_type_object(self):
447 self.parser.add_option("-s", type=types.StringType)
448 self.assertEquals(self.parser.get_option("-s").type, "string")
449 self.parser.add_option("-x", type=types.IntType)
450 self.assertEquals(self.parser.get_option("-x").type, "int")
Tim Peters10d59f32004-10-27 02:43:25 +0000451
Greg Wardeba20e62004-07-31 16:15:44 +0000452
453# Custom type for testing processing of default values.
454_time_units = { 's' : 1, 'm' : 60, 'h' : 60*60, 'd' : 60*60*24 }
455
456def _check_duration(option, opt, value):
457 try:
458 if value[-1].isdigit():
459 return int(value)
460 else:
461 return int(value[:-1]) * _time_units[value[-1]]
Georg Brandl9bbf8362010-02-07 13:02:10 +0000462 except (ValueError, IndexError):
Greg Wardeba20e62004-07-31 16:15:44 +0000463 raise OptionValueError(
464 'option %s: invalid duration: %r' % (opt, value))
465
466class DurationOption(Option):
467 TYPES = Option.TYPES + ('duration',)
468 TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
469 TYPE_CHECKER['duration'] = _check_duration
470
471class TestDefaultValues(BaseTest):
472 def setUp(self):
473 self.parser = OptionParser()
474 self.parser.add_option("-v", "--verbose", default=True)
475 self.parser.add_option("-q", "--quiet", dest='verbose')
476 self.parser.add_option("-n", type="int", default=37)
477 self.parser.add_option("-m", type="int")
478 self.parser.add_option("-s", default="foo")
479 self.parser.add_option("-t")
480 self.parser.add_option("-u", default=None)
481 self.expected = { 'verbose': True,
482 'n': 37,
483 'm': None,
484 's': "foo",
485 't': None,
486 'u': None }
487
488 def test_basic_defaults(self):
489 self.assertEqual(self.parser.get_default_values(), self.expected)
490
491 def test_mixed_defaults_post(self):
492 self.parser.set_defaults(n=42, m=-100)
493 self.expected.update({'n': 42, 'm': -100})
494 self.assertEqual(self.parser.get_default_values(), self.expected)
495
496 def test_mixed_defaults_pre(self):
497 self.parser.set_defaults(x="barf", y="blah")
498 self.parser.add_option("-x", default="frob")
499 self.parser.add_option("-y")
500
501 self.expected.update({'x': "frob", 'y': "blah"})
502 self.assertEqual(self.parser.get_default_values(), self.expected)
503
504 self.parser.remove_option("-y")
505 self.parser.add_option("-y", default=None)
506 self.expected.update({'y': None})
507 self.assertEqual(self.parser.get_default_values(), self.expected)
508
509 def test_process_default(self):
510 self.parser.option_class = DurationOption
511 self.parser.add_option("-d", type="duration", default=300)
512 self.parser.add_option("-e", type="duration", default="6m")
513 self.parser.set_defaults(n="42")
514 self.expected.update({'d': 300, 'e': 360, 'n': 42})
515 self.assertEqual(self.parser.get_default_values(), self.expected)
516
517 self.parser.set_process_default_values(False)
518 self.expected.update({'d': 300, 'e': "6m", 'n': "42"})
519 self.assertEqual(self.parser.get_default_values(), self.expected)
520
521
522class TestProgName(BaseTest):
523 """
524 Test that %prog expands to the right thing in usage, version,
525 and help strings.
526 """
527
528 def assertUsage(self, parser, expected_usage):
529 self.assertEqual(parser.get_usage(), expected_usage)
530
531 def assertVersion(self, parser, expected_version):
532 self.assertEqual(parser.get_version(), expected_version)
533
534
535 def test_default_progname(self):
536 # Make sure that program name taken from sys.argv[0] by default.
Tim Peters579f7352004-07-31 21:14:28 +0000537 save_argv = sys.argv[:]
538 try:
Greg Ward48aa84b2004-10-27 02:20:04 +0000539 sys.argv[0] = os.path.join("foo", "bar", "baz.py")
Greg Wardab05edc2006-04-23 03:47:58 +0000540 parser = OptionParser("%prog ...", version="%prog 1.2")
541 expected_usage = "Usage: baz.py ...\n"
Tim Peters579f7352004-07-31 21:14:28 +0000542 self.assertUsage(parser, expected_usage)
543 self.assertVersion(parser, "baz.py 1.2")
544 self.assertHelp(parser,
Greg Ward48aa84b2004-10-27 02:20:04 +0000545 expected_usage + "\n" +
Greg Wardab05edc2006-04-23 03:47:58 +0000546 "Options:\n"
Greg Ward48aa84b2004-10-27 02:20:04 +0000547 " --version show program's version number and exit\n"
548 " -h, --help show this help message and exit\n")
Tim Peters579f7352004-07-31 21:14:28 +0000549 finally:
550 sys.argv[:] = save_argv
Greg Wardeba20e62004-07-31 16:15:44 +0000551
552 def test_custom_progname(self):
553 parser = OptionParser(prog="thingy",
554 version="%prog 0.1",
555 usage="%prog arg arg")
556 parser.remove_option("-h")
557 parser.remove_option("--version")
Greg Wardab05edc2006-04-23 03:47:58 +0000558 expected_usage = "Usage: thingy arg arg\n"
Greg Wardeba20e62004-07-31 16:15:44 +0000559 self.assertUsage(parser, expected_usage)
560 self.assertVersion(parser, "thingy 0.1")
561 self.assertHelp(parser, expected_usage + "\n")
562
563
564class TestExpandDefaults(BaseTest):
565 def setUp(self):
566 self.parser = OptionParser(prog="test")
567 self.help_prefix = """\
Greg Wardab05edc2006-04-23 03:47:58 +0000568Usage: test [options]
Greg Wardeba20e62004-07-31 16:15:44 +0000569
Greg Wardab05edc2006-04-23 03:47:58 +0000570Options:
Greg Wardeba20e62004-07-31 16:15:44 +0000571 -h, --help show this help message and exit
572"""
573 self.file_help = "read from FILE [default: %default]"
574 self.expected_help_file = self.help_prefix + \
575 " -f FILE, --file=FILE read from FILE [default: foo.txt]\n"
576 self.expected_help_none = self.help_prefix + \
577 " -f FILE, --file=FILE read from FILE [default: none]\n"
578
579 def test_option_default(self):
580 self.parser.add_option("-f", "--file",
581 default="foo.txt",
582 help=self.file_help)
583 self.assertHelp(self.parser, self.expected_help_file)
584
585 def test_parser_default_1(self):
586 self.parser.add_option("-f", "--file",
587 help=self.file_help)
588 self.parser.set_default('file', "foo.txt")
589 self.assertHelp(self.parser, self.expected_help_file)
590
591 def test_parser_default_2(self):
592 self.parser.add_option("-f", "--file",
593 help=self.file_help)
594 self.parser.set_defaults(file="foo.txt")
595 self.assertHelp(self.parser, self.expected_help_file)
596
597 def test_no_default(self):
598 self.parser.add_option("-f", "--file",
599 help=self.file_help)
600 self.assertHelp(self.parser, self.expected_help_none)
601
602 def test_default_none_1(self):
603 self.parser.add_option("-f", "--file",
604 default=None,
605 help=self.file_help)
606 self.assertHelp(self.parser, self.expected_help_none)
Tim Peters10d59f32004-10-27 02:43:25 +0000607
Greg Wardeba20e62004-07-31 16:15:44 +0000608 def test_default_none_2(self):
609 self.parser.add_option("-f", "--file",
610 help=self.file_help)
611 self.parser.set_defaults(file=None)
612 self.assertHelp(self.parser, self.expected_help_none)
613
614 def test_float_default(self):
615 self.parser.add_option(
616 "-p", "--prob",
617 help="blow up with probability PROB [default: %default]")
618 self.parser.set_defaults(prob=0.43)
619 expected_help = self.help_prefix + \
620 " -p PROB, --prob=PROB blow up with probability PROB [default: 0.43]\n"
621 self.assertHelp(self.parser, expected_help)
622
623 def test_alt_expand(self):
624 self.parser.add_option("-f", "--file",
625 default="foo.txt",
626 help="read from FILE [default: *DEFAULT*]")
627 self.parser.formatter.default_tag = "*DEFAULT*"
628 self.assertHelp(self.parser, self.expected_help_file)
629
630 def test_no_expand(self):
631 self.parser.add_option("-f", "--file",
632 default="foo.txt",
633 help="read from %default file")
634 self.parser.formatter.default_tag = None
635 expected_help = self.help_prefix + \
636 " -f FILE, --file=FILE read from %default file\n"
637 self.assertHelp(self.parser, expected_help)
638
Greg Ward55493222003-04-21 02:41:25 +0000639
640# -- Test parser.parse_args() ------------------------------------------
641
642class TestStandard(BaseTest):
643 def setUp(self):
644 options = [make_option("-a", type="string"),
645 make_option("-b", "--boo", type="int", dest='boo'),
646 make_option("--foo", action="append")]
647
Greg Ward48aa84b2004-10-27 02:20:04 +0000648 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
649 option_list=options)
Greg Ward55493222003-04-21 02:41:25 +0000650
651 def test_required_value(self):
Greg Wardeba20e62004-07-31 16:15:44 +0000652 self.assertParseFail(["-a"], "-a option requires an argument")
Greg Ward55493222003-04-21 02:41:25 +0000653
654 def test_invalid_integer(self):
655 self.assertParseFail(["-b", "5x"],
656 "option -b: invalid integer value: '5x'")
657
658 def test_no_such_option(self):
659 self.assertParseFail(["--boo13"], "no such option: --boo13")
660
661 def test_long_invalid_integer(self):
662 self.assertParseFail(["--boo=x5"],
663 "option --boo: invalid integer value: 'x5'")
664
665 def test_empty(self):
666 self.assertParseOK([], {'a': None, 'boo': None, 'foo': None}, [])
667
668 def test_shortopt_empty_longopt_append(self):
669 self.assertParseOK(["-a", "", "--foo=blah", "--foo="],
670 {'a': "", 'boo': None, 'foo': ["blah", ""]},
671 [])
672
673 def test_long_option_append(self):
674 self.assertParseOK(["--foo", "bar", "--foo", "", "--foo=x"],
675 {'a': None,
676 'boo': None,
677 'foo': ["bar", "", "x"]},
678 [])
679
680 def test_option_argument_joined(self):
681 self.assertParseOK(["-abc"],
682 {'a': "bc", 'boo': None, 'foo': None},
683 [])
684
685 def test_option_argument_split(self):
686 self.assertParseOK(["-a", "34"],
687 {'a': "34", 'boo': None, 'foo': None},
688 [])
689
690 def test_option_argument_joined_integer(self):
691 self.assertParseOK(["-b34"],
692 {'a': None, 'boo': 34, 'foo': None},
693 [])
694
695 def test_option_argument_split_negative_integer(self):
696 self.assertParseOK(["-b", "-5"],
697 {'a': None, 'boo': -5, 'foo': None},
698 [])
699
700 def test_long_option_argument_joined(self):
701 self.assertParseOK(["--boo=13"],
702 {'a': None, 'boo': 13, 'foo': None},
703 [])
704
705 def test_long_option_argument_split(self):
706 self.assertParseOK(["--boo", "111"],
707 {'a': None, 'boo': 111, 'foo': None},
708 [])
709
710 def test_long_option_short_option(self):
711 self.assertParseOK(["--foo=bar", "-axyz"],
712 {'a': 'xyz', 'boo': None, 'foo': ["bar"]},
713 [])
714
715 def test_abbrev_long_option(self):
716 self.assertParseOK(["--f=bar", "-axyz"],
717 {'a': 'xyz', 'boo': None, 'foo': ["bar"]},
718 [])
719
720 def test_defaults(self):
721 (options, args) = self.parser.parse_args([])
722 defaults = self.parser.get_default_values()
723 self.assertEqual(vars(defaults), vars(options))
724
725 def test_ambiguous_option(self):
726 self.parser.add_option("--foz", action="store",
727 type="string", dest="foo")
Greg Ward55493222003-04-21 02:41:25 +0000728 self.assertParseFail(["--f=bar"],
Armin Rigoa3f09272006-05-28 19:13:17 +0000729 "ambiguous option: --f (--foo, --foz?)")
Greg Ward55493222003-04-21 02:41:25 +0000730
731
732 def test_short_and_long_option_split(self):
733 self.assertParseOK(["-a", "xyz", "--foo", "bar"],
734 {'a': 'xyz', 'boo': None, 'foo': ["bar"]},
735 []),
736
737 def test_short_option_split_long_option_append(self):
738 self.assertParseOK(["--foo=bar", "-b", "123", "--foo", "baz"],
739 {'a': None, 'boo': 123, 'foo': ["bar", "baz"]},
740 [])
741
742 def test_short_option_split_one_positional_arg(self):
743 self.assertParseOK(["-a", "foo", "bar"],
744 {'a': "foo", 'boo': None, 'foo': None},
745 ["bar"]),
746
747 def test_short_option_consumes_separator(self):
748 self.assertParseOK(["-a", "--", "foo", "bar"],
749 {'a': "--", 'boo': None, 'foo': None},
750 ["foo", "bar"]),
Greg Wardab05edc2006-04-23 03:47:58 +0000751 self.assertParseOK(["-a", "--", "--foo", "bar"],
752 {'a': "--", 'boo': None, 'foo': ["bar"]},
753 []),
Greg Ward55493222003-04-21 02:41:25 +0000754
755 def test_short_option_joined_and_separator(self):
756 self.assertParseOK(["-ab", "--", "--foo", "bar"],
757 {'a': "b", 'boo': None, 'foo': None},
758 ["--foo", "bar"]),
759
Greg Wardab05edc2006-04-23 03:47:58 +0000760 def test_hyphen_becomes_positional_arg(self):
Greg Ward55493222003-04-21 02:41:25 +0000761 self.assertParseOK(["-ab", "-", "--foo", "bar"],
762 {'a': "b", 'boo': None, 'foo': ["bar"]},
763 ["-"])
764
765 def test_no_append_versus_append(self):
766 self.assertParseOK(["-b3", "-b", "5", "--foo=bar", "--foo", "baz"],
767 {'a': None, 'boo': 5, 'foo': ["bar", "baz"]},
768 [])
769
770 def test_option_consumes_optionlike_string(self):
771 self.assertParseOK(["-a", "-b3"],
772 {'a': "-b3", 'boo': None, 'foo': None},
773 [])
774
R. David Murray5efa1522010-06-26 03:32:13 +0000775 def test_combined_single_invalid_option(self):
776 self.parser.add_option("-t", action="store_true")
777 self.assertParseFail(["-test"],
778 "no such option: -e")
779
Greg Ward55493222003-04-21 02:41:25 +0000780class TestBool(BaseTest):
781 def setUp(self):
782 options = [make_option("-v",
783 "--verbose",
784 action="store_true",
785 dest="verbose",
786 default=''),
787 make_option("-q",
788 "--quiet",
789 action="store_false",
790 dest="verbose")]
791 self.parser = OptionParser(option_list = options)
792
793 def test_bool_default(self):
794 self.assertParseOK([],
795 {'verbose': ''},
796 [])
797
798 def test_bool_false(self):
799 (options, args) = self.assertParseOK(["-q"],
800 {'verbose': 0},
801 [])
802 if hasattr(__builtins__, 'False'):
803 self.failUnless(options.verbose is False)
804
805 def test_bool_true(self):
806 (options, args) = self.assertParseOK(["-v"],
807 {'verbose': 1},
808 [])
809 if hasattr(__builtins__, 'True'):
810 self.failUnless(options.verbose is True)
811
812 def test_bool_flicker_on_and_off(self):
813 self.assertParseOK(["-qvq", "-q", "-v"],
814 {'verbose': 1},
815 [])
816
817class TestChoice(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.parser.add_option("-c", action="store", type="choice",
821 dest="choice", choices=["one", "two", "three"])
822
823 def test_valid_choice(self):
824 self.assertParseOK(["-c", "one", "xyz"],
825 {'choice': 'one'},
826 ["xyz"])
827
828 def test_invalid_choice(self):
829 self.assertParseFail(["-c", "four", "abc"],
830 "option -c: invalid choice: 'four' "
831 "(choose from 'one', 'two', 'three')")
832
833 def test_add_choice_option(self):
834 self.parser.add_option("-d", "--default",
835 choices=["four", "five", "six"])
836 opt = self.parser.get_option("-d")
837 self.assertEqual(opt.type, "choice")
838 self.assertEqual(opt.action, "store")
839
840class TestCount(BaseTest):
841 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000842 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000843 self.v_opt = make_option("-v", action="count", dest="verbose")
844 self.parser.add_option(self.v_opt)
845 self.parser.add_option("--verbose", type="int", dest="verbose")
846 self.parser.add_option("-q", "--quiet",
847 action="store_const", dest="verbose", const=0)
848
849 def test_empty(self):
850 self.assertParseOK([], {'verbose': None}, [])
851
852 def test_count_one(self):
853 self.assertParseOK(["-v"], {'verbose': 1}, [])
854
855 def test_count_three(self):
856 self.assertParseOK(["-vvv"], {'verbose': 3}, [])
857
858 def test_count_three_apart(self):
859 self.assertParseOK(["-v", "-v", "-v"], {'verbose': 3}, [])
860
861 def test_count_override_amount(self):
862 self.assertParseOK(["-vvv", "--verbose=2"], {'verbose': 2}, [])
863
864 def test_count_override_quiet(self):
865 self.assertParseOK(["-vvv", "--verbose=2", "-q"], {'verbose': 0}, [])
866
867 def test_count_overriding(self):
868 self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"],
869 {'verbose': 1}, [])
870
871 def test_count_interspersed_args(self):
872 self.assertParseOK(["--quiet", "3", "-v"],
873 {'verbose': 1},
874 ["3"])
875
876 def test_count_no_interspersed_args(self):
877 self.parser.disable_interspersed_args()
878 self.assertParseOK(["--quiet", "3", "-v"],
879 {'verbose': 0},
880 ["3", "-v"])
881
882 def test_count_no_such_option(self):
883 self.assertParseFail(["-q3", "-v"], "no such option: -3")
884
885 def test_count_option_no_value(self):
886 self.assertParseFail(["--quiet=3", "-v"],
887 "--quiet option does not take a value")
888
889 def test_count_with_default(self):
890 self.parser.set_default('verbose', 0)
891 self.assertParseOK([], {'verbose':0}, [])
892
893 def test_count_overriding_default(self):
894 self.parser.set_default('verbose', 0)
895 self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"],
896 {'verbose': 1}, [])
897
Greg Ward48aa84b2004-10-27 02:20:04 +0000898class TestMultipleArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +0000899 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000900 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000901 self.parser.add_option("-p", "--point",
902 action="store", nargs=3, type="float", dest="point")
903
904 def test_nargs_with_positional_args(self):
905 self.assertParseOK(["foo", "-p", "1", "2.5", "-4.3", "xyz"],
906 {'point': (1.0, 2.5, -4.3)},
907 ["foo", "xyz"])
908
909 def test_nargs_long_opt(self):
910 self.assertParseOK(["--point", "-1", "2.5", "-0", "xyz"],
911 {'point': (-1.0, 2.5, -0.0)},
912 ["xyz"])
913
914 def test_nargs_invalid_float_value(self):
915 self.assertParseFail(["-p", "1.0", "2x", "3.5"],
916 "option -p: "
917 "invalid floating-point value: '2x'")
918
919 def test_nargs_required_values(self):
920 self.assertParseFail(["--point", "1.0", "3.5"],
Greg Wardeba20e62004-07-31 16:15:44 +0000921 "--point option requires 3 arguments")
Greg Ward55493222003-04-21 02:41:25 +0000922
Greg Ward48aa84b2004-10-27 02:20:04 +0000923class TestMultipleArgsAppend(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +0000924 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000925 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000926 self.parser.add_option("-p", "--point", action="store", nargs=3,
927 type="float", dest="point")
928 self.parser.add_option("-f", "--foo", action="append", nargs=2,
929 type="int", dest="foo")
Greg Wardab05edc2006-04-23 03:47:58 +0000930 self.parser.add_option("-z", "--zero", action="append_const",
931 dest="foo", const=(0, 0))
Greg Ward55493222003-04-21 02:41:25 +0000932
933 def test_nargs_append(self):
934 self.assertParseOK(["-f", "4", "-3", "blah", "--foo", "1", "666"],
935 {'point': None, 'foo': [(4, -3), (1, 666)]},
936 ["blah"])
937
938 def test_nargs_append_required_values(self):
939 self.assertParseFail(["-f4,3"],
Greg Wardeba20e62004-07-31 16:15:44 +0000940 "-f option requires 2 arguments")
Greg Ward55493222003-04-21 02:41:25 +0000941
942 def test_nargs_append_simple(self):
943 self.assertParseOK(["--foo=3", "4"],
944 {'point': None, 'foo':[(3, 4)]},
945 [])
946
Greg Wardab05edc2006-04-23 03:47:58 +0000947 def test_nargs_append_const(self):
948 self.assertParseOK(["--zero", "--foo", "3", "4", "-z"],
949 {'point': None, 'foo':[(0, 0), (3, 4), (0, 0)]},
950 [])
951
Greg Ward55493222003-04-21 02:41:25 +0000952class TestVersion(BaseTest):
953 def test_version(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000954 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
955 version="%prog 0.1")
956 save_argv = sys.argv[:]
957 try:
958 sys.argv[0] = os.path.join(os.curdir, "foo", "bar")
959 self.assertOutput(["--version"], "bar 0.1\n")
960 finally:
961 sys.argv[:] = save_argv
Greg Ward55493222003-04-21 02:41:25 +0000962
963 def test_no_version(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000964 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000965 self.assertParseFail(["--version"],
966 "no such option: --version")
967
968# -- Test conflicting default values and parser.parse_args() -----------
969
970class TestConflictingDefaults(BaseTest):
971 """Conflicting default values: the last one should win."""
972 def setUp(self):
973 self.parser = OptionParser(option_list=[
974 make_option("-v", action="store_true", dest="verbose", default=1)])
975
976 def test_conflict_default(self):
977 self.parser.add_option("-q", action="store_false", dest="verbose",
978 default=0)
979 self.assertParseOK([], {'verbose': 0}, [])
980
981 def test_conflict_default_none(self):
982 self.parser.add_option("-q", action="store_false", dest="verbose",
983 default=None)
984 self.assertParseOK([], {'verbose': None}, [])
985
986class TestOptionGroup(BaseTest):
987 def setUp(self):
988 self.parser = OptionParser(usage=SUPPRESS_USAGE)
989
990 def test_option_group_create_instance(self):
991 group = OptionGroup(self.parser, "Spam")
992 self.parser.add_option_group(group)
993 group.add_option("--spam", action="store_true",
994 help="spam spam spam spam")
995 self.assertParseOK(["--spam"], {'spam': 1}, [])
996
997 def test_add_group_no_group(self):
998 self.assertTypeError(self.parser.add_option_group,
999 "not an OptionGroup instance: None", None)
1000
1001 def test_add_group_invalid_arguments(self):
1002 self.assertTypeError(self.parser.add_option_group,
1003 "invalid arguments", None, None)
1004
1005 def test_add_group_wrong_parser(self):
1006 group = OptionGroup(self.parser, "Spam")
1007 group.parser = OptionParser()
Greg Wardeba20e62004-07-31 16:15:44 +00001008 self.assertRaises(self.parser.add_option_group, (group,), None,
1009 ValueError, "invalid OptionGroup (wrong parser)")
Greg Ward55493222003-04-21 02:41:25 +00001010
1011 def test_group_manipulate(self):
1012 group = self.parser.add_option_group("Group 2",
1013 description="Some more options")
1014 group.set_title("Bacon")
1015 group.add_option("--bacon", type="int")
1016 self.assert_(self.parser.get_option_group("--bacon"), group)
1017
1018# -- Test extending and parser.parse_args() ----------------------------
1019
1020class TestExtendAddTypes(BaseTest):
1021 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +00001022 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
1023 option_class=self.MyOption)
Greg Ward55493222003-04-21 02:41:25 +00001024 self.parser.add_option("-a", None, type="string", dest="a")
1025 self.parser.add_option("-f", "--file", type="file", dest="file")
1026
Greg Wardab05edc2006-04-23 03:47:58 +00001027 def tearDown(self):
1028 if os.path.isdir(test_support.TESTFN):
1029 os.rmdir(test_support.TESTFN)
1030 elif os.path.isfile(test_support.TESTFN):
1031 os.unlink(test_support.TESTFN)
1032
Greg Ward55493222003-04-21 02:41:25 +00001033 class MyOption (Option):
Greg Wardab05edc2006-04-23 03:47:58 +00001034 def check_file(option, opt, value):
Greg Ward55493222003-04-21 02:41:25 +00001035 if not os.path.exists(value):
1036 raise OptionValueError("%s: file does not exist" % value)
1037 elif not os.path.isfile(value):
1038 raise OptionValueError("%s: not a regular file" % value)
1039 return value
1040
1041 TYPES = Option.TYPES + ("file",)
1042 TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
1043 TYPE_CHECKER["file"] = check_file
1044
Greg Wardab05edc2006-04-23 03:47:58 +00001045 def test_filetype_ok(self):
Greg Ward55493222003-04-21 02:41:25 +00001046 open(test_support.TESTFN, "w").close()
1047 self.assertParseOK(["--file", test_support.TESTFN, "-afoo"],
1048 {'file': test_support.TESTFN, 'a': 'foo'},
1049 [])
1050
Greg Wardab05edc2006-04-23 03:47:58 +00001051 def test_filetype_noexist(self):
Greg Ward55493222003-04-21 02:41:25 +00001052 self.assertParseFail(["--file", test_support.TESTFN, "-afoo"],
1053 "%s: file does not exist" %
1054 test_support.TESTFN)
1055
Greg Wardab05edc2006-04-23 03:47:58 +00001056 def test_filetype_notfile(self):
Greg Ward55493222003-04-21 02:41:25 +00001057 os.mkdir(test_support.TESTFN)
1058 self.assertParseFail(["--file", test_support.TESTFN, "-afoo"],
1059 "%s: not a regular file" %
1060 test_support.TESTFN)
Greg Wardab05edc2006-04-23 03:47:58 +00001061
Greg Ward55493222003-04-21 02:41:25 +00001062
1063class TestExtendAddActions(BaseTest):
1064 def setUp(self):
1065 options = [self.MyOption("-a", "--apple", action="extend",
1066 type="string", dest="apple")]
1067 self.parser = OptionParser(option_list=options)
1068
1069 class MyOption (Option):
1070 ACTIONS = Option.ACTIONS + ("extend",)
1071 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1072 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1073
Greg Wardab05edc2006-04-23 03:47:58 +00001074 def take_action(self, action, dest, opt, value, values, parser):
Greg Ward55493222003-04-21 02:41:25 +00001075 if action == "extend":
1076 lvalue = value.split(",")
1077 values.ensure_value(dest, []).extend(lvalue)
1078 else:
1079 Option.take_action(self, action, dest, opt, parser, value,
1080 values)
1081
1082 def test_extend_add_action(self):
1083 self.assertParseOK(["-afoo,bar", "--apple=blah"],
1084 {'apple': ["foo", "bar", "blah"]},
1085 [])
1086
1087 def test_extend_add_action_normal(self):
1088 self.assertParseOK(["-a", "foo", "-abar", "--apple=x,y"],
1089 {'apple': ["foo", "bar", "x", "y"]},
1090 [])
1091
1092# -- Test callbacks and parser.parse_args() ----------------------------
1093
1094class TestCallback(BaseTest):
1095 def setUp(self):
1096 options = [make_option("-x",
1097 None,
1098 action="callback",
1099 callback=self.process_opt),
1100 make_option("-f",
1101 "--file",
1102 action="callback",
1103 callback=self.process_opt,
1104 type="string",
1105 dest="filename")]
1106 self.parser = OptionParser(option_list=options)
1107
1108 def process_opt(self, option, opt, value, parser_):
1109 if opt == "-x":
1110 self.assertEqual(option._short_opts, ["-x"])
1111 self.assertEqual(option._long_opts, [])
1112 self.assert_(parser_ is self.parser)
1113 self.assert_(value is None)
1114 self.assertEqual(vars(parser_.values), {'filename': None})
1115
1116 parser_.values.x = 42
1117 elif opt == "--file":
1118 self.assertEqual(option._short_opts, ["-f"])
1119 self.assertEqual(option._long_opts, ["--file"])
1120 self.assert_(parser_ is self.parser)
1121 self.assertEqual(value, "foo")
1122 self.assertEqual(vars(parser_.values), {'filename': None, 'x': 42})
1123
1124 setattr(parser_.values, option.dest, value)
1125 else:
1126 self.fail("Unknown option %r in process_opt." % opt)
1127
1128 def test_callback(self):
1129 self.assertParseOK(["-x", "--file=foo"],
1130 {'filename': "foo", 'x': 42},
1131 [])
1132
Greg Wardeba20e62004-07-31 16:15:44 +00001133 def test_callback_help(self):
1134 # This test was prompted by SF bug #960515 -- the point is
1135 # not to inspect the help text, just to make sure that
1136 # format_help() doesn't crash.
1137 parser = OptionParser(usage=SUPPRESS_USAGE)
1138 parser.remove_option("-h")
1139 parser.add_option("-t", "--test", action="callback",
1140 callback=lambda: None, type="string",
1141 help="foo")
1142
Greg Wardab05edc2006-04-23 03:47:58 +00001143 expected_help = ("Options:\n"
Greg Wardeba20e62004-07-31 16:15:44 +00001144 " -t TEST, --test=TEST foo\n")
1145 self.assertHelp(parser, expected_help)
1146
1147
1148class TestCallbackExtraArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001149 def setUp(self):
1150 options = [make_option("-p", "--point", action="callback",
1151 callback=self.process_tuple,
1152 callback_args=(3, int), type="string",
1153 dest="points", default=[])]
1154 self.parser = OptionParser(option_list=options)
1155
Greg Wardab05edc2006-04-23 03:47:58 +00001156 def process_tuple(self, option, opt, value, parser_, len, type):
Greg Ward55493222003-04-21 02:41:25 +00001157 self.assertEqual(len, 3)
1158 self.assert_(type is int)
1159
1160 if opt == "-p":
1161 self.assertEqual(value, "1,2,3")
1162 elif opt == "--point":
1163 self.assertEqual(value, "4,5,6")
1164
1165 value = tuple(map(type, value.split(",")))
1166 getattr(parser_.values, option.dest).append(value)
1167
1168 def test_callback_extra_args(self):
1169 self.assertParseOK(["-p1,2,3", "--point", "4,5,6"],
1170 {'points': [(1,2,3), (4,5,6)]},
1171 [])
1172
Greg Wardeba20e62004-07-31 16:15:44 +00001173class TestCallbackMeddleArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001174 def setUp(self):
1175 options = [make_option(str(x), action="callback",
1176 callback=self.process_n, dest='things')
1177 for x in range(-1, -6, -1)]
1178 self.parser = OptionParser(option_list=options)
1179
1180 # Callback that meddles in rargs, largs
Greg Wardab05edc2006-04-23 03:47:58 +00001181 def process_n(self, option, opt, value, parser_):
Greg Ward55493222003-04-21 02:41:25 +00001182 # option is -3, -5, etc.
1183 nargs = int(opt[1:])
1184 rargs = parser_.rargs
1185 if len(rargs) < nargs:
1186 self.fail("Expected %d arguments for %s option." % (nargs, opt))
1187 dest = parser_.values.ensure_value(option.dest, [])
1188 dest.append(tuple(rargs[0:nargs]))
1189 parser_.largs.append(nargs)
1190 del rargs[0:nargs]
1191
1192 def test_callback_meddle_args(self):
1193 self.assertParseOK(["-1", "foo", "-3", "bar", "baz", "qux"],
1194 {'things': [("foo",), ("bar", "baz", "qux")]},
1195 [1, 3])
1196
1197 def test_callback_meddle_args_separator(self):
1198 self.assertParseOK(["-2", "foo", "--"],
1199 {'things': [('foo', '--')]},
1200 [2])
1201
Greg Wardeba20e62004-07-31 16:15:44 +00001202class TestCallbackManyArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001203 def setUp(self):
1204 options = [make_option("-a", "--apple", action="callback", nargs=2,
1205 callback=self.process_many, type="string"),
1206 make_option("-b", "--bob", action="callback", nargs=3,
1207 callback=self.process_many, type="int")]
1208 self.parser = OptionParser(option_list=options)
1209
Greg Wardab05edc2006-04-23 03:47:58 +00001210 def process_many(self, option, opt, value, parser_):
Greg Ward55493222003-04-21 02:41:25 +00001211 if opt == "-a":
1212 self.assertEqual(value, ("foo", "bar"))
1213 elif opt == "--apple":
1214 self.assertEqual(value, ("ding", "dong"))
1215 elif opt == "-b":
1216 self.assertEqual(value, (1, 2, 3))
1217 elif opt == "--bob":
1218 self.assertEqual(value, (-666, 42, 0))
1219
1220 def test_many_args(self):
1221 self.assertParseOK(["-a", "foo", "bar", "--apple", "ding", "dong",
1222 "-b", "1", "2", "3", "--bob", "-666", "42",
1223 "0"],
Greg Wardeba20e62004-07-31 16:15:44 +00001224 {"apple": None, "bob": None},
Greg Ward55493222003-04-21 02:41:25 +00001225 [])
1226
Greg Wardeba20e62004-07-31 16:15:44 +00001227class TestCallbackCheckAbbrev(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001228 def setUp(self):
1229 self.parser = OptionParser()
1230 self.parser.add_option("--foo-bar", action="callback",
1231 callback=self.check_abbrev)
1232
Greg Wardab05edc2006-04-23 03:47:58 +00001233 def check_abbrev(self, option, opt, value, parser):
Greg Ward55493222003-04-21 02:41:25 +00001234 self.assertEqual(opt, "--foo-bar")
1235
1236 def test_abbrev_callback_expansion(self):
1237 self.assertParseOK(["--foo"], {}, [])
1238
Greg Wardeba20e62004-07-31 16:15:44 +00001239class TestCallbackVarArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001240 def setUp(self):
1241 options = [make_option("-a", type="int", nargs=2, dest="a"),
1242 make_option("-b", action="store_true", dest="b"),
1243 make_option("-c", "--callback", action="callback",
1244 callback=self.variable_args, dest="c")]
Greg Ward48aa84b2004-10-27 02:20:04 +00001245 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
1246 option_list=options)
Greg Ward55493222003-04-21 02:41:25 +00001247
Greg Wardab05edc2006-04-23 03:47:58 +00001248 def variable_args(self, option, opt, value, parser):
Greg Ward55493222003-04-21 02:41:25 +00001249 self.assert_(value is None)
1250 done = 0
1251 value = []
1252 rargs = parser.rargs
1253 while rargs:
1254 arg = rargs[0]
1255 if ((arg[:2] == "--" and len(arg) > 2) or
1256 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1257 break
1258 else:
1259 value.append(arg)
1260 del rargs[0]
1261 setattr(parser.values, option.dest, value)
1262
1263 def test_variable_args(self):
1264 self.assertParseOK(["-a3", "-5", "--callback", "foo", "bar"],
1265 {'a': (3, -5), 'b': None, 'c': ["foo", "bar"]},
1266 [])
1267
1268 def test_consume_separator_stop_at_option(self):
1269 self.assertParseOK(["-c", "37", "--", "xxx", "-b", "hello"],
1270 {'a': None,
1271 'b': True,
1272 'c': ["37", "--", "xxx"]},
1273 ["hello"])
1274
1275 def test_positional_arg_and_variable_args(self):
1276 self.assertParseOK(["hello", "-c", "foo", "-", "bar"],
1277 {'a': None,
1278 'b': None,
1279 'c':["foo", "-", "bar"]},
1280 ["hello"])
1281
1282 def test_stop_at_option(self):
1283 self.assertParseOK(["-c", "foo", "-b"],
1284 {'a': None, 'b': True, 'c': ["foo"]},
1285 [])
1286
1287 def test_stop_at_invalid_option(self):
1288 self.assertParseFail(["-c", "3", "-5", "-a"], "no such option: -5")
1289
1290
1291# -- Test conflict handling and parser.parse_args() --------------------
1292
1293class ConflictBase(BaseTest):
1294 def setUp(self):
1295 options = [make_option("-v", "--verbose", action="count",
1296 dest="verbose", help="increment verbosity")]
Greg Ward48aa84b2004-10-27 02:20:04 +00001297 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
1298 option_list=options)
Greg Ward55493222003-04-21 02:41:25 +00001299
Greg Wardab05edc2006-04-23 03:47:58 +00001300 def show_version(self, option, opt, value, parser):
Greg Ward55493222003-04-21 02:41:25 +00001301 parser.values.show_version = 1
1302
1303class TestConflict(ConflictBase):
1304 """Use the default conflict resolution for Optik 1.2: error."""
1305 def assert_conflict_error(self, func):
Greg Wardeba20e62004-07-31 16:15:44 +00001306 err = self.assertRaises(
1307 func, ("-v", "--version"), {'action' : "callback",
1308 'callback' : self.show_version,
1309 'help' : "show version"},
1310 OptionConflictError,
1311 "option -v/--version: conflicting option string(s): -v")
Greg Ward55493222003-04-21 02:41:25 +00001312
1313 self.assertEqual(err.msg, "conflicting option string(s): -v")
1314 self.assertEqual(err.option_id, "-v/--version")
1315
1316 def test_conflict_error(self):
1317 self.assert_conflict_error(self.parser.add_option)
1318
1319 def test_conflict_error_group(self):
1320 group = OptionGroup(self.parser, "Group 1")
1321 self.assert_conflict_error(group.add_option)
1322
1323 def test_no_such_conflict_handler(self):
Greg Wardeba20e62004-07-31 16:15:44 +00001324 self.assertRaises(
1325 self.parser.set_conflict_handler, ('foo',), None,
1326 ValueError, "invalid conflict_resolution value 'foo'")
Greg Ward55493222003-04-21 02:41:25 +00001327
1328
Greg Ward55493222003-04-21 02:41:25 +00001329class TestConflictResolve(ConflictBase):
1330 def setUp(self):
1331 ConflictBase.setUp(self)
1332 self.parser.set_conflict_handler("resolve")
1333 self.parser.add_option("-v", "--version", action="callback",
1334 callback=self.show_version, help="show version")
1335
1336 def test_conflict_resolve(self):
1337 v_opt = self.parser.get_option("-v")
1338 verbose_opt = self.parser.get_option("--verbose")
1339 version_opt = self.parser.get_option("--version")
1340
1341 self.assert_(v_opt is version_opt)
1342 self.assert_(v_opt is not verbose_opt)
1343 self.assertEqual(v_opt._long_opts, ["--version"])
1344 self.assertEqual(version_opt._short_opts, ["-v"])
1345 self.assertEqual(version_opt._long_opts, ["--version"])
1346 self.assertEqual(verbose_opt._short_opts, [])
1347 self.assertEqual(verbose_opt._long_opts, ["--verbose"])
1348
1349 def test_conflict_resolve_help(self):
Greg Ward48aa84b2004-10-27 02:20:04 +00001350 self.assertOutput(["-h"], """\
Greg Wardab05edc2006-04-23 03:47:58 +00001351Options:
Greg Ward55493222003-04-21 02:41:25 +00001352 --verbose increment verbosity
1353 -h, --help show this help message and exit
1354 -v, --version show version
1355""")
1356
1357 def test_conflict_resolve_short_opt(self):
1358 self.assertParseOK(["-v"],
1359 {'verbose': None, 'show_version': 1},
1360 [])
1361
1362 def test_conflict_resolve_long_opt(self):
1363 self.assertParseOK(["--verbose"],
1364 {'verbose': 1},
1365 [])
1366
1367 def test_conflict_resolve_long_opts(self):
1368 self.assertParseOK(["--verbose", "--version"],
1369 {'verbose': 1, 'show_version': 1},
1370 [])
1371
1372class TestConflictOverride(BaseTest):
1373 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +00001374 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +00001375 self.parser.set_conflict_handler("resolve")
1376 self.parser.add_option("-n", "--dry-run",
1377 action="store_true", dest="dry_run",
1378 help="don't do anything")
1379 self.parser.add_option("--dry-run", "-n",
1380 action="store_const", const=42, dest="dry_run",
1381 help="dry run mode")
1382
1383 def test_conflict_override_opts(self):
1384 opt = self.parser.get_option("--dry-run")
1385 self.assertEqual(opt._short_opts, ["-n"])
1386 self.assertEqual(opt._long_opts, ["--dry-run"])
1387
1388 def test_conflict_override_help(self):
Greg Ward48aa84b2004-10-27 02:20:04 +00001389 self.assertOutput(["-h"], """\
Greg Wardab05edc2006-04-23 03:47:58 +00001390Options:
Greg Ward55493222003-04-21 02:41:25 +00001391 -h, --help show this help message and exit
1392 -n, --dry-run dry run mode
1393""")
1394
1395 def test_conflict_override_args(self):
1396 self.assertParseOK(["-n"],
1397 {'dry_run': 42},
1398 [])
1399
1400# -- Other testing. ----------------------------------------------------
1401
Greg Wardeba20e62004-07-31 16:15:44 +00001402_expected_help_basic = """\
Greg Wardab05edc2006-04-23 03:47:58 +00001403Usage: bar.py [options]
Greg Wardeba20e62004-07-31 16:15:44 +00001404
Greg Wardab05edc2006-04-23 03:47:58 +00001405Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001406 -a APPLE throw APPLEs at basket
1407 -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the
1408 evil spirits that cause trouble and mayhem)
1409 --foo=FOO store FOO in the foo list for later fooing
1410 -h, --help show this help message and exit
1411"""
1412
1413_expected_help_long_opts_first = """\
Greg Wardab05edc2006-04-23 03:47:58 +00001414Usage: bar.py [options]
Greg Wardeba20e62004-07-31 16:15:44 +00001415
Greg Wardab05edc2006-04-23 03:47:58 +00001416Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001417 -a APPLE throw APPLEs at basket
1418 --boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the
1419 evil spirits that cause trouble and mayhem)
1420 --foo=FOO store FOO in the foo list for later fooing
1421 --help, -h show this help message and exit
1422"""
1423
1424_expected_help_title_formatter = """\
1425Usage
1426=====
1427 bar.py [options]
1428
Greg Wardab05edc2006-04-23 03:47:58 +00001429Options
Greg Wardeba20e62004-07-31 16:15:44 +00001430=======
1431-a APPLE throw APPLEs at basket
1432--boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the
1433 evil spirits that cause trouble and mayhem)
1434--foo=FOO store FOO in the foo list for later fooing
1435--help, -h show this help message and exit
1436"""
1437
1438_expected_help_short_lines = """\
Greg Wardab05edc2006-04-23 03:47:58 +00001439Usage: bar.py [options]
Greg Wardeba20e62004-07-31 16:15:44 +00001440
Greg Wardab05edc2006-04-23 03:47:58 +00001441Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001442 -a APPLE throw APPLEs at basket
1443 -b NUM, --boo=NUM shout "boo!" NUM times (in order to
1444 frighten away all the evil spirits
1445 that cause trouble and mayhem)
1446 --foo=FOO store FOO in the foo list for later
1447 fooing
1448 -h, --help show this help message and exit
1449"""
1450
Greg Ward55493222003-04-21 02:41:25 +00001451class TestHelp(BaseTest):
1452 def setUp(self):
Greg Wardeba20e62004-07-31 16:15:44 +00001453 self.parser = self.make_parser(80)
1454
1455 def make_parser(self, columns):
Greg Ward55493222003-04-21 02:41:25 +00001456 options = [
1457 make_option("-a", type="string", dest='a',
1458 metavar="APPLE", help="throw APPLEs at basket"),
1459 make_option("-b", "--boo", type="int", dest='boo',
1460 metavar="NUM",
1461 help=
1462 "shout \"boo!\" NUM times (in order to frighten away "
1463 "all the evil spirits that cause trouble and mayhem)"),
1464 make_option("--foo", action="append", type="string", dest='foo',
1465 help="store FOO in the foo list for later fooing"),
1466 ]
Greg Ward48fae7a2006-07-23 16:05:51 +00001467
1468 # We need to set COLUMNS for the OptionParser constructor, but
1469 # we must restore its original value -- otherwise, this test
1470 # screws things up for other tests when it's part of the Python
1471 # test suite.
Walter Dörwald536120e2009-04-26 21:04:55 +00001472 with test_support.EnvironmentVarGuard() as env:
1473 env.set('COLUMNS', str(columns))
Tim Peterse7d7caa2006-06-19 09:09:44 +00001474 return InterceptingOptionParser(option_list=options)
Greg Ward55493222003-04-21 02:41:25 +00001475
1476 def assertHelpEquals(self, expected_output):
Greg Ward0e0c9f42006-06-11 16:24:11 +00001477 if type(expected_output) is types.UnicodeType:
1478 encoding = self.parser._get_encoding(sys.stdout)
1479 expected_output = expected_output.encode(encoding, "replace")
1480
Greg Ward48aa84b2004-10-27 02:20:04 +00001481 save_argv = sys.argv[:]
1482 try:
1483 # Make optparse believe bar.py is being executed.
1484 sys.argv[0] = os.path.join("foo", "bar.py")
1485 self.assertOutput(["-h"], expected_output)
1486 finally:
1487 sys.argv[:] = save_argv
Greg Ward55493222003-04-21 02:41:25 +00001488
1489 def test_help(self):
Greg Wardeba20e62004-07-31 16:15:44 +00001490 self.assertHelpEquals(_expected_help_basic)
Greg Ward55493222003-04-21 02:41:25 +00001491
1492 def test_help_old_usage(self):
Greg Wardab05edc2006-04-23 03:47:58 +00001493 self.parser.set_usage("Usage: %prog [options]")
Greg Wardeba20e62004-07-31 16:15:44 +00001494 self.assertHelpEquals(_expected_help_basic)
Greg Ward55493222003-04-21 02:41:25 +00001495
1496 def test_help_long_opts_first(self):
1497 self.parser.formatter.short_first = 0
Greg Wardeba20e62004-07-31 16:15:44 +00001498 self.assertHelpEquals(_expected_help_long_opts_first)
Greg Ward55493222003-04-21 02:41:25 +00001499
1500 def test_help_title_formatter(self):
Walter Dörwald536120e2009-04-26 21:04:55 +00001501 with test_support.EnvironmentVarGuard() as env:
1502 env.set("COLUMNS", "80")
Guido van Rossum0567ba22007-01-14 03:46:33 +00001503 self.parser.formatter = TitledHelpFormatter()
1504 self.assertHelpEquals(_expected_help_title_formatter)
Greg Ward55493222003-04-21 02:41:25 +00001505
Greg Wardeba20e62004-07-31 16:15:44 +00001506 def test_wrap_columns(self):
1507 # Ensure that wrapping respects $COLUMNS environment variable.
1508 # Need to reconstruct the parser, since that's the only time
1509 # we look at $COLUMNS.
1510 self.parser = self.make_parser(60)
1511 self.assertHelpEquals(_expected_help_short_lines)
Greg Ward55493222003-04-21 02:41:25 +00001512
Greg Ward0e0c9f42006-06-11 16:24:11 +00001513 def test_help_unicode(self):
1514 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
1515 self.parser.add_option("-a", action="store_true", help=u"ol\u00E9!")
1516 expect = u"""\
1517Options:
1518 -h, --help show this help message and exit
1519 -a ol\u00E9!
1520"""
1521 self.assertHelpEquals(expect)
1522
1523 def test_help_unicode_description(self):
1524 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
1525 description=u"ol\u00E9!")
1526 expect = u"""\
1527ol\u00E9!
1528
1529Options:
1530 -h, --help show this help message and exit
1531"""
1532 self.assertHelpEquals(expect)
1533
Greg Ward55493222003-04-21 02:41:25 +00001534 def test_help_description_groups(self):
1535 self.parser.set_description(
Greg Wardeba20e62004-07-31 16:15:44 +00001536 "This is the program description for %prog. %prog has "
Greg Ward55493222003-04-21 02:41:25 +00001537 "an option group as well as single options.")
1538
1539 group = OptionGroup(
1540 self.parser, "Dangerous Options",
1541 "Caution: use of these options is at your own risk. "
1542 "It is believed that some of them bite.")
1543 group.add_option("-g", action="store_true", help="Group option.")
1544 self.parser.add_option_group(group)
1545
Greg Wardab05edc2006-04-23 03:47:58 +00001546 expect = """\
1547Usage: bar.py [options]
Greg Ward55493222003-04-21 02:41:25 +00001548
Greg Wardeba20e62004-07-31 16:15:44 +00001549This is the program description for bar.py. bar.py has an option group as
1550well as single options.
1551
Greg Wardab05edc2006-04-23 03:47:58 +00001552Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001553 -a APPLE throw APPLEs at basket
1554 -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the
1555 evil spirits that cause trouble and mayhem)
1556 --foo=FOO store FOO in the foo list for later fooing
1557 -h, --help show this help message and exit
Greg Ward55493222003-04-21 02:41:25 +00001558
1559 Dangerous Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001560 Caution: use of these options is at your own risk. It is believed
1561 that some of them bite.
1562
1563 -g Group option.
Greg Wardab05edc2006-04-23 03:47:58 +00001564"""
Greg Ward55493222003-04-21 02:41:25 +00001565
Greg Wardab05edc2006-04-23 03:47:58 +00001566 self.assertHelpEquals(expect)
Greg Wardeba20e62004-07-31 16:15:44 +00001567
Greg Wardab05edc2006-04-23 03:47:58 +00001568 self.parser.epilog = "Please report bugs to /dev/null."
1569 self.assertHelpEquals(expect + "\nPlease report bugs to /dev/null.\n")
Tim Peters10d59f32004-10-27 02:43:25 +00001570
Greg Wardeba20e62004-07-31 16:15:44 +00001571
Greg Ward55493222003-04-21 02:41:25 +00001572class TestMatchAbbrev(BaseTest):
1573 def test_match_abbrev(self):
1574 self.assertEqual(_match_abbrev("--f",
1575 {"--foz": None,
1576 "--foo": None,
1577 "--fie": None,
1578 "--f": None}),
1579 "--f")
1580
1581 def test_match_abbrev_error(self):
1582 s = "--f"
1583 wordmap = {"--foz": None, "--foo": None, "--fie": None}
Greg Wardeba20e62004-07-31 16:15:44 +00001584 self.assertRaises(
1585 _match_abbrev, (s, wordmap), None,
Armin Rigoa3f09272006-05-28 19:13:17 +00001586 BadOptionError, "ambiguous option: --f (--fie, --foo, --foz?)")
Greg Wardeba20e62004-07-31 16:15:44 +00001587
1588
Greg Wardab05edc2006-04-23 03:47:58 +00001589class TestParseNumber(BaseTest):
1590 def setUp(self):
1591 self.parser = InterceptingOptionParser()
1592 self.parser.add_option("-n", type=int)
1593 self.parser.add_option("-l", type=long)
1594
1595 def test_parse_num_fail(self):
1596 self.assertRaises(
1597 _parse_num, ("", int), {},
1598 ValueError,
1599 re.compile(r"invalid literal for int().*: '?'?"))
1600 self.assertRaises(
1601 _parse_num, ("0xOoops", long), {},
1602 ValueError,
1603 re.compile(r"invalid literal for long().*: '?0xOoops'?"))
1604
1605 def test_parse_num_ok(self):
1606 self.assertEqual(_parse_num("0", int), 0)
1607 self.assertEqual(_parse_num("0x10", int), 16)
1608 self.assertEqual(_parse_num("0XA", long), 10L)
1609 self.assertEqual(_parse_num("010", long), 8L)
1610 self.assertEqual(_parse_num("0b11", int), 3)
1611 self.assertEqual(_parse_num("0b", long), 0L)
1612
1613 def test_numeric_options(self):
1614 self.assertParseOK(["-n", "42", "-l", "0x20"],
1615 { "n": 42, "l": 0x20 }, [])
1616 self.assertParseOK(["-n", "0b0101", "-l010"],
1617 { "n": 5, "l": 8 }, [])
1618 self.assertParseFail(["-n008"],
1619 "option -n: invalid integer value: '008'")
1620 self.assertParseFail(["-l0b0123"],
1621 "option -l: invalid long integer value: '0b0123'")
1622 self.assertParseFail(["-l", "0x12x"],
1623 "option -l: invalid long integer value: '0x12x'")
1624
1625
Greg Ward55493222003-04-21 02:41:25 +00001626def test_main():
Collin Winterc2898c52007-04-25 17:29:52 +00001627 test_support.run_unittest(__name__)
Greg Ward55493222003-04-21 02:41:25 +00001628
1629if __name__ == '__main__':
Collin Winterc2898c52007-04-25 17:29:52 +00001630 test_main()