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.
16 from StringIO
import StringIO
17 from test
import test_support
20 from optparse
import make_option
, Option
, \
21 TitledHelpFormatter
, OptionParser
, OptionGroup
, \
22 SUPPRESS_USAGE
, OptionError
, OptionConflictError
, \
23 BadOptionError
, OptionValueError
, Values
24 from optparse
import _match_abbrev
25 from optparse
import _parse_num
27 retype
= type(re
.compile(''))
29 class InterceptedError(Exception):
34 self
.error_message
= error_message
35 self
.exit_status
= exit_status
36 self
.exit_message
= exit_message
39 return self
.error_message
or self
.exit_message
or "intercepted error"
41 class InterceptingOptionParser(OptionParser
):
42 def exit(self
, status
=0, msg
=None):
43 raise InterceptedError(exit_status
=status
, exit_message
=msg
)
46 raise InterceptedError(error_message
=msg
)
49 class BaseTest(unittest
.TestCase
):
50 def assertParseOK(self
, args
, expected_opts
, expected_positional_args
):
51 """Assert the options are what we expected when parsing arguments.
53 Otherwise, fail with a nicely formatted message.
56 args -- A list of arguments to parse with OptionParser.
57 expected_opts -- The options expected.
58 expected_positional_args -- The positional arguments expected.
60 Returns the options and positional args for further testing.
63 (options
, positional_args
) = self
.parser
.parse_args(args
)
64 optdict
= vars(options
)
66 self
.assertEqual(optdict
, expected_opts
,
68 Options are %(optdict)s.
69 Should be %(expected_opts)s.
70 Args were %(args)s.""" % locals())
72 self
.assertEqual(positional_args
, expected_positional_args
,
74 Positional arguments are %(positional_args)s.
75 Should be %(expected_positional_args)s.
76 Args were %(args)s.""" % locals ())
78 return (options
, positional_args
)
80 def assertRaises(self
,
87 Assert that the expected exception is raised when calling a
88 function, and that the right error message is included with
92 func -- the function to call
93 args -- positional arguments to `func`
94 kwargs -- keyword arguments to `func`
95 expected_exception -- exception that should be raised
96 expected_message -- expected exception message (or pattern
97 if a compiled regex object)
99 Returns the exception raised for further testing.
107 func(*args
, **kwargs
)
108 except expected_exception
, err
:
109 actual_message
= str(err
)
110 if isinstance(expected_message
, retype
):
111 self
.assertTrue(expected_message
.search(actual_message
),
113 expected exception message pattern:
115 actual exception message:
117 """ % (expected_message
.pattern
, actual_message
))
119 self
.assertEqual(actual_message
,
122 expected exception message:
124 actual exception message:
126 """ % (expected_message
, actual_message
))
130 self
.fail("""expected exception %(expected_exception)s not raised
133 and kwargs %(kwargs)r
137 # -- Assertions used in more than one class --------------------
139 def assertParseFail(self
, cmdline_args
, expected_output
):
141 Assert the parser fails with the expected message. Caller
142 must ensure that self.parser is an InterceptingOptionParser.
145 self
.parser
.parse_args(cmdline_args
)
146 except InterceptedError
, err
:
147 self
.assertEqual(err
.error_message
, expected_output
)
149 self
.assertFalse("expected parse failure")
151 def assertOutput(self
,
155 expected_error
=None):
156 """Assert the parser prints the expected output on stdout."""
157 save_stdout
= sys
.stdout
158 encoding
= getattr(save_stdout
, 'encoding', None)
161 sys
.stdout
= StringIO()
163 sys
.stdout
.encoding
= encoding
164 self
.parser
.parse_args(cmdline_args
)
166 output
= sys
.stdout
.getvalue()
167 sys
.stdout
= save_stdout
169 except InterceptedError
, err
:
171 type(output
) is types
.StringType
,
172 "expected output to be an ordinary string, not %r"
175 if output
!= expected_output
:
176 self
.fail("expected: \n'''\n" + expected_output
+
177 "'''\nbut got \n'''\n" + output
+ "'''")
178 self
.assertEqual(err
.exit_status
, expected_status
)
179 self
.assertEqual(err
.exit_message
, expected_error
)
181 self
.assertFalse("expected parser.exit()")
183 def assertTypeError(self
, func
, expected_message
, *args
):
184 """Assert that TypeError is raised when executing func."""
185 self
.assertRaises(func
, args
, None, TypeError, expected_message
)
187 def assertHelp(self
, parser
, expected_help
):
188 actual_help
= parser
.format_help()
189 if actual_help
!= expected_help
:
190 raise self
.failureException(
191 'help text failure; expected:\n"' +
192 expected_help
+ '"; got:\n"' +
195 # -- Test make_option() aka Option -------------------------------------
197 # It's not necessary to test correct options here. All the tests in the
198 # parser.parse_args() section deal with those, because they're needed
201 class TestOptionChecks(BaseTest
):
203 self
.parser
= OptionParser(usage
=SUPPRESS_USAGE
)
205 def assertOptionError(self
, expected_message
, args
=[], kwargs
={}):
206 self
.assertRaises(make_option
, args
, kwargs
,
207 OptionError
, expected_message
)
209 def test_opt_string_empty(self
):
210 self
.assertTypeError(make_option
,
211 "at least one option string must be supplied")
213 def test_opt_string_too_short(self
):
214 self
.assertOptionError(
215 "invalid option string 'b': must be at least two characters long",
218 def test_opt_string_short_invalid(self
):
219 self
.assertOptionError(
220 "invalid short option string '--': must be "
221 "of the form -x, (x any non-dash char)",
224 def test_opt_string_long_invalid(self
):
225 self
.assertOptionError(
226 "invalid long option string '---': "
227 "must start with --, followed by non-dash",
230 def test_attr_invalid(self
):
231 self
.assertOptionError(
232 "option -b: invalid keyword arguments: bar, foo",
233 ["-b"], {'foo': None, 'bar': None})
235 def test_action_invalid(self
):
236 self
.assertOptionError(
237 "option -b: invalid action: 'foo'",
238 ["-b"], {'action': 'foo'})
240 def test_type_invalid(self
):
241 self
.assertOptionError(
242 "option -b: invalid option type: 'foo'",
243 ["-b"], {'type': 'foo'})
244 self
.assertOptionError(
245 "option -b: invalid option type: 'tuple'",
246 ["-b"], {'type': tuple})
248 def test_no_type_for_action(self
):
249 self
.assertOptionError(
250 "option -b: must not supply a type for action 'count'",
251 ["-b"], {'action': 'count', 'type': 'int'})
253 def test_no_choices_list(self
):
254 self
.assertOptionError(
255 "option -b/--bad: must supply a list of "
256 "choices for type 'choice'",
257 ["-b", "--bad"], {'type': "choice"})
259 def test_bad_choices_list(self
):
260 typename
= type('').__name
__
261 self
.assertOptionError(
262 "option -b/--bad: choices must be a list of "
263 "strings ('%s' supplied)" % typename
,
265 {'type': "choice", 'choices':"bad choices"})
267 def test_no_choices_for_type(self
):
268 self
.assertOptionError(
269 "option -b: must not supply choices for type 'int'",
270 ["-b"], {'type': 'int', 'choices':"bad"})
272 def test_no_const_for_action(self
):
273 self
.assertOptionError(
274 "option -b: 'const' must not be supplied for action 'store'",
275 ["-b"], {'action': 'store', 'const': 1})
277 def test_no_nargs_for_action(self
):
278 self
.assertOptionError(
279 "option -b: 'nargs' must not be supplied for action 'count'",
280 ["-b"], {'action': 'count', 'nargs': 2})
282 def test_callback_not_callable(self
):
283 self
.assertOptionError(
284 "option -b: callback not callable: 'foo'",
285 ["-b"], {'action': 'callback',
291 def test_callback_args_no_tuple(self
):
292 self
.assertOptionError(
293 "option -b: callback_args, if supplied, "
294 "must be a tuple: not 'foo'",
295 ["-b"], {'action': 'callback',
296 'callback': self
.dummy
,
297 'callback_args': 'foo'})
299 def test_callback_kwargs_no_dict(self
):
300 self
.assertOptionError(
301 "option -b: callback_kwargs, if supplied, "
302 "must be a dict: not 'foo'",
303 ["-b"], {'action': 'callback',
304 'callback': self
.dummy
,
305 'callback_kwargs': 'foo'})
307 def test_no_callback_for_action(self
):
308 self
.assertOptionError(
309 "option -b: callback supplied ('foo') for non-callback option",
310 ["-b"], {'action': 'store',
313 def test_no_callback_args_for_action(self
):
314 self
.assertOptionError(
315 "option -b: callback_args supplied for non-callback option",
316 ["-b"], {'action': 'store',
317 'callback_args': 'foo'})
319 def test_no_callback_kwargs_for_action(self
):
320 self
.assertOptionError(
321 "option -b: callback_kwargs supplied for non-callback option",
322 ["-b"], {'action': 'store',
323 'callback_kwargs': 'foo'})
325 class TestOptionParser(BaseTest
):
327 self
.parser
= OptionParser()
328 self
.parser
.add_option("-v", "--verbose", "-n", "--noisy",
329 action
="store_true", dest
="verbose")
330 self
.parser
.add_option("-q", "--quiet", "--silent",
331 action
="store_false", dest
="verbose")
333 def test_add_option_no_Option(self
):
334 self
.assertTypeError(self
.parser
.add_option
,
335 "not an Option instance: None", None)
337 def test_add_option_invalid_arguments(self
):
338 self
.assertTypeError(self
.parser
.add_option
,
339 "invalid arguments", None, None)
341 def test_get_option(self
):
342 opt1
= self
.parser
.get_option("-v")
343 self
.assertIsInstance(opt1
, Option
)
344 self
.assertEqual(opt1
._short_opts
, ["-v", "-n"])
345 self
.assertEqual(opt1
._long_opts
, ["--verbose", "--noisy"])
346 self
.assertEqual(opt1
.action
, "store_true")
347 self
.assertEqual(opt1
.dest
, "verbose")
349 def test_get_option_equals(self
):
350 opt1
= self
.parser
.get_option("-v")
351 opt2
= self
.parser
.get_option("--verbose")
352 opt3
= self
.parser
.get_option("-n")
353 opt4
= self
.parser
.get_option("--noisy")
354 self
.assertTrue(opt1
is opt2
is opt3
is opt4
)
356 def test_has_option(self
):
357 self
.assertTrue(self
.parser
.has_option("-v"))
358 self
.assertTrue(self
.parser
.has_option("--verbose"))
360 def assertTrueremoved(self
):
361 self
.assertTrue(self
.parser
.get_option("-v") is None)
362 self
.assertTrue(self
.parser
.get_option("--verbose") is None)
363 self
.assertTrue(self
.parser
.get_option("-n") is None)
364 self
.assertTrue(self
.parser
.get_option("--noisy") is None)
366 self
.assertFalse(self
.parser
.has_option("-v"))
367 self
.assertFalse(self
.parser
.has_option("--verbose"))
368 self
.assertFalse(self
.parser
.has_option("-n"))
369 self
.assertFalse(self
.parser
.has_option("--noisy"))
371 self
.assertTrue(self
.parser
.has_option("-q"))
372 self
.assertTrue(self
.parser
.has_option("--silent"))
374 def test_remove_short_opt(self
):
375 self
.parser
.remove_option("-n")
376 self
.assertTrueremoved()
378 def test_remove_long_opt(self
):
379 self
.parser
.remove_option("--verbose")
380 self
.assertTrueremoved()
382 def test_remove_nonexistent(self
):
383 self
.assertRaises(self
.parser
.remove_option
, ('foo',), None,
384 ValueError, "no such option 'foo'")
386 def test_refleak(self
):
387 # If an OptionParser is carrying around a reference to a large
388 # object, various cycles can prevent it from being GC'd in
389 # a timely fashion. destroy() breaks the cycles to ensure stuff
392 refcount
= sys
.getrefcount(big_thing
)
393 parser
= OptionParser()
394 parser
.add_option("-a", "--aaarggh")
395 parser
.big_thing
= big_thing
398 #self.assertEqual(refcount, sys.getrefcount(big_thing))
400 self
.assertEqual(refcount
, sys
.getrefcount(big_thing
))
403 class TestOptionValues(BaseTest
):
407 def test_basics(self
):
409 self
.assertEqual(vars(values
), {})
410 self
.assertEqual(values
, {})
411 self
.assertNotEqual(values
, {"foo": "bar"})
412 self
.assertNotEqual(values
, "")
414 dict = {"foo": "bar", "baz": 42}
415 values
= Values(defaults
=dict)
416 self
.assertEqual(vars(values
), dict)
417 self
.assertEqual(values
, dict)
418 self
.assertNotEqual(values
, {"foo": "bar"})
419 self
.assertNotEqual(values
, {})
420 self
.assertNotEqual(values
, "")
421 self
.assertNotEqual(values
, [])
424 class TestTypeAliases(BaseTest
):
426 self
.parser
= OptionParser()
428 def test_str_aliases_string(self
):
429 self
.parser
.add_option("-s", type="str")
430 self
.assertEquals(self
.parser
.get_option("-s").type, "string")
432 def test_new_type_object(self
):
433 self
.parser
.add_option("-s", type=str)
434 self
.assertEquals(self
.parser
.get_option("-s").type, "string")
435 self
.parser
.add_option("-x", type=int)
436 self
.assertEquals(self
.parser
.get_option("-x").type, "int")
438 def test_old_type_object(self
):
439 self
.parser
.add_option("-s", type=types
.StringType
)
440 self
.assertEquals(self
.parser
.get_option("-s").type, "string")
441 self
.parser
.add_option("-x", type=types
.IntType
)
442 self
.assertEquals(self
.parser
.get_option("-x").type, "int")
445 # Custom type for testing processing of default values.
446 _time_units
= { 's' : 1, 'm' : 60, 'h' : 60*60, 'd' : 60*60*24 }
448 def _check_duration(option
, opt
, value
):
450 if value
[-1].isdigit():
453 return int(value
[:-1]) * _time_units
[value
[-1]]
454 except (ValueError, IndexError):
455 raise OptionValueError(
456 'option %s: invalid duration: %r' % (opt
, value
))
458 class DurationOption(Option
):
459 TYPES
= Option
.TYPES
+ ('duration',)
460 TYPE_CHECKER
= copy
.copy(Option
.TYPE_CHECKER
)
461 TYPE_CHECKER
['duration'] = _check_duration
463 class TestDefaultValues(BaseTest
):
465 self
.parser
= OptionParser()
466 self
.parser
.add_option("-v", "--verbose", default
=True)
467 self
.parser
.add_option("-q", "--quiet", dest
='verbose')
468 self
.parser
.add_option("-n", type="int", default
=37)
469 self
.parser
.add_option("-m", type="int")
470 self
.parser
.add_option("-s", default
="foo")
471 self
.parser
.add_option("-t")
472 self
.parser
.add_option("-u", default
=None)
473 self
.expected
= { 'verbose': True,
480 def test_basic_defaults(self
):
481 self
.assertEqual(self
.parser
.get_default_values(), self
.expected
)
483 def test_mixed_defaults_post(self
):
484 self
.parser
.set_defaults(n
=42, m
=-100)
485 self
.expected
.update({'n': 42, 'm': -100})
486 self
.assertEqual(self
.parser
.get_default_values(), self
.expected
)
488 def test_mixed_defaults_pre(self
):
489 self
.parser
.set_defaults(x
="barf", y
="blah")
490 self
.parser
.add_option("-x", default
="frob")
491 self
.parser
.add_option("-y")
493 self
.expected
.update({'x': "frob", 'y': "blah"})
494 self
.assertEqual(self
.parser
.get_default_values(), self
.expected
)
496 self
.parser
.remove_option("-y")
497 self
.parser
.add_option("-y", default
=None)
498 self
.expected
.update({'y': None})
499 self
.assertEqual(self
.parser
.get_default_values(), self
.expected
)
501 def test_process_default(self
):
502 self
.parser
.option_class
= DurationOption
503 self
.parser
.add_option("-d", type="duration", default
=300)
504 self
.parser
.add_option("-e", type="duration", default
="6m")
505 self
.parser
.set_defaults(n
="42")
506 self
.expected
.update({'d': 300, 'e': 360, 'n': 42})
507 self
.assertEqual(self
.parser
.get_default_values(), self
.expected
)
509 self
.parser
.set_process_default_values(False)
510 self
.expected
.update({'d': 300, 'e': "6m", 'n': "42"})
511 self
.assertEqual(self
.parser
.get_default_values(), self
.expected
)
514 class TestProgName(BaseTest
):
516 Test that %prog expands to the right thing in usage, version,
520 def assertUsage(self
, parser
, expected_usage
):
521 self
.assertEqual(parser
.get_usage(), expected_usage
)
523 def assertVersion(self
, parser
, expected_version
):
524 self
.assertEqual(parser
.get_version(), expected_version
)
527 def test_default_progname(self
):
528 # Make sure that program name taken from sys.argv[0] by default.
529 save_argv
= sys
.argv
[:]
531 sys
.argv
[0] = os
.path
.join("foo", "bar", "baz.py")
532 parser
= OptionParser("%prog ...", version
="%prog 1.2")
533 expected_usage
= "Usage: baz.py ...\n"
534 self
.assertUsage(parser
, expected_usage
)
535 self
.assertVersion(parser
, "baz.py 1.2")
536 self
.assertHelp(parser
,
537 expected_usage
+ "\n" +
539 " --version show program's version number and exit\n"
540 " -h, --help show this help message and exit\n")
542 sys
.argv
[:] = save_argv
544 def test_custom_progname(self
):
545 parser
= OptionParser(prog
="thingy",
547 usage
="%prog arg arg")
548 parser
.remove_option("-h")
549 parser
.remove_option("--version")
550 expected_usage
= "Usage: thingy arg arg\n"
551 self
.assertUsage(parser
, expected_usage
)
552 self
.assertVersion(parser
, "thingy 0.1")
553 self
.assertHelp(parser
, expected_usage
+ "\n")
556 class TestExpandDefaults(BaseTest
):
558 self
.parser
= OptionParser(prog
="test")
559 self
.help_prefix
= """\
560 Usage: test [options]
563 -h, --help show this help message and exit
565 self
.file_help
= "read from FILE [default: %default]"
566 self
.expected_help_file
= self
.help_prefix
+ \
567 " -f FILE, --file=FILE read from FILE [default: foo.txt]\n"
568 self
.expected_help_none
= self
.help_prefix
+ \
569 " -f FILE, --file=FILE read from FILE [default: none]\n"
571 def test_option_default(self
):
572 self
.parser
.add_option("-f", "--file",
575 self
.assertHelp(self
.parser
, self
.expected_help_file
)
577 def test_parser_default_1(self
):
578 self
.parser
.add_option("-f", "--file",
580 self
.parser
.set_default('file', "foo.txt")
581 self
.assertHelp(self
.parser
, self
.expected_help_file
)
583 def test_parser_default_2(self
):
584 self
.parser
.add_option("-f", "--file",
586 self
.parser
.set_defaults(file="foo.txt")
587 self
.assertHelp(self
.parser
, self
.expected_help_file
)
589 def test_no_default(self
):
590 self
.parser
.add_option("-f", "--file",
592 self
.assertHelp(self
.parser
, self
.expected_help_none
)
594 def test_default_none_1(self
):
595 self
.parser
.add_option("-f", "--file",
598 self
.assertHelp(self
.parser
, self
.expected_help_none
)
600 def test_default_none_2(self
):
601 self
.parser
.add_option("-f", "--file",
603 self
.parser
.set_defaults(file=None)
604 self
.assertHelp(self
.parser
, self
.expected_help_none
)
606 def test_float_default(self
):
607 self
.parser
.add_option(
609 help="blow up with probability PROB [default: %default]")
610 self
.parser
.set_defaults(prob
=0.43)
611 expected_help
= self
.help_prefix
+ \
612 " -p PROB, --prob=PROB blow up with probability PROB [default: 0.43]\n"
613 self
.assertHelp(self
.parser
, expected_help
)
615 def test_alt_expand(self
):
616 self
.parser
.add_option("-f", "--file",
618 help="read from FILE [default: *DEFAULT*]")
619 self
.parser
.formatter
.default_tag
= "*DEFAULT*"
620 self
.assertHelp(self
.parser
, self
.expected_help_file
)
622 def test_no_expand(self
):
623 self
.parser
.add_option("-f", "--file",
625 help="read from %default file")
626 self
.parser
.formatter
.default_tag
= None
627 expected_help
= self
.help_prefix
+ \
628 " -f FILE, --file=FILE read from %default file\n"
629 self
.assertHelp(self
.parser
, expected_help
)
632 # -- Test parser.parse_args() ------------------------------------------
634 class TestStandard(BaseTest
):
636 options
= [make_option("-a", type="string"),
637 make_option("-b", "--boo", type="int", dest
='boo'),
638 make_option("--foo", action
="append")]
640 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
,
643 def test_required_value(self
):
644 self
.assertParseFail(["-a"], "-a option requires an argument")
646 def test_invalid_integer(self
):
647 self
.assertParseFail(["-b", "5x"],
648 "option -b: invalid integer value: '5x'")
650 def test_no_such_option(self
):
651 self
.assertParseFail(["--boo13"], "no such option: --boo13")
653 def test_long_invalid_integer(self
):
654 self
.assertParseFail(["--boo=x5"],
655 "option --boo: invalid integer value: 'x5'")
657 def test_empty(self
):
658 self
.assertParseOK([], {'a': None, 'boo': None, 'foo': None}, [])
660 def test_shortopt_empty_longopt_append(self
):
661 self
.assertParseOK(["-a", "", "--foo=blah", "--foo="],
662 {'a': "", 'boo': None, 'foo': ["blah", ""]},
665 def test_long_option_append(self
):
666 self
.assertParseOK(["--foo", "bar", "--foo", "", "--foo=x"],
669 'foo': ["bar", "", "x"]},
672 def test_option_argument_joined(self
):
673 self
.assertParseOK(["-abc"],
674 {'a': "bc", 'boo': None, 'foo': None},
677 def test_option_argument_split(self
):
678 self
.assertParseOK(["-a", "34"],
679 {'a': "34", 'boo': None, 'foo': None},
682 def test_option_argument_joined_integer(self
):
683 self
.assertParseOK(["-b34"],
684 {'a': None, 'boo': 34, 'foo': None},
687 def test_option_argument_split_negative_integer(self
):
688 self
.assertParseOK(["-b", "-5"],
689 {'a': None, 'boo': -5, 'foo': None},
692 def test_long_option_argument_joined(self
):
693 self
.assertParseOK(["--boo=13"],
694 {'a': None, 'boo': 13, 'foo': None},
697 def test_long_option_argument_split(self
):
698 self
.assertParseOK(["--boo", "111"],
699 {'a': None, 'boo': 111, 'foo': None},
702 def test_long_option_short_option(self
):
703 self
.assertParseOK(["--foo=bar", "-axyz"],
704 {'a': 'xyz', 'boo': None, 'foo': ["bar"]},
707 def test_abbrev_long_option(self
):
708 self
.assertParseOK(["--f=bar", "-axyz"],
709 {'a': 'xyz', 'boo': None, 'foo': ["bar"]},
712 def test_defaults(self
):
713 (options
, args
) = self
.parser
.parse_args([])
714 defaults
= self
.parser
.get_default_values()
715 self
.assertEqual(vars(defaults
), vars(options
))
717 def test_ambiguous_option(self
):
718 self
.parser
.add_option("--foz", action
="store",
719 type="string", dest
="foo")
720 self
.assertParseFail(["--f=bar"],
721 "ambiguous option: --f (--foo, --foz?)")
724 def test_short_and_long_option_split(self
):
725 self
.assertParseOK(["-a", "xyz", "--foo", "bar"],
726 {'a': 'xyz', 'boo': None, 'foo': ["bar"]},
729 def test_short_option_split_long_option_append(self
):
730 self
.assertParseOK(["--foo=bar", "-b", "123", "--foo", "baz"],
731 {'a': None, 'boo': 123, 'foo': ["bar", "baz"]},
734 def test_short_option_split_one_positional_arg(self
):
735 self
.assertParseOK(["-a", "foo", "bar"],
736 {'a': "foo", 'boo': None, 'foo': None},
739 def test_short_option_consumes_separator(self
):
740 self
.assertParseOK(["-a", "--", "foo", "bar"],
741 {'a': "--", 'boo': None, 'foo': None},
743 self
.assertParseOK(["-a", "--", "--foo", "bar"],
744 {'a': "--", 'boo': None, 'foo': ["bar"]},
747 def test_short_option_joined_and_separator(self
):
748 self
.assertParseOK(["-ab", "--", "--foo", "bar"],
749 {'a': "b", 'boo': None, 'foo': None},
752 def test_hyphen_becomes_positional_arg(self
):
753 self
.assertParseOK(["-ab", "-", "--foo", "bar"],
754 {'a': "b", 'boo': None, 'foo': ["bar"]},
757 def test_no_append_versus_append(self
):
758 self
.assertParseOK(["-b3", "-b", "5", "--foo=bar", "--foo", "baz"],
759 {'a': None, 'boo': 5, 'foo': ["bar", "baz"]},
762 def test_option_consumes_optionlike_string(self
):
763 self
.assertParseOK(["-a", "-b3"],
764 {'a': "-b3", 'boo': None, 'foo': None},
767 def test_combined_single_invalid_option(self
):
768 self
.parser
.add_option("-t", action
="store_true")
769 self
.assertParseFail(["-test"],
770 "no such option: -e")
772 class TestBool(BaseTest
):
774 options
= [make_option("-v",
781 action
="store_false",
783 self
.parser
= OptionParser(option_list
= options
)
785 def test_bool_default(self
):
786 self
.assertParseOK([],
790 def test_bool_false(self
):
791 (options
, args
) = self
.assertParseOK(["-q"],
794 if hasattr(__builtins__
, 'False'):
795 self
.assertTrue(options
.verbose
is False)
797 def test_bool_true(self
):
798 (options
, args
) = self
.assertParseOK(["-v"],
801 if hasattr(__builtins__
, 'True'):
802 self
.assertTrue(options
.verbose
is True)
804 def test_bool_flicker_on_and_off(self
):
805 self
.assertParseOK(["-qvq", "-q", "-v"],
809 class TestChoice(BaseTest
):
811 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
)
812 self
.parser
.add_option("-c", action
="store", type="choice",
813 dest
="choice", choices
=["one", "two", "three"])
815 def test_valid_choice(self
):
816 self
.assertParseOK(["-c", "one", "xyz"],
820 def test_invalid_choice(self
):
821 self
.assertParseFail(["-c", "four", "abc"],
822 "option -c: invalid choice: 'four' "
823 "(choose from 'one', 'two', 'three')")
825 def test_add_choice_option(self
):
826 self
.parser
.add_option("-d", "--default",
827 choices
=["four", "five", "six"])
828 opt
= self
.parser
.get_option("-d")
829 self
.assertEqual(opt
.type, "choice")
830 self
.assertEqual(opt
.action
, "store")
832 class TestCount(BaseTest
):
834 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
)
835 self
.v_opt
= make_option("-v", action
="count", dest
="verbose")
836 self
.parser
.add_option(self
.v_opt
)
837 self
.parser
.add_option("--verbose", type="int", dest
="verbose")
838 self
.parser
.add_option("-q", "--quiet",
839 action
="store_const", dest
="verbose", const
=0)
841 def test_empty(self
):
842 self
.assertParseOK([], {'verbose': None}, [])
844 def test_count_one(self
):
845 self
.assertParseOK(["-v"], {'verbose': 1}, [])
847 def test_count_three(self
):
848 self
.assertParseOK(["-vvv"], {'verbose': 3}, [])
850 def test_count_three_apart(self
):
851 self
.assertParseOK(["-v", "-v", "-v"], {'verbose': 3}, [])
853 def test_count_override_amount(self
):
854 self
.assertParseOK(["-vvv", "--verbose=2"], {'verbose': 2}, [])
856 def test_count_override_quiet(self
):
857 self
.assertParseOK(["-vvv", "--verbose=2", "-q"], {'verbose': 0}, [])
859 def test_count_overriding(self
):
860 self
.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"],
863 def test_count_interspersed_args(self
):
864 self
.assertParseOK(["--quiet", "3", "-v"],
868 def test_count_no_interspersed_args(self
):
869 self
.parser
.disable_interspersed_args()
870 self
.assertParseOK(["--quiet", "3", "-v"],
874 def test_count_no_such_option(self
):
875 self
.assertParseFail(["-q3", "-v"], "no such option: -3")
877 def test_count_option_no_value(self
):
878 self
.assertParseFail(["--quiet=3", "-v"],
879 "--quiet option does not take a value")
881 def test_count_with_default(self
):
882 self
.parser
.set_default('verbose', 0)
883 self
.assertParseOK([], {'verbose':0}, [])
885 def test_count_overriding_default(self
):
886 self
.parser
.set_default('verbose', 0)
887 self
.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"],
890 class TestMultipleArgs(BaseTest
):
892 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
)
893 self
.parser
.add_option("-p", "--point",
894 action
="store", nargs
=3, type="float", dest
="point")
896 def test_nargs_with_positional_args(self
):
897 self
.assertParseOK(["foo", "-p", "1", "2.5", "-4.3", "xyz"],
898 {'point': (1.0, 2.5, -4.3)},
901 def test_nargs_long_opt(self
):
902 self
.assertParseOK(["--point", "-1", "2.5", "-0", "xyz"],
903 {'point': (-1.0, 2.5, -0.0)},
906 def test_nargs_invalid_float_value(self
):
907 self
.assertParseFail(["-p", "1.0", "2x", "3.5"],
909 "invalid floating-point value: '2x'")
911 def test_nargs_required_values(self
):
912 self
.assertParseFail(["--point", "1.0", "3.5"],
913 "--point option requires 3 arguments")
915 class TestMultipleArgsAppend(BaseTest
):
917 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
)
918 self
.parser
.add_option("-p", "--point", action
="store", nargs
=3,
919 type="float", dest
="point")
920 self
.parser
.add_option("-f", "--foo", action
="append", nargs
=2,
921 type="int", dest
="foo")
922 self
.parser
.add_option("-z", "--zero", action
="append_const",
923 dest
="foo", const
=(0, 0))
925 def test_nargs_append(self
):
926 self
.assertParseOK(["-f", "4", "-3", "blah", "--foo", "1", "666"],
927 {'point': None, 'foo': [(4, -3), (1, 666)]},
930 def test_nargs_append_required_values(self
):
931 self
.assertParseFail(["-f4,3"],
932 "-f option requires 2 arguments")
934 def test_nargs_append_simple(self
):
935 self
.assertParseOK(["--foo=3", "4"],
936 {'point': None, 'foo':[(3, 4)]},
939 def test_nargs_append_const(self
):
940 self
.assertParseOK(["--zero", "--foo", "3", "4", "-z"],
941 {'point': None, 'foo':[(0, 0), (3, 4), (0, 0)]},
944 class TestVersion(BaseTest
):
945 def test_version(self
):
946 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
,
948 save_argv
= sys
.argv
[:]
950 sys
.argv
[0] = os
.path
.join(os
.curdir
, "foo", "bar")
951 self
.assertOutput(["--version"], "bar 0.1\n")
953 sys
.argv
[:] = save_argv
955 def test_no_version(self
):
956 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
)
957 self
.assertParseFail(["--version"],
958 "no such option: --version")
960 # -- Test conflicting default values and parser.parse_args() -----------
962 class TestConflictingDefaults(BaseTest
):
963 """Conflicting default values: the last one should win."""
965 self
.parser
= OptionParser(option_list
=[
966 make_option("-v", action
="store_true", dest
="verbose", default
=1)])
968 def test_conflict_default(self
):
969 self
.parser
.add_option("-q", action
="store_false", dest
="verbose",
971 self
.assertParseOK([], {'verbose': 0}, [])
973 def test_conflict_default_none(self
):
974 self
.parser
.add_option("-q", action
="store_false", dest
="verbose",
976 self
.assertParseOK([], {'verbose': None}, [])
978 class TestOptionGroup(BaseTest
):
980 self
.parser
= OptionParser(usage
=SUPPRESS_USAGE
)
982 def test_option_group_create_instance(self
):
983 group
= OptionGroup(self
.parser
, "Spam")
984 self
.parser
.add_option_group(group
)
985 group
.add_option("--spam", action
="store_true",
986 help="spam spam spam spam")
987 self
.assertParseOK(["--spam"], {'spam': 1}, [])
989 def test_add_group_no_group(self
):
990 self
.assertTypeError(self
.parser
.add_option_group
,
991 "not an OptionGroup instance: None", None)
993 def test_add_group_invalid_arguments(self
):
994 self
.assertTypeError(self
.parser
.add_option_group
,
995 "invalid arguments", None, None)
997 def test_add_group_wrong_parser(self
):
998 group
= OptionGroup(self
.parser
, "Spam")
999 group
.parser
= OptionParser()
1000 self
.assertRaises(self
.parser
.add_option_group
, (group
,), None,
1001 ValueError, "invalid OptionGroup (wrong parser)")
1003 def test_group_manipulate(self
):
1004 group
= self
.parser
.add_option_group("Group 2",
1005 description
="Some more options")
1006 group
.set_title("Bacon")
1007 group
.add_option("--bacon", type="int")
1008 self
.assertTrue(self
.parser
.get_option_group("--bacon"), group
)
1010 # -- Test extending and parser.parse_args() ----------------------------
1012 class TestExtendAddTypes(BaseTest
):
1014 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
,
1015 option_class
=self
.MyOption
)
1016 self
.parser
.add_option("-a", None, type="string", dest
="a")
1017 self
.parser
.add_option("-f", "--file", type="file", dest
="file")
1020 if os
.path
.isdir(test_support
.TESTFN
):
1021 os
.rmdir(test_support
.TESTFN
)
1022 elif os
.path
.isfile(test_support
.TESTFN
):
1023 os
.unlink(test_support
.TESTFN
)
1025 class MyOption (Option
):
1026 def check_file(option
, opt
, value
):
1027 if not os
.path
.exists(value
):
1028 raise OptionValueError("%s: file does not exist" % value
)
1029 elif not os
.path
.isfile(value
):
1030 raise OptionValueError("%s: not a regular file" % value
)
1033 TYPES
= Option
.TYPES
+ ("file",)
1034 TYPE_CHECKER
= copy
.copy(Option
.TYPE_CHECKER
)
1035 TYPE_CHECKER
["file"] = check_file
1037 def test_filetype_ok(self
):
1038 open(test_support
.TESTFN
, "w").close()
1039 self
.assertParseOK(["--file", test_support
.TESTFN
, "-afoo"],
1040 {'file': test_support
.TESTFN
, 'a': 'foo'},
1043 def test_filetype_noexist(self
):
1044 self
.assertParseFail(["--file", test_support
.TESTFN
, "-afoo"],
1045 "%s: file does not exist" %
1046 test_support
.TESTFN
)
1048 def test_filetype_notfile(self
):
1049 os
.mkdir(test_support
.TESTFN
)
1050 self
.assertParseFail(["--file", test_support
.TESTFN
, "-afoo"],
1051 "%s: not a regular file" %
1052 test_support
.TESTFN
)
1055 class TestExtendAddActions(BaseTest
):
1057 options
= [self
.MyOption("-a", "--apple", action
="extend",
1058 type="string", dest
="apple")]
1059 self
.parser
= OptionParser(option_list
=options
)
1061 class MyOption (Option
):
1062 ACTIONS
= Option
.ACTIONS
+ ("extend",)
1063 STORE_ACTIONS
= Option
.STORE_ACTIONS
+ ("extend",)
1064 TYPED_ACTIONS
= Option
.TYPED_ACTIONS
+ ("extend",)
1066 def take_action(self
, action
, dest
, opt
, value
, values
, parser
):
1067 if action
== "extend":
1068 lvalue
= value
.split(",")
1069 values
.ensure_value(dest
, []).extend(lvalue
)
1071 Option
.take_action(self
, action
, dest
, opt
, parser
, value
,
1074 def test_extend_add_action(self
):
1075 self
.assertParseOK(["-afoo,bar", "--apple=blah"],
1076 {'apple': ["foo", "bar", "blah"]},
1079 def test_extend_add_action_normal(self
):
1080 self
.assertParseOK(["-a", "foo", "-abar", "--apple=x,y"],
1081 {'apple': ["foo", "bar", "x", "y"]},
1084 # -- Test callbacks and parser.parse_args() ----------------------------
1086 class TestCallback(BaseTest
):
1088 options
= [make_option("-x",
1091 callback
=self
.process_opt
),
1095 callback
=self
.process_opt
,
1098 self
.parser
= OptionParser(option_list
=options
)
1100 def process_opt(self
, option
, opt
, value
, parser_
):
1102 self
.assertEqual(option
._short
_opts
, ["-x"])
1103 self
.assertEqual(option
._long
_opts
, [])
1104 self
.assertTrue(parser_
is self
.parser
)
1105 self
.assertTrue(value
is None)
1106 self
.assertEqual(vars(parser_
.values
), {'filename': None})
1108 parser_
.values
.x
= 42
1109 elif opt
== "--file":
1110 self
.assertEqual(option
._short
_opts
, ["-f"])
1111 self
.assertEqual(option
._long
_opts
, ["--file"])
1112 self
.assertTrue(parser_
is self
.parser
)
1113 self
.assertEqual(value
, "foo")
1114 self
.assertEqual(vars(parser_
.values
), {'filename': None, 'x': 42})
1116 setattr(parser_
.values
, option
.dest
, value
)
1118 self
.fail("Unknown option %r in process_opt." % opt
)
1120 def test_callback(self
):
1121 self
.assertParseOK(["-x", "--file=foo"],
1122 {'filename': "foo", 'x': 42},
1125 def test_callback_help(self
):
1126 # This test was prompted by SF bug #960515 -- the point is
1127 # not to inspect the help text, just to make sure that
1128 # format_help() doesn't crash.
1129 parser
= OptionParser(usage
=SUPPRESS_USAGE
)
1130 parser
.remove_option("-h")
1131 parser
.add_option("-t", "--test", action
="callback",
1132 callback
=lambda: None, type="string",
1135 expected_help
= ("Options:\n"
1136 " -t TEST, --test=TEST foo\n")
1137 self
.assertHelp(parser
, expected_help
)
1140 class TestCallbackExtraArgs(BaseTest
):
1142 options
= [make_option("-p", "--point", action
="callback",
1143 callback
=self
.process_tuple
,
1144 callback_args
=(3, int), type="string",
1145 dest
="points", default
=[])]
1146 self
.parser
= OptionParser(option_list
=options
)
1148 def process_tuple(self
, option
, opt
, value
, parser_
, len, type):
1149 self
.assertEqual(len, 3)
1150 self
.assertTrue(type is int)
1153 self
.assertEqual(value
, "1,2,3")
1154 elif opt
== "--point":
1155 self
.assertEqual(value
, "4,5,6")
1157 value
= tuple(map(type, value
.split(",")))
1158 getattr(parser_
.values
, option
.dest
).append(value
)
1160 def test_callback_extra_args(self
):
1161 self
.assertParseOK(["-p1,2,3", "--point", "4,5,6"],
1162 {'points': [(1,2,3), (4,5,6)]},
1165 class TestCallbackMeddleArgs(BaseTest
):
1167 options
= [make_option(str(x
), action
="callback",
1168 callback
=self
.process_n
, dest
='things')
1169 for x
in range(-1, -6, -1)]
1170 self
.parser
= OptionParser(option_list
=options
)
1172 # Callback that meddles in rargs, largs
1173 def process_n(self
, option
, opt
, value
, parser_
):
1174 # option is -3, -5, etc.
1175 nargs
= int(opt
[1:])
1176 rargs
= parser_
.rargs
1177 if len(rargs
) < nargs
:
1178 self
.fail("Expected %d arguments for %s option." % (nargs
, opt
))
1179 dest
= parser_
.values
.ensure_value(option
.dest
, [])
1180 dest
.append(tuple(rargs
[0:nargs
]))
1181 parser_
.largs
.append(nargs
)
1184 def test_callback_meddle_args(self
):
1185 self
.assertParseOK(["-1", "foo", "-3", "bar", "baz", "qux"],
1186 {'things': [("foo",), ("bar", "baz", "qux")]},
1189 def test_callback_meddle_args_separator(self
):
1190 self
.assertParseOK(["-2", "foo", "--"],
1191 {'things': [('foo', '--')]},
1194 class TestCallbackManyArgs(BaseTest
):
1196 options
= [make_option("-a", "--apple", action
="callback", nargs
=2,
1197 callback
=self
.process_many
, type="string"),
1198 make_option("-b", "--bob", action
="callback", nargs
=3,
1199 callback
=self
.process_many
, type="int")]
1200 self
.parser
= OptionParser(option_list
=options
)
1202 def process_many(self
, option
, opt
, value
, parser_
):
1204 self
.assertEqual(value
, ("foo", "bar"))
1205 elif opt
== "--apple":
1206 self
.assertEqual(value
, ("ding", "dong"))
1208 self
.assertEqual(value
, (1, 2, 3))
1209 elif opt
== "--bob":
1210 self
.assertEqual(value
, (-666, 42, 0))
1212 def test_many_args(self
):
1213 self
.assertParseOK(["-a", "foo", "bar", "--apple", "ding", "dong",
1214 "-b", "1", "2", "3", "--bob", "-666", "42",
1216 {"apple": None, "bob": None},
1219 class TestCallbackCheckAbbrev(BaseTest
):
1221 self
.parser
= OptionParser()
1222 self
.parser
.add_option("--foo-bar", action
="callback",
1223 callback
=self
.check_abbrev
)
1225 def check_abbrev(self
, option
, opt
, value
, parser
):
1226 self
.assertEqual(opt
, "--foo-bar")
1228 def test_abbrev_callback_expansion(self
):
1229 self
.assertParseOK(["--foo"], {}, [])
1231 class TestCallbackVarArgs(BaseTest
):
1233 options
= [make_option("-a", type="int", nargs
=2, dest
="a"),
1234 make_option("-b", action
="store_true", dest
="b"),
1235 make_option("-c", "--callback", action
="callback",
1236 callback
=self
.variable_args
, dest
="c")]
1237 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
,
1238 option_list
=options
)
1240 def variable_args(self
, option
, opt
, value
, parser
):
1241 self
.assertTrue(value
is None)
1243 rargs
= parser
.rargs
1246 if ((arg
[:2] == "--" and len(arg
) > 2) or
1247 (arg
[:1] == "-" and len(arg
) > 1 and arg
[1] != "-")):
1252 setattr(parser
.values
, option
.dest
, value
)
1254 def test_variable_args(self
):
1255 self
.assertParseOK(["-a3", "-5", "--callback", "foo", "bar"],
1256 {'a': (3, -5), 'b': None, 'c': ["foo", "bar"]},
1259 def test_consume_separator_stop_at_option(self
):
1260 self
.assertParseOK(["-c", "37", "--", "xxx", "-b", "hello"],
1263 'c': ["37", "--", "xxx"]},
1266 def test_positional_arg_and_variable_args(self
):
1267 self
.assertParseOK(["hello", "-c", "foo", "-", "bar"],
1270 'c':["foo", "-", "bar"]},
1273 def test_stop_at_option(self
):
1274 self
.assertParseOK(["-c", "foo", "-b"],
1275 {'a': None, 'b': True, 'c': ["foo"]},
1278 def test_stop_at_invalid_option(self
):
1279 self
.assertParseFail(["-c", "3", "-5", "-a"], "no such option: -5")
1282 # -- Test conflict handling and parser.parse_args() --------------------
1284 class ConflictBase(BaseTest
):
1286 options
= [make_option("-v", "--verbose", action
="count",
1287 dest
="verbose", help="increment verbosity")]
1288 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
,
1289 option_list
=options
)
1291 def show_version(self
, option
, opt
, value
, parser
):
1292 parser
.values
.show_version
= 1
1294 class TestConflict(ConflictBase
):
1295 """Use the default conflict resolution for Optik 1.2: error."""
1296 def assertTrueconflict_error(self
, func
):
1297 err
= self
.assertRaises(
1298 func
, ("-v", "--version"), {'action' : "callback",
1299 'callback' : self
.show_version
,
1300 'help' : "show version"},
1301 OptionConflictError
,
1302 "option -v/--version: conflicting option string(s): -v")
1304 self
.assertEqual(err
.msg
, "conflicting option string(s): -v")
1305 self
.assertEqual(err
.option_id
, "-v/--version")
1307 def test_conflict_error(self
):
1308 self
.assertTrueconflict_error(self
.parser
.add_option
)
1310 def test_conflict_error_group(self
):
1311 group
= OptionGroup(self
.parser
, "Group 1")
1312 self
.assertTrueconflict_error(group
.add_option
)
1314 def test_no_such_conflict_handler(self
):
1316 self
.parser
.set_conflict_handler
, ('foo',), None,
1317 ValueError, "invalid conflict_resolution value 'foo'")
1320 class TestConflictResolve(ConflictBase
):
1322 ConflictBase
.setUp(self
)
1323 self
.parser
.set_conflict_handler("resolve")
1324 self
.parser
.add_option("-v", "--version", action
="callback",
1325 callback
=self
.show_version
, help="show version")
1327 def test_conflict_resolve(self
):
1328 v_opt
= self
.parser
.get_option("-v")
1329 verbose_opt
= self
.parser
.get_option("--verbose")
1330 version_opt
= self
.parser
.get_option("--version")
1332 self
.assertTrue(v_opt
is version_opt
)
1333 self
.assertTrue(v_opt
is not verbose_opt
)
1334 self
.assertEqual(v_opt
._long
_opts
, ["--version"])
1335 self
.assertEqual(version_opt
._short
_opts
, ["-v"])
1336 self
.assertEqual(version_opt
._long
_opts
, ["--version"])
1337 self
.assertEqual(verbose_opt
._short
_opts
, [])
1338 self
.assertEqual(verbose_opt
._long
_opts
, ["--verbose"])
1340 def test_conflict_resolve_help(self
):
1341 self
.assertOutput(["-h"], """\
1343 --verbose increment verbosity
1344 -h, --help show this help message and exit
1345 -v, --version show version
1348 def test_conflict_resolve_short_opt(self
):
1349 self
.assertParseOK(["-v"],
1350 {'verbose': None, 'show_version': 1},
1353 def test_conflict_resolve_long_opt(self
):
1354 self
.assertParseOK(["--verbose"],
1358 def test_conflict_resolve_long_opts(self
):
1359 self
.assertParseOK(["--verbose", "--version"],
1360 {'verbose': 1, 'show_version': 1},
1363 class TestConflictOverride(BaseTest
):
1365 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
)
1366 self
.parser
.set_conflict_handler("resolve")
1367 self
.parser
.add_option("-n", "--dry-run",
1368 action
="store_true", dest
="dry_run",
1369 help="don't do anything")
1370 self
.parser
.add_option("--dry-run", "-n",
1371 action
="store_const", const
=42, dest
="dry_run",
1372 help="dry run mode")
1374 def test_conflict_override_opts(self
):
1375 opt
= self
.parser
.get_option("--dry-run")
1376 self
.assertEqual(opt
._short
_opts
, ["-n"])
1377 self
.assertEqual(opt
._long
_opts
, ["--dry-run"])
1379 def test_conflict_override_help(self
):
1380 self
.assertOutput(["-h"], """\
1382 -h, --help show this help message and exit
1383 -n, --dry-run dry run mode
1386 def test_conflict_override_args(self
):
1387 self
.assertParseOK(["-n"],
1391 # -- Other testing. ----------------------------------------------------
1393 _expected_help_basic
= """\
1394 Usage: bar.py [options]
1397 -a APPLE throw APPLEs at basket
1398 -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the
1399 evil spirits that cause trouble and mayhem)
1400 --foo=FOO store FOO in the foo list for later fooing
1401 -h, --help show this help message and exit
1404 _expected_help_long_opts_first
= """\
1405 Usage: bar.py [options]
1408 -a APPLE throw APPLEs at basket
1409 --boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the
1410 evil spirits that cause trouble and mayhem)
1411 --foo=FOO store FOO in the foo list for later fooing
1412 --help, -h show this help message and exit
1415 _expected_help_title_formatter
= """\
1422 -a APPLE throw APPLEs at basket
1423 --boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the
1424 evil spirits that cause trouble and mayhem)
1425 --foo=FOO store FOO in the foo list for later fooing
1426 --help, -h show this help message and exit
1429 _expected_help_short_lines
= """\
1430 Usage: bar.py [options]
1433 -a APPLE throw APPLEs at basket
1434 -b NUM, --boo=NUM shout "boo!" NUM times (in order to
1435 frighten away all the evil spirits
1436 that cause trouble and mayhem)
1437 --foo=FOO store FOO in the foo list for later
1439 -h, --help show this help message and exit
1442 class TestHelp(BaseTest
):
1444 self
.parser
= self
.make_parser(80)
1446 def make_parser(self
, columns
):
1448 make_option("-a", type="string", dest
='a',
1449 metavar
="APPLE", help="throw APPLEs at basket"),
1450 make_option("-b", "--boo", type="int", dest
='boo',
1453 "shout \"boo!\" NUM times (in order to frighten away "
1454 "all the evil spirits that cause trouble and mayhem)"),
1455 make_option("--foo", action
="append", type="string", dest
='foo',
1456 help="store FOO in the foo list for later fooing"),
1459 # We need to set COLUMNS for the OptionParser constructor, but
1460 # we must restore its original value -- otherwise, this test
1461 # screws things up for other tests when it's part of the Python
1463 with test_support
.EnvironmentVarGuard() as env
:
1464 env
['COLUMNS'] = str(columns
)
1465 return InterceptingOptionParser(option_list
=options
)
1467 def assertHelpEquals(self
, expected_output
):
1468 if type(expected_output
) is types
.UnicodeType
:
1469 encoding
= self
.parser
._get
_encoding
(sys
.stdout
)
1470 expected_output
= expected_output
.encode(encoding
, "replace")
1472 save_argv
= sys
.argv
[:]
1474 # Make optparse believe bar.py is being executed.
1475 sys
.argv
[0] = os
.path
.join("foo", "bar.py")
1476 self
.assertOutput(["-h"], expected_output
)
1478 sys
.argv
[:] = save_argv
1480 def test_help(self
):
1481 self
.assertHelpEquals(_expected_help_basic
)
1483 def test_help_old_usage(self
):
1484 self
.parser
.set_usage("Usage: %prog [options]")
1485 self
.assertHelpEquals(_expected_help_basic
)
1487 def test_help_long_opts_first(self
):
1488 self
.parser
.formatter
.short_first
= 0
1489 self
.assertHelpEquals(_expected_help_long_opts_first
)
1491 def test_help_title_formatter(self
):
1492 with test_support
.EnvironmentVarGuard() as env
:
1493 env
["COLUMNS"] = "80"
1494 self
.parser
.formatter
= TitledHelpFormatter()
1495 self
.assertHelpEquals(_expected_help_title_formatter
)
1497 def test_wrap_columns(self
):
1498 # Ensure that wrapping respects $COLUMNS environment variable.
1499 # Need to reconstruct the parser, since that's the only time
1500 # we look at $COLUMNS.
1501 self
.parser
= self
.make_parser(60)
1502 self
.assertHelpEquals(_expected_help_short_lines
)
1504 def test_help_unicode(self
):
1505 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
)
1506 self
.parser
.add_option("-a", action
="store_true", help=u
"ol\u00E9!")
1509 -h, --help show this help message and exit
1512 self
.assertHelpEquals(expect
)
1514 def test_help_unicode_description(self
):
1515 self
.parser
= InterceptingOptionParser(usage
=SUPPRESS_USAGE
,
1516 description
=u
"ol\u00E9!")
1521 -h, --help show this help message and exit
1523 self
.assertHelpEquals(expect
)
1525 def test_help_description_groups(self
):
1526 self
.parser
.set_description(
1527 "This is the program description for %prog. %prog has "
1528 "an option group as well as single options.")
1530 group
= OptionGroup(
1531 self
.parser
, "Dangerous Options",
1532 "Caution: use of these options is at your own risk. "
1533 "It is believed that some of them bite.")
1534 group
.add_option("-g", action
="store_true", help="Group option.")
1535 self
.parser
.add_option_group(group
)
1538 Usage: bar.py [options]
1540 This is the program description for bar.py. bar.py has an option group as
1541 well as single options.
1544 -a APPLE throw APPLEs at basket
1545 -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the
1546 evil spirits that cause trouble and mayhem)
1547 --foo=FOO store FOO in the foo list for later fooing
1548 -h, --help show this help message and exit
1551 Caution: use of these options is at your own risk. It is believed
1552 that some of them bite.
1557 self
.assertHelpEquals(expect
)
1559 self
.parser
.epilog
= "Please report bugs to /dev/null."
1560 self
.assertHelpEquals(expect
+ "\nPlease report bugs to /dev/null.\n")
1563 class TestMatchAbbrev(BaseTest
):
1564 def test_match_abbrev(self
):
1565 self
.assertEqual(_match_abbrev("--f",
1572 def test_match_abbrev_error(self
):
1574 wordmap
= {"--foz": None, "--foo": None, "--fie": None}
1576 _match_abbrev
, (s
, wordmap
), None,
1577 BadOptionError
, "ambiguous option: --f (--fie, --foo, --foz?)")
1580 class TestParseNumber(BaseTest
):
1582 self
.parser
= InterceptingOptionParser()
1583 self
.parser
.add_option("-n", type=int)
1584 self
.parser
.add_option("-l", type=long)
1586 def test_parse_num_fail(self
):
1588 _parse_num
, ("", int), {},
1590 re
.compile(r
"invalid literal for int().*: '?'?"))
1592 _parse_num
, ("0xOoops", long), {},
1594 re
.compile(r
"invalid literal for long().*: '?0xOoops'?"))
1596 def test_parse_num_ok(self
):
1597 self
.assertEqual(_parse_num("0", int), 0)
1598 self
.assertEqual(_parse_num("0x10", int), 16)
1599 self
.assertEqual(_parse_num("0XA", long), 10L)
1600 self
.assertEqual(_parse_num("010", long), 8L)
1601 self
.assertEqual(_parse_num("0b11", int), 3)
1602 self
.assertEqual(_parse_num("0b", long), 0L)
1604 def test_numeric_options(self
):
1605 self
.assertParseOK(["-n", "42", "-l", "0x20"],
1606 { "n": 42, "l": 0x20 }, [])
1607 self
.assertParseOK(["-n", "0b0101", "-l010"],
1608 { "n": 5, "l": 8 }, [])
1609 self
.assertParseFail(["-n008"],
1610 "option -n: invalid integer value: '008'")
1611 self
.assertParseFail(["-l0b0123"],
1612 "option -l: invalid long integer value: '0b0123'")
1613 self
.assertParseFail(["-l", "0x12x"],
1614 "option -l: invalid long integer value: '0x12x'")
1618 test_support
.run_unittest(__name__
)
1620 if __name__
== '__main__':