blob: 183a9df1157dfb70a661b781c5969f273c22d756 [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
R. David Murray80972692010-06-26 00:17:12 +0000757 def test_combined_single_invalid_option(self):
758 self.parser.add_option("-t", action="store_true")
759 self.assertParseFail(["-test"],
R. David Murray76af4022010-06-26 03:34:33 +0000760 "no such option: -e")
R. David Murray80972692010-06-26 00:17:12 +0000761
Greg Ward55493222003-04-21 02:41:25 +0000762class TestBool(BaseTest):
763 def setUp(self):
764 options = [make_option("-v",
765 "--verbose",
766 action="store_true",
767 dest="verbose",
768 default=''),
769 make_option("-q",
770 "--quiet",
771 action="store_false",
772 dest="verbose")]
773 self.parser = OptionParser(option_list = options)
774
775 def test_bool_default(self):
776 self.assertParseOK([],
777 {'verbose': ''},
778 [])
779
780 def test_bool_false(self):
781 (options, args) = self.assertParseOK(["-q"],
782 {'verbose': 0},
783 [])
784 if hasattr(__builtins__, 'False'):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000785 self.assertTrue(options.verbose is False)
Greg Ward55493222003-04-21 02:41:25 +0000786
787 def test_bool_true(self):
788 (options, args) = self.assertParseOK(["-v"],
789 {'verbose': 1},
790 [])
791 if hasattr(__builtins__, 'True'):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000792 self.assertTrue(options.verbose is True)
Greg Ward55493222003-04-21 02:41:25 +0000793
794 def test_bool_flicker_on_and_off(self):
795 self.assertParseOK(["-qvq", "-q", "-v"],
796 {'verbose': 1},
797 [])
798
799class TestChoice(BaseTest):
800 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000801 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000802 self.parser.add_option("-c", action="store", type="choice",
803 dest="choice", choices=["one", "two", "three"])
804
805 def test_valid_choice(self):
806 self.assertParseOK(["-c", "one", "xyz"],
807 {'choice': 'one'},
808 ["xyz"])
809
810 def test_invalid_choice(self):
811 self.assertParseFail(["-c", "four", "abc"],
812 "option -c: invalid choice: 'four' "
813 "(choose from 'one', 'two', 'three')")
814
815 def test_add_choice_option(self):
816 self.parser.add_option("-d", "--default",
817 choices=["four", "five", "six"])
818 opt = self.parser.get_option("-d")
819 self.assertEqual(opt.type, "choice")
820 self.assertEqual(opt.action, "store")
821
822class TestCount(BaseTest):
823 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000824 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000825 self.v_opt = make_option("-v", action="count", dest="verbose")
826 self.parser.add_option(self.v_opt)
827 self.parser.add_option("--verbose", type="int", dest="verbose")
828 self.parser.add_option("-q", "--quiet",
829 action="store_const", dest="verbose", const=0)
830
831 def test_empty(self):
832 self.assertParseOK([], {'verbose': None}, [])
833
834 def test_count_one(self):
835 self.assertParseOK(["-v"], {'verbose': 1}, [])
836
837 def test_count_three(self):
838 self.assertParseOK(["-vvv"], {'verbose': 3}, [])
839
840 def test_count_three_apart(self):
841 self.assertParseOK(["-v", "-v", "-v"], {'verbose': 3}, [])
842
843 def test_count_override_amount(self):
844 self.assertParseOK(["-vvv", "--verbose=2"], {'verbose': 2}, [])
845
846 def test_count_override_quiet(self):
847 self.assertParseOK(["-vvv", "--verbose=2", "-q"], {'verbose': 0}, [])
848
849 def test_count_overriding(self):
850 self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"],
851 {'verbose': 1}, [])
852
853 def test_count_interspersed_args(self):
854 self.assertParseOK(["--quiet", "3", "-v"],
855 {'verbose': 1},
856 ["3"])
857
858 def test_count_no_interspersed_args(self):
859 self.parser.disable_interspersed_args()
860 self.assertParseOK(["--quiet", "3", "-v"],
861 {'verbose': 0},
862 ["3", "-v"])
863
864 def test_count_no_such_option(self):
865 self.assertParseFail(["-q3", "-v"], "no such option: -3")
866
867 def test_count_option_no_value(self):
868 self.assertParseFail(["--quiet=3", "-v"],
869 "--quiet option does not take a value")
870
871 def test_count_with_default(self):
872 self.parser.set_default('verbose', 0)
873 self.assertParseOK([], {'verbose':0}, [])
874
875 def test_count_overriding_default(self):
876 self.parser.set_default('verbose', 0)
877 self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"],
878 {'verbose': 1}, [])
879
Greg Ward48aa84b2004-10-27 02:20:04 +0000880class TestMultipleArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +0000881 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000882 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000883 self.parser.add_option("-p", "--point",
884 action="store", nargs=3, type="float", dest="point")
885
886 def test_nargs_with_positional_args(self):
887 self.assertParseOK(["foo", "-p", "1", "2.5", "-4.3", "xyz"],
888 {'point': (1.0, 2.5, -4.3)},
889 ["foo", "xyz"])
890
891 def test_nargs_long_opt(self):
892 self.assertParseOK(["--point", "-1", "2.5", "-0", "xyz"],
893 {'point': (-1.0, 2.5, -0.0)},
894 ["xyz"])
895
896 def test_nargs_invalid_float_value(self):
897 self.assertParseFail(["-p", "1.0", "2x", "3.5"],
898 "option -p: "
899 "invalid floating-point value: '2x'")
900
901 def test_nargs_required_values(self):
902 self.assertParseFail(["--point", "1.0", "3.5"],
Greg Wardeba20e62004-07-31 16:15:44 +0000903 "--point option requires 3 arguments")
Greg Ward55493222003-04-21 02:41:25 +0000904
Greg Ward48aa84b2004-10-27 02:20:04 +0000905class TestMultipleArgsAppend(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +0000906 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000907 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000908 self.parser.add_option("-p", "--point", action="store", nargs=3,
909 type="float", dest="point")
910 self.parser.add_option("-f", "--foo", action="append", nargs=2,
911 type="int", dest="foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000912 self.parser.add_option("-z", "--zero", action="append_const",
913 dest="foo", const=(0, 0))
Greg Ward55493222003-04-21 02:41:25 +0000914
915 def test_nargs_append(self):
916 self.assertParseOK(["-f", "4", "-3", "blah", "--foo", "1", "666"],
917 {'point': None, 'foo': [(4, -3), (1, 666)]},
918 ["blah"])
919
920 def test_nargs_append_required_values(self):
921 self.assertParseFail(["-f4,3"],
Greg Wardeba20e62004-07-31 16:15:44 +0000922 "-f option requires 2 arguments")
Greg Ward55493222003-04-21 02:41:25 +0000923
924 def test_nargs_append_simple(self):
925 self.assertParseOK(["--foo=3", "4"],
926 {'point': None, 'foo':[(3, 4)]},
927 [])
928
Thomas Wouters477c8d52006-05-27 19:21:47 +0000929 def test_nargs_append_const(self):
930 self.assertParseOK(["--zero", "--foo", "3", "4", "-z"],
931 {'point': None, 'foo':[(0, 0), (3, 4), (0, 0)]},
932 [])
933
Greg Ward55493222003-04-21 02:41:25 +0000934class TestVersion(BaseTest):
935 def test_version(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000936 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
937 version="%prog 0.1")
938 save_argv = sys.argv[:]
939 try:
940 sys.argv[0] = os.path.join(os.curdir, "foo", "bar")
941 self.assertOutput(["--version"], "bar 0.1\n")
942 finally:
943 sys.argv[:] = save_argv
Greg Ward55493222003-04-21 02:41:25 +0000944
945 def test_no_version(self):
Greg Ward48aa84b2004-10-27 02:20:04 +0000946 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +0000947 self.assertParseFail(["--version"],
948 "no such option: --version")
949
950# -- Test conflicting default values and parser.parse_args() -----------
951
952class TestConflictingDefaults(BaseTest):
953 """Conflicting default values: the last one should win."""
954 def setUp(self):
955 self.parser = OptionParser(option_list=[
956 make_option("-v", action="store_true", dest="verbose", default=1)])
957
958 def test_conflict_default(self):
959 self.parser.add_option("-q", action="store_false", dest="verbose",
960 default=0)
961 self.assertParseOK([], {'verbose': 0}, [])
962
963 def test_conflict_default_none(self):
964 self.parser.add_option("-q", action="store_false", dest="verbose",
965 default=None)
966 self.assertParseOK([], {'verbose': None}, [])
967
968class TestOptionGroup(BaseTest):
969 def setUp(self):
970 self.parser = OptionParser(usage=SUPPRESS_USAGE)
971
972 def test_option_group_create_instance(self):
973 group = OptionGroup(self.parser, "Spam")
974 self.parser.add_option_group(group)
975 group.add_option("--spam", action="store_true",
976 help="spam spam spam spam")
977 self.assertParseOK(["--spam"], {'spam': 1}, [])
978
979 def test_add_group_no_group(self):
980 self.assertTypeError(self.parser.add_option_group,
981 "not an OptionGroup instance: None", None)
982
983 def test_add_group_invalid_arguments(self):
984 self.assertTypeError(self.parser.add_option_group,
985 "invalid arguments", None, None)
986
987 def test_add_group_wrong_parser(self):
988 group = OptionGroup(self.parser, "Spam")
989 group.parser = OptionParser()
Greg Wardeba20e62004-07-31 16:15:44 +0000990 self.assertRaises(self.parser.add_option_group, (group,), None,
991 ValueError, "invalid OptionGroup (wrong parser)")
Greg Ward55493222003-04-21 02:41:25 +0000992
993 def test_group_manipulate(self):
994 group = self.parser.add_option_group("Group 2",
995 description="Some more options")
996 group.set_title("Bacon")
997 group.add_option("--bacon", type="int")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000998 self.assertTrue(self.parser.get_option_group("--bacon"), group)
Greg Ward55493222003-04-21 02:41:25 +0000999
1000# -- Test extending and parser.parse_args() ----------------------------
1001
1002class TestExtendAddTypes(BaseTest):
1003 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +00001004 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
1005 option_class=self.MyOption)
Greg Ward55493222003-04-21 02:41:25 +00001006 self.parser.add_option("-a", None, type="string", dest="a")
1007 self.parser.add_option("-f", "--file", type="file", dest="file")
1008
Thomas Wouters477c8d52006-05-27 19:21:47 +00001009 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001010 if os.path.isdir(support.TESTFN):
1011 os.rmdir(support.TESTFN)
1012 elif os.path.isfile(support.TESTFN):
1013 os.unlink(support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001014
Greg Ward55493222003-04-21 02:41:25 +00001015 class MyOption (Option):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001016 def check_file(option, opt, value):
Greg Ward55493222003-04-21 02:41:25 +00001017 if not os.path.exists(value):
1018 raise OptionValueError("%s: file does not exist" % value)
1019 elif not os.path.isfile(value):
1020 raise OptionValueError("%s: not a regular file" % value)
1021 return value
1022
1023 TYPES = Option.TYPES + ("file",)
1024 TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
1025 TYPE_CHECKER["file"] = check_file
1026
Thomas Wouters477c8d52006-05-27 19:21:47 +00001027 def test_filetype_ok(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001028 open(support.TESTFN, "w").close()
1029 self.assertParseOK(["--file", support.TESTFN, "-afoo"],
1030 {'file': support.TESTFN, 'a': 'foo'},
Greg Ward55493222003-04-21 02:41:25 +00001031 [])
1032
Thomas Wouters477c8d52006-05-27 19:21:47 +00001033 def test_filetype_noexist(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001034 self.assertParseFail(["--file", support.TESTFN, "-afoo"],
Greg Ward55493222003-04-21 02:41:25 +00001035 "%s: file does not exist" %
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001036 support.TESTFN)
Greg Ward55493222003-04-21 02:41:25 +00001037
Thomas Wouters477c8d52006-05-27 19:21:47 +00001038 def test_filetype_notfile(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001039 os.mkdir(support.TESTFN)
1040 self.assertParseFail(["--file", support.TESTFN, "-afoo"],
Greg Ward55493222003-04-21 02:41:25 +00001041 "%s: not a regular file" %
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001042 support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001043
Greg Ward55493222003-04-21 02:41:25 +00001044
1045class TestExtendAddActions(BaseTest):
1046 def setUp(self):
1047 options = [self.MyOption("-a", "--apple", action="extend",
1048 type="string", dest="apple")]
1049 self.parser = OptionParser(option_list=options)
1050
1051 class MyOption (Option):
1052 ACTIONS = Option.ACTIONS + ("extend",)
1053 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1054 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1055
Thomas Wouters477c8d52006-05-27 19:21:47 +00001056 def take_action(self, action, dest, opt, value, values, parser):
Greg Ward55493222003-04-21 02:41:25 +00001057 if action == "extend":
1058 lvalue = value.split(",")
1059 values.ensure_value(dest, []).extend(lvalue)
1060 else:
1061 Option.take_action(self, action, dest, opt, parser, value,
1062 values)
1063
1064 def test_extend_add_action(self):
1065 self.assertParseOK(["-afoo,bar", "--apple=blah"],
1066 {'apple': ["foo", "bar", "blah"]},
1067 [])
1068
1069 def test_extend_add_action_normal(self):
1070 self.assertParseOK(["-a", "foo", "-abar", "--apple=x,y"],
1071 {'apple': ["foo", "bar", "x", "y"]},
1072 [])
1073
1074# -- Test callbacks and parser.parse_args() ----------------------------
1075
1076class TestCallback(BaseTest):
1077 def setUp(self):
1078 options = [make_option("-x",
1079 None,
1080 action="callback",
1081 callback=self.process_opt),
1082 make_option("-f",
1083 "--file",
1084 action="callback",
1085 callback=self.process_opt,
1086 type="string",
1087 dest="filename")]
1088 self.parser = OptionParser(option_list=options)
1089
1090 def process_opt(self, option, opt, value, parser_):
1091 if opt == "-x":
1092 self.assertEqual(option._short_opts, ["-x"])
1093 self.assertEqual(option._long_opts, [])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001094 self.assertTrue(parser_ is self.parser)
1095 self.assertTrue(value is None)
Greg Ward55493222003-04-21 02:41:25 +00001096 self.assertEqual(vars(parser_.values), {'filename': None})
1097
1098 parser_.values.x = 42
1099 elif opt == "--file":
1100 self.assertEqual(option._short_opts, ["-f"])
1101 self.assertEqual(option._long_opts, ["--file"])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001102 self.assertTrue(parser_ is self.parser)
Greg Ward55493222003-04-21 02:41:25 +00001103 self.assertEqual(value, "foo")
1104 self.assertEqual(vars(parser_.values), {'filename': None, 'x': 42})
1105
1106 setattr(parser_.values, option.dest, value)
1107 else:
1108 self.fail("Unknown option %r in process_opt." % opt)
1109
1110 def test_callback(self):
1111 self.assertParseOK(["-x", "--file=foo"],
1112 {'filename': "foo", 'x': 42},
1113 [])
1114
Greg Wardeba20e62004-07-31 16:15:44 +00001115 def test_callback_help(self):
1116 # This test was prompted by SF bug #960515 -- the point is
1117 # not to inspect the help text, just to make sure that
1118 # format_help() doesn't crash.
1119 parser = OptionParser(usage=SUPPRESS_USAGE)
1120 parser.remove_option("-h")
1121 parser.add_option("-t", "--test", action="callback",
1122 callback=lambda: None, type="string",
1123 help="foo")
1124
Thomas Wouters477c8d52006-05-27 19:21:47 +00001125 expected_help = ("Options:\n"
Greg Wardeba20e62004-07-31 16:15:44 +00001126 " -t TEST, --test=TEST foo\n")
1127 self.assertHelp(parser, expected_help)
1128
1129
1130class TestCallbackExtraArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001131 def setUp(self):
1132 options = [make_option("-p", "--point", action="callback",
1133 callback=self.process_tuple,
1134 callback_args=(3, int), type="string",
1135 dest="points", default=[])]
1136 self.parser = OptionParser(option_list=options)
1137
Thomas Wouters477c8d52006-05-27 19:21:47 +00001138 def process_tuple(self, option, opt, value, parser_, len, type):
Greg Ward55493222003-04-21 02:41:25 +00001139 self.assertEqual(len, 3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001140 self.assertTrue(type is int)
Greg Ward55493222003-04-21 02:41:25 +00001141
1142 if opt == "-p":
1143 self.assertEqual(value, "1,2,3")
1144 elif opt == "--point":
1145 self.assertEqual(value, "4,5,6")
1146
1147 value = tuple(map(type, value.split(",")))
1148 getattr(parser_.values, option.dest).append(value)
1149
1150 def test_callback_extra_args(self):
1151 self.assertParseOK(["-p1,2,3", "--point", "4,5,6"],
1152 {'points': [(1,2,3), (4,5,6)]},
1153 [])
1154
Greg Wardeba20e62004-07-31 16:15:44 +00001155class TestCallbackMeddleArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001156 def setUp(self):
1157 options = [make_option(str(x), action="callback",
1158 callback=self.process_n, dest='things')
1159 for x in range(-1, -6, -1)]
1160 self.parser = OptionParser(option_list=options)
1161
1162 # Callback that meddles in rargs, largs
Thomas Wouters477c8d52006-05-27 19:21:47 +00001163 def process_n(self, option, opt, value, parser_):
Greg Ward55493222003-04-21 02:41:25 +00001164 # option is -3, -5, etc.
1165 nargs = int(opt[1:])
1166 rargs = parser_.rargs
1167 if len(rargs) < nargs:
1168 self.fail("Expected %d arguments for %s option." % (nargs, opt))
1169 dest = parser_.values.ensure_value(option.dest, [])
1170 dest.append(tuple(rargs[0:nargs]))
1171 parser_.largs.append(nargs)
1172 del rargs[0:nargs]
1173
1174 def test_callback_meddle_args(self):
1175 self.assertParseOK(["-1", "foo", "-3", "bar", "baz", "qux"],
1176 {'things': [("foo",), ("bar", "baz", "qux")]},
1177 [1, 3])
1178
1179 def test_callback_meddle_args_separator(self):
1180 self.assertParseOK(["-2", "foo", "--"],
1181 {'things': [('foo', '--')]},
1182 [2])
1183
Greg Wardeba20e62004-07-31 16:15:44 +00001184class TestCallbackManyArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001185 def setUp(self):
1186 options = [make_option("-a", "--apple", action="callback", nargs=2,
1187 callback=self.process_many, type="string"),
1188 make_option("-b", "--bob", action="callback", nargs=3,
1189 callback=self.process_many, type="int")]
1190 self.parser = OptionParser(option_list=options)
1191
Thomas Wouters477c8d52006-05-27 19:21:47 +00001192 def process_many(self, option, opt, value, parser_):
Greg Ward55493222003-04-21 02:41:25 +00001193 if opt == "-a":
1194 self.assertEqual(value, ("foo", "bar"))
1195 elif opt == "--apple":
1196 self.assertEqual(value, ("ding", "dong"))
1197 elif opt == "-b":
1198 self.assertEqual(value, (1, 2, 3))
1199 elif opt == "--bob":
1200 self.assertEqual(value, (-666, 42, 0))
1201
1202 def test_many_args(self):
1203 self.assertParseOK(["-a", "foo", "bar", "--apple", "ding", "dong",
1204 "-b", "1", "2", "3", "--bob", "-666", "42",
1205 "0"],
Greg Wardeba20e62004-07-31 16:15:44 +00001206 {"apple": None, "bob": None},
Greg Ward55493222003-04-21 02:41:25 +00001207 [])
1208
Greg Wardeba20e62004-07-31 16:15:44 +00001209class TestCallbackCheckAbbrev(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001210 def setUp(self):
1211 self.parser = OptionParser()
1212 self.parser.add_option("--foo-bar", action="callback",
1213 callback=self.check_abbrev)
1214
Thomas Wouters477c8d52006-05-27 19:21:47 +00001215 def check_abbrev(self, option, opt, value, parser):
Greg Ward55493222003-04-21 02:41:25 +00001216 self.assertEqual(opt, "--foo-bar")
1217
1218 def test_abbrev_callback_expansion(self):
1219 self.assertParseOK(["--foo"], {}, [])
1220
Greg Wardeba20e62004-07-31 16:15:44 +00001221class TestCallbackVarArgs(BaseTest):
Greg Ward55493222003-04-21 02:41:25 +00001222 def setUp(self):
1223 options = [make_option("-a", type="int", nargs=2, dest="a"),
1224 make_option("-b", action="store_true", dest="b"),
1225 make_option("-c", "--callback", action="callback",
1226 callback=self.variable_args, dest="c")]
Greg Ward48aa84b2004-10-27 02:20:04 +00001227 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
1228 option_list=options)
Greg Ward55493222003-04-21 02:41:25 +00001229
Thomas Wouters477c8d52006-05-27 19:21:47 +00001230 def variable_args(self, option, opt, value, parser):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001231 self.assertTrue(value is None)
Greg Ward55493222003-04-21 02:41:25 +00001232 value = []
1233 rargs = parser.rargs
1234 while rargs:
1235 arg = rargs[0]
1236 if ((arg[:2] == "--" and len(arg) > 2) or
1237 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1238 break
1239 else:
1240 value.append(arg)
1241 del rargs[0]
1242 setattr(parser.values, option.dest, value)
1243
1244 def test_variable_args(self):
1245 self.assertParseOK(["-a3", "-5", "--callback", "foo", "bar"],
1246 {'a': (3, -5), 'b': None, 'c': ["foo", "bar"]},
1247 [])
1248
1249 def test_consume_separator_stop_at_option(self):
1250 self.assertParseOK(["-c", "37", "--", "xxx", "-b", "hello"],
1251 {'a': None,
1252 'b': True,
1253 'c': ["37", "--", "xxx"]},
1254 ["hello"])
1255
1256 def test_positional_arg_and_variable_args(self):
1257 self.assertParseOK(["hello", "-c", "foo", "-", "bar"],
1258 {'a': None,
1259 'b': None,
1260 'c':["foo", "-", "bar"]},
1261 ["hello"])
1262
1263 def test_stop_at_option(self):
1264 self.assertParseOK(["-c", "foo", "-b"],
1265 {'a': None, 'b': True, 'c': ["foo"]},
1266 [])
1267
1268 def test_stop_at_invalid_option(self):
1269 self.assertParseFail(["-c", "3", "-5", "-a"], "no such option: -5")
1270
1271
1272# -- Test conflict handling and parser.parse_args() --------------------
1273
1274class ConflictBase(BaseTest):
1275 def setUp(self):
1276 options = [make_option("-v", "--verbose", action="count",
1277 dest="verbose", help="increment verbosity")]
Greg Ward48aa84b2004-10-27 02:20:04 +00001278 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
1279 option_list=options)
Greg Ward55493222003-04-21 02:41:25 +00001280
Thomas Wouters477c8d52006-05-27 19:21:47 +00001281 def show_version(self, option, opt, value, parser):
Greg Ward55493222003-04-21 02:41:25 +00001282 parser.values.show_version = 1
1283
1284class TestConflict(ConflictBase):
1285 """Use the default conflict resolution for Optik 1.2: error."""
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001286 def assertTrueconflict_error(self, func):
Greg Wardeba20e62004-07-31 16:15:44 +00001287 err = self.assertRaises(
1288 func, ("-v", "--version"), {'action' : "callback",
1289 'callback' : self.show_version,
1290 'help' : "show version"},
1291 OptionConflictError,
1292 "option -v/--version: conflicting option string(s): -v")
Greg Ward55493222003-04-21 02:41:25 +00001293
1294 self.assertEqual(err.msg, "conflicting option string(s): -v")
1295 self.assertEqual(err.option_id, "-v/--version")
1296
1297 def test_conflict_error(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001298 self.assertTrueconflict_error(self.parser.add_option)
Greg Ward55493222003-04-21 02:41:25 +00001299
1300 def test_conflict_error_group(self):
1301 group = OptionGroup(self.parser, "Group 1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001302 self.assertTrueconflict_error(group.add_option)
Greg Ward55493222003-04-21 02:41:25 +00001303
1304 def test_no_such_conflict_handler(self):
Greg Wardeba20e62004-07-31 16:15:44 +00001305 self.assertRaises(
1306 self.parser.set_conflict_handler, ('foo',), None,
1307 ValueError, "invalid conflict_resolution value 'foo'")
Greg Ward55493222003-04-21 02:41:25 +00001308
1309
Greg Ward55493222003-04-21 02:41:25 +00001310class TestConflictResolve(ConflictBase):
1311 def setUp(self):
1312 ConflictBase.setUp(self)
1313 self.parser.set_conflict_handler("resolve")
1314 self.parser.add_option("-v", "--version", action="callback",
1315 callback=self.show_version, help="show version")
1316
1317 def test_conflict_resolve(self):
1318 v_opt = self.parser.get_option("-v")
1319 verbose_opt = self.parser.get_option("--verbose")
1320 version_opt = self.parser.get_option("--version")
1321
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001322 self.assertTrue(v_opt is version_opt)
1323 self.assertTrue(v_opt is not verbose_opt)
Greg Ward55493222003-04-21 02:41:25 +00001324 self.assertEqual(v_opt._long_opts, ["--version"])
1325 self.assertEqual(version_opt._short_opts, ["-v"])
1326 self.assertEqual(version_opt._long_opts, ["--version"])
1327 self.assertEqual(verbose_opt._short_opts, [])
1328 self.assertEqual(verbose_opt._long_opts, ["--verbose"])
1329
1330 def test_conflict_resolve_help(self):
Greg Ward48aa84b2004-10-27 02:20:04 +00001331 self.assertOutput(["-h"], """\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001332Options:
Greg Ward55493222003-04-21 02:41:25 +00001333 --verbose increment verbosity
1334 -h, --help show this help message and exit
1335 -v, --version show version
1336""")
1337
1338 def test_conflict_resolve_short_opt(self):
1339 self.assertParseOK(["-v"],
1340 {'verbose': None, 'show_version': 1},
1341 [])
1342
1343 def test_conflict_resolve_long_opt(self):
1344 self.assertParseOK(["--verbose"],
1345 {'verbose': 1},
1346 [])
1347
1348 def test_conflict_resolve_long_opts(self):
1349 self.assertParseOK(["--verbose", "--version"],
1350 {'verbose': 1, 'show_version': 1},
1351 [])
1352
1353class TestConflictOverride(BaseTest):
1354 def setUp(self):
Greg Ward48aa84b2004-10-27 02:20:04 +00001355 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Greg Ward55493222003-04-21 02:41:25 +00001356 self.parser.set_conflict_handler("resolve")
1357 self.parser.add_option("-n", "--dry-run",
1358 action="store_true", dest="dry_run",
1359 help="don't do anything")
1360 self.parser.add_option("--dry-run", "-n",
1361 action="store_const", const=42, dest="dry_run",
1362 help="dry run mode")
1363
1364 def test_conflict_override_opts(self):
1365 opt = self.parser.get_option("--dry-run")
1366 self.assertEqual(opt._short_opts, ["-n"])
1367 self.assertEqual(opt._long_opts, ["--dry-run"])
1368
1369 def test_conflict_override_help(self):
Greg Ward48aa84b2004-10-27 02:20:04 +00001370 self.assertOutput(["-h"], """\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001371Options:
Greg Ward55493222003-04-21 02:41:25 +00001372 -h, --help show this help message and exit
1373 -n, --dry-run dry run mode
1374""")
1375
1376 def test_conflict_override_args(self):
1377 self.assertParseOK(["-n"],
1378 {'dry_run': 42},
1379 [])
1380
1381# -- Other testing. ----------------------------------------------------
1382
Greg Wardeba20e62004-07-31 16:15:44 +00001383_expected_help_basic = """\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001384Usage: bar.py [options]
Greg Wardeba20e62004-07-31 16:15:44 +00001385
Thomas Wouters477c8d52006-05-27 19:21:47 +00001386Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001387 -a APPLE throw APPLEs at basket
1388 -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the
1389 evil spirits that cause trouble and mayhem)
1390 --foo=FOO store FOO in the foo list for later fooing
1391 -h, --help show this help message and exit
1392"""
1393
1394_expected_help_long_opts_first = """\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001395Usage: bar.py [options]
Greg Wardeba20e62004-07-31 16:15:44 +00001396
Thomas Wouters477c8d52006-05-27 19:21:47 +00001397Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001398 -a APPLE throw APPLEs at basket
1399 --boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the
1400 evil spirits that cause trouble and mayhem)
1401 --foo=FOO store FOO in the foo list for later fooing
1402 --help, -h show this help message and exit
1403"""
1404
1405_expected_help_title_formatter = """\
1406Usage
1407=====
1408 bar.py [options]
1409
Thomas Wouters477c8d52006-05-27 19:21:47 +00001410Options
Greg Wardeba20e62004-07-31 16:15:44 +00001411=======
1412-a APPLE throw APPLEs at basket
1413--boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the
1414 evil spirits that cause trouble and mayhem)
1415--foo=FOO store FOO in the foo list for later fooing
1416--help, -h show this help message and exit
1417"""
1418
1419_expected_help_short_lines = """\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001420Usage: bar.py [options]
Greg Wardeba20e62004-07-31 16:15:44 +00001421
Thomas Wouters477c8d52006-05-27 19:21:47 +00001422Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001423 -a APPLE throw APPLEs at basket
1424 -b NUM, --boo=NUM shout "boo!" NUM times (in order to
1425 frighten away all the evil spirits
1426 that cause trouble and mayhem)
1427 --foo=FOO store FOO in the foo list for later
1428 fooing
1429 -h, --help show this help message and exit
1430"""
1431
Greg Ward55493222003-04-21 02:41:25 +00001432class TestHelp(BaseTest):
1433 def setUp(self):
Greg Wardeba20e62004-07-31 16:15:44 +00001434 self.parser = self.make_parser(80)
1435
1436 def make_parser(self, columns):
Greg Ward55493222003-04-21 02:41:25 +00001437 options = [
1438 make_option("-a", type="string", dest='a',
1439 metavar="APPLE", help="throw APPLEs at basket"),
1440 make_option("-b", "--boo", type="int", dest='boo',
1441 metavar="NUM",
1442 help=
1443 "shout \"boo!\" NUM times (in order to frighten away "
1444 "all the evil spirits that cause trouble and mayhem)"),
1445 make_option("--foo", action="append", type="string", dest='foo',
1446 help="store FOO in the foo list for later fooing"),
1447 ]
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001448
1449 # We need to set COLUMNS for the OptionParser constructor, but
1450 # we must restore its original value -- otherwise, this test
1451 # screws things up for other tests when it's part of the Python
1452 # test suite.
Hirokazu Yamamoto71959632009-04-27 01:44:28 +00001453 with support.EnvironmentVarGuard() as env:
Walter Dörwald155374d2009-05-01 19:58:58 +00001454 env['COLUMNS'] = str(columns)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001455 return InterceptingOptionParser(option_list=options)
Greg Ward55493222003-04-21 02:41:25 +00001456
1457 def assertHelpEquals(self, expected_output):
Greg Ward48aa84b2004-10-27 02:20:04 +00001458 save_argv = sys.argv[:]
1459 try:
1460 # Make optparse believe bar.py is being executed.
1461 sys.argv[0] = os.path.join("foo", "bar.py")
1462 self.assertOutput(["-h"], expected_output)
1463 finally:
1464 sys.argv[:] = save_argv
Greg Ward55493222003-04-21 02:41:25 +00001465
1466 def test_help(self):
Greg Wardeba20e62004-07-31 16:15:44 +00001467 self.assertHelpEquals(_expected_help_basic)
Greg Ward55493222003-04-21 02:41:25 +00001468
1469 def test_help_old_usage(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001470 self.parser.set_usage("Usage: %prog [options]")
Greg Wardeba20e62004-07-31 16:15:44 +00001471 self.assertHelpEquals(_expected_help_basic)
Greg Ward55493222003-04-21 02:41:25 +00001472
1473 def test_help_long_opts_first(self):
1474 self.parser.formatter.short_first = 0
Greg Wardeba20e62004-07-31 16:15:44 +00001475 self.assertHelpEquals(_expected_help_long_opts_first)
Greg Ward55493222003-04-21 02:41:25 +00001476
1477 def test_help_title_formatter(self):
Hirokazu Yamamoto71959632009-04-27 01:44:28 +00001478 with support.EnvironmentVarGuard() as env:
Walter Dörwald155374d2009-05-01 19:58:58 +00001479 env["COLUMNS"] = "80"
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001480 self.parser.formatter = TitledHelpFormatter()
1481 self.assertHelpEquals(_expected_help_title_formatter)
Greg Ward55493222003-04-21 02:41:25 +00001482
Greg Wardeba20e62004-07-31 16:15:44 +00001483 def test_wrap_columns(self):
1484 # Ensure that wrapping respects $COLUMNS environment variable.
1485 # Need to reconstruct the parser, since that's the only time
1486 # we look at $COLUMNS.
1487 self.parser = self.make_parser(60)
1488 self.assertHelpEquals(_expected_help_short_lines)
Greg Ward55493222003-04-21 02:41:25 +00001489
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001490 def test_help_unicode(self):
1491 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001492 self.parser.add_option("-a", action="store_true", help="ol\u00E9!")
1493 expect = """\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001494Options:
1495 -h, --help show this help message and exit
1496 -a ol\u00E9!
1497"""
1498 self.assertHelpEquals(expect)
1499
1500 def test_help_unicode_description(self):
1501 self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001502 description="ol\u00E9!")
1503 expect = """\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001504ol\u00E9!
1505
1506Options:
1507 -h, --help show this help message and exit
1508"""
1509 self.assertHelpEquals(expect)
1510
Greg Ward55493222003-04-21 02:41:25 +00001511 def test_help_description_groups(self):
1512 self.parser.set_description(
Greg Wardeba20e62004-07-31 16:15:44 +00001513 "This is the program description for %prog. %prog has "
Greg Ward55493222003-04-21 02:41:25 +00001514 "an option group as well as single options.")
1515
1516 group = OptionGroup(
1517 self.parser, "Dangerous Options",
1518 "Caution: use of these options is at your own risk. "
1519 "It is believed that some of them bite.")
1520 group.add_option("-g", action="store_true", help="Group option.")
1521 self.parser.add_option_group(group)
1522
Thomas Wouters477c8d52006-05-27 19:21:47 +00001523 expect = """\
1524Usage: bar.py [options]
Greg Ward55493222003-04-21 02:41:25 +00001525
Greg Wardeba20e62004-07-31 16:15:44 +00001526This is the program description for bar.py. bar.py has an option group as
1527well as single options.
1528
Thomas Wouters477c8d52006-05-27 19:21:47 +00001529Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001530 -a APPLE throw APPLEs at basket
1531 -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the
1532 evil spirits that cause trouble and mayhem)
1533 --foo=FOO store FOO in the foo list for later fooing
1534 -h, --help show this help message and exit
Greg Ward55493222003-04-21 02:41:25 +00001535
1536 Dangerous Options:
Greg Wardeba20e62004-07-31 16:15:44 +00001537 Caution: use of these options is at your own risk. It is believed
1538 that some of them bite.
1539
1540 -g Group option.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001541"""
Greg Ward55493222003-04-21 02:41:25 +00001542
Thomas Wouters477c8d52006-05-27 19:21:47 +00001543 self.assertHelpEquals(expect)
Greg Wardeba20e62004-07-31 16:15:44 +00001544
Thomas Wouters477c8d52006-05-27 19:21:47 +00001545 self.parser.epilog = "Please report bugs to /dev/null."
1546 self.assertHelpEquals(expect + "\nPlease report bugs to /dev/null.\n")
Tim Peters10d59f32004-10-27 02:43:25 +00001547
Greg Wardeba20e62004-07-31 16:15:44 +00001548
Greg Ward55493222003-04-21 02:41:25 +00001549class TestMatchAbbrev(BaseTest):
1550 def test_match_abbrev(self):
1551 self.assertEqual(_match_abbrev("--f",
1552 {"--foz": None,
1553 "--foo": None,
1554 "--fie": None,
1555 "--f": None}),
1556 "--f")
1557
1558 def test_match_abbrev_error(self):
1559 s = "--f"
1560 wordmap = {"--foz": None, "--foo": None, "--fie": None}
Greg Wardeba20e62004-07-31 16:15:44 +00001561 self.assertRaises(
1562 _match_abbrev, (s, wordmap), None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001563 BadOptionError, "ambiguous option: --f (--fie, --foo, --foz?)")
Greg Wardeba20e62004-07-31 16:15:44 +00001564
1565
Thomas Wouters477c8d52006-05-27 19:21:47 +00001566class TestParseNumber(BaseTest):
1567 def setUp(self):
1568 self.parser = InterceptingOptionParser()
1569 self.parser.add_option("-n", type=int)
Guido van Rossume2a383d2007-01-15 16:59:06 +00001570 self.parser.add_option("-l", type=int)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001571
1572 def test_parse_num_fail(self):
1573 self.assertRaises(
1574 _parse_num, ("", int), {},
1575 ValueError,
1576 re.compile(r"invalid literal for int().*: '?'?"))
1577 self.assertRaises(
Guido van Rossume2a383d2007-01-15 16:59:06 +00001578 _parse_num, ("0xOoops", int), {},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001579 ValueError,
Guido van Rossumb4e87e32007-07-09 10:08:42 +00001580 re.compile(r"invalid literal for int().*: s?'?0xOoops'?"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001581
1582 def test_parse_num_ok(self):
1583 self.assertEqual(_parse_num("0", int), 0)
1584 self.assertEqual(_parse_num("0x10", int), 16)
Guido van Rossume2a383d2007-01-15 16:59:06 +00001585 self.assertEqual(_parse_num("0XA", int), 10)
1586 self.assertEqual(_parse_num("010", int), 8)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001587 self.assertEqual(_parse_num("0b11", int), 3)
Guido van Rossume2a383d2007-01-15 16:59:06 +00001588 self.assertEqual(_parse_num("0b", int), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001589
1590 def test_numeric_options(self):
1591 self.assertParseOK(["-n", "42", "-l", "0x20"],
1592 { "n": 42, "l": 0x20 }, [])
1593 self.assertParseOK(["-n", "0b0101", "-l010"],
1594 { "n": 5, "l": 8 }, [])
1595 self.assertParseFail(["-n008"],
1596 "option -n: invalid integer value: '008'")
1597 self.assertParseFail(["-l0b0123"],
Guido van Rossumddefaf32007-01-14 03:31:43 +00001598 "option -l: invalid integer value: '0b0123'")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001599 self.assertParseFail(["-l", "0x12x"],
Guido van Rossumddefaf32007-01-14 03:31:43 +00001600 "option -l: invalid integer value: '0x12x'")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001601
1602
Greg Ward55493222003-04-21 02:41:25 +00001603def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001604 support.run_unittest(__name__)
Greg Ward55493222003-04-21 02:41:25 +00001605
1606if __name__ == '__main__':
Guido van Rossumd8faa362007-04-27 19:54:29 +00001607 test_main()