test_optparse.py 59.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
#
# Test suite for Optik.  Supplied by Johannes Gijsbers
# (taradino@softhome.net) -- translated from the original Optik
# test suite to this PyUnit-based version.
#
# $Id$
#

import sys
import os
11
import re
12 13 14
import copy
import unittest

15
from io import StringIO
16
from test import support
17

18

19 20 21
from optparse import make_option, Option, \
     TitledHelpFormatter, OptionParser, OptionGroup, \
     SUPPRESS_USAGE, OptionError, OptionConflictError, \
22 23 24
     BadOptionError, OptionValueError, Values
from optparse import _match_abbrev
from optparse import _parse_num
25

26
retype = type(re.compile(''))
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

class InterceptedError(Exception):
    def __init__(self,
                 error_message=None,
                 exit_status=None,
                 exit_message=None):
        self.error_message = error_message
        self.exit_status = exit_status
        self.exit_message = exit_message

    def __str__(self):
        return self.error_message or self.exit_message or "intercepted error"

class InterceptingOptionParser(OptionParser):
    def exit(self, status=0, msg=None):
        raise InterceptedError(exit_status=status, exit_message=msg)

    def error(self, msg):
        raise InterceptedError(error_message=msg)

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

class BaseTest(unittest.TestCase):
    def assertParseOK(self, args, expected_opts, expected_positional_args):
        """Assert the options are what we expected when parsing arguments.

        Otherwise, fail with a nicely formatted message.

        Keyword arguments:
        args -- A list of arguments to parse with OptionParser.
        expected_opts -- The options expected.
        expected_positional_args -- The positional arguments expected.

        Returns the options and positional args for further testing.
        """

        (options, positional_args) = self.parser.parse_args(args)
        optdict = vars(options)

        self.assertEqual(optdict, expected_opts,
                         """
Options are %(optdict)s.
Should be %(expected_opts)s.
Args were %(args)s.""" % locals())

        self.assertEqual(positional_args, expected_positional_args,
                         """
Positional arguments are %(positional_args)s.
Should be %(expected_positional_args)s.
Args were %(args)s.""" % locals ())

        return (options, positional_args)

79 80 81 82 83
    def assertRaises(self,
                     func,
                     args,
                     kwargs,
                     expected_exception,
84 85 86 87 88
                     expected_message):
        """
        Assert that the expected exception is raised when calling a
        function, and that the right error message is included with
        that exception.
89

90 91 92 93 94
        Arguments:
          func -- the function to call
          args -- positional arguments to `func`
          kwargs -- keyword arguments to `func`
          expected_exception -- exception that should be raised
95 96
          expected_message -- expected exception message (or pattern
            if a compiled regex object)
97 98 99

        Returns the exception raised for further testing.
        """
100 101 102 103
        if args is None:
            args = ()
        if kwargs is None:
            kwargs = {}
104 105

        try:
106
            func(*args, **kwargs)
107
        except expected_exception as err:
108
            actual_message = str(err)
109
            if isinstance(expected_message, retype):
110
                self.assertTrue(expected_message.search(actual_message),
111
                             """\
112 113 114 115 116 117 118 119 120
expected exception message pattern:
/%s/
actual exception message:
'''%s'''
""" % (expected_message.pattern, actual_message))
            else:
                self.assertEqual(actual_message,
                                 expected_message,
                                 """\
121
expected exception message:
122
'''%s'''
123
actual exception message:
124 125
'''%s'''
""" % (expected_message, actual_message))
126 127 128

            return err
        else:
129 130 131 132 133
            self.fail("""expected exception %(expected_exception)s not raised
called %(func)r
with args %(args)r
and kwargs %(kwargs)r
""" % locals ())
134

135

136 137 138
    # -- Assertions used in more than one class --------------------

    def assertParseFail(self, cmdline_args, expected_output):
139 140 141 142
        """
        Assert the parser fails with the expected message.  Caller
        must ensure that self.parser is an InterceptingOptionParser.
        """
143
        try:
144
            self.parser.parse_args(cmdline_args)
145
        except InterceptedError as err:
146 147 148
            self.assertEqual(err.error_message, expected_output)
        else:
            self.assertFalse("expected parse failure")
149

150 151 152 153 154
    def assertOutput(self,
                     cmdline_args,
                     expected_output,
                     expected_status=0,
                     expected_error=None):
155
        """Assert the parser prints the expected output on stdout."""
156 157
        save_stdout = sys.stdout
        try:
158 159 160 161 162 163 164
            try:
                sys.stdout = StringIO()
                self.parser.parse_args(cmdline_args)
            finally:
                output = sys.stdout.getvalue()
                sys.stdout = save_stdout

165
        except InterceptedError as err:
166
            self.assertTrue(
167
                isinstance(output, str),
168 169 170
                "expected output to be an ordinary string, not %r"
                % type(output))

171 172 173
            if output != expected_output:
                self.fail("expected: \n'''\n" + expected_output +
                          "'''\nbut got \n'''\n" + output + "'''")
174 175 176 177
            self.assertEqual(err.exit_status, expected_status)
            self.assertEqual(err.exit_message, expected_error)
        else:
            self.assertFalse("expected parser.exit()")
178

179 180 181
    def assertTypeError(self, func, expected_message, *args):
        """Assert that TypeError is raised when executing func."""
        self.assertRaises(func, args, None, TypeError, expected_message)
182 183 184 185 186 187 188 189

    def assertHelp(self, parser, expected_help):
        actual_help = parser.format_help()
        if actual_help != expected_help:
            raise self.failureException(
                'help text failure; expected:\n"' +
                expected_help + '"; got:\n"' +
                actual_help + '"\n')
190 191 192

# -- Test make_option() aka Option -------------------------------------

193
# It's not necessary to test correct options here.  All the tests in the
194
# parser.parse_args() section deal with those, because they're needed
195
# there.
196 197 198 199 200

class TestOptionChecks(BaseTest):
    def setUp(self):
        self.parser = OptionParser(usage=SUPPRESS_USAGE)

201
    def assertOptionError(self, expected_message, args=[], kwargs={}):
202
        self.assertRaises(make_option, args, kwargs,
203
                          OptionError, expected_message)
204 205 206 207 208 209

    def test_opt_string_empty(self):
        self.assertTypeError(make_option,
                             "at least one option string must be supplied")

    def test_opt_string_too_short(self):
210 211 212
        self.assertOptionError(
            "invalid option string 'b': must be at least two characters long",
            ["b"])
213 214

    def test_opt_string_short_invalid(self):
215 216 217 218
        self.assertOptionError(
            "invalid short option string '--': must be "
            "of the form -x, (x any non-dash char)",
            ["--"])
219 220

    def test_opt_string_long_invalid(self):
221 222 223 224
        self.assertOptionError(
            "invalid long option string '---': "
            "must start with --, followed by non-dash",
            ["---"])
225 226

    def test_attr_invalid(self):
227
        self.assertOptionError(
228
            "option -b: invalid keyword arguments: bar, foo",
229
            ["-b"], {'foo': None, 'bar': None})
230 231

    def test_action_invalid(self):
232 233 234
        self.assertOptionError(
            "option -b: invalid action: 'foo'",
            ["-b"], {'action': 'foo'})
235 236

    def test_type_invalid(self):
237 238 239 240 241 242
        self.assertOptionError(
            "option -b: invalid option type: 'foo'",
            ["-b"], {'type': 'foo'})
        self.assertOptionError(
            "option -b: invalid option type: 'tuple'",
            ["-b"], {'type': tuple})
243 244

    def test_no_type_for_action(self):
245 246 247
        self.assertOptionError(
            "option -b: must not supply a type for action 'count'",
            ["-b"], {'action': 'count', 'type': 'int'})
248 249

    def test_no_choices_list(self):
250 251 252 253
        self.assertOptionError(
            "option -b/--bad: must supply a list of "
            "choices for type 'choice'",
            ["-b", "--bad"], {'type': "choice"})
254 255 256

    def test_bad_choices_list(self):
        typename = type('').__name__
257 258 259 260 261
        self.assertOptionError(
            "option -b/--bad: choices must be a list of "
            "strings ('%s' supplied)" % typename,
            ["-b", "--bad"],
            {'type': "choice", 'choices':"bad choices"})
262 263

    def test_no_choices_for_type(self):
264 265 266
        self.assertOptionError(
            "option -b: must not supply choices for type 'int'",
            ["-b"], {'type': 'int', 'choices':"bad"})
267 268

    def test_no_const_for_action(self):
269 270 271
        self.assertOptionError(
            "option -b: 'const' must not be supplied for action 'store'",
            ["-b"], {'action': 'store', 'const': 1})
272 273

    def test_no_nargs_for_action(self):
274 275 276
        self.assertOptionError(
            "option -b: 'nargs' must not be supplied for action 'count'",
            ["-b"], {'action': 'count', 'nargs': 2})
277 278

    def test_callback_not_callable(self):
279 280 281 282
        self.assertOptionError(
            "option -b: callback not callable: 'foo'",
            ["-b"], {'action': 'callback',
                     'callback': 'foo'})
283 284 285 286 287

    def dummy(self):
        pass

    def test_callback_args_no_tuple(self):
288 289 290 291 292 293
        self.assertOptionError(
            "option -b: callback_args, if supplied, "
            "must be a tuple: not 'foo'",
            ["-b"], {'action': 'callback',
                     'callback': self.dummy,
                     'callback_args': 'foo'})
294 295

    def test_callback_kwargs_no_dict(self):
296 297 298 299 300 301
        self.assertOptionError(
            "option -b: callback_kwargs, if supplied, "
            "must be a dict: not 'foo'",
            ["-b"], {'action': 'callback',
                     'callback': self.dummy,
                     'callback_kwargs': 'foo'})
302 303

    def test_no_callback_for_action(self):
304 305 306 307
        self.assertOptionError(
            "option -b: callback supplied ('foo') for non-callback option",
            ["-b"], {'action': 'store',
                     'callback': 'foo'})
308 309

    def test_no_callback_args_for_action(self):
310 311 312 313
        self.assertOptionError(
            "option -b: callback_args supplied for non-callback option",
            ["-b"], {'action': 'store',
                     'callback_args': 'foo'})
314 315

    def test_no_callback_kwargs_for_action(self):
316 317 318 319
        self.assertOptionError(
            "option -b: callback_kwargs supplied for non-callback option",
            ["-b"], {'action': 'store',
                     'callback_kwargs': 'foo'})
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338

class TestOptionParser(BaseTest):
    def setUp(self):
        self.parser = OptionParser()
        self.parser.add_option("-v", "--verbose", "-n", "--noisy",
                          action="store_true", dest="verbose")
        self.parser.add_option("-q", "--quiet", "--silent",
                          action="store_false", dest="verbose")

    def test_add_option_no_Option(self):
        self.assertTypeError(self.parser.add_option,
                             "not an Option instance: None", None)

    def test_add_option_invalid_arguments(self):
        self.assertTypeError(self.parser.add_option,
                             "invalid arguments", None, None)

    def test_get_option(self):
        opt1 = self.parser.get_option("-v")
339
        self.assertIsInstance(opt1, Option)
340 341 342 343 344 345 346 347 348 349
        self.assertEqual(opt1._short_opts, ["-v", "-n"])
        self.assertEqual(opt1._long_opts, ["--verbose", "--noisy"])
        self.assertEqual(opt1.action, "store_true")
        self.assertEqual(opt1.dest, "verbose")

    def test_get_option_equals(self):
        opt1 = self.parser.get_option("-v")
        opt2 = self.parser.get_option("--verbose")
        opt3 = self.parser.get_option("-n")
        opt4 = self.parser.get_option("--noisy")
350
        self.assertTrue(opt1 is opt2 is opt3 is opt4)
351 352

    def test_has_option(self):
353 354
        self.assertTrue(self.parser.has_option("-v"))
        self.assertTrue(self.parser.has_option("--verbose"))
355

356 357 358 359 360
    def assertTrueremoved(self):
        self.assertTrue(self.parser.get_option("-v") is None)
        self.assertTrue(self.parser.get_option("--verbose") is None)
        self.assertTrue(self.parser.get_option("-n") is None)
        self.assertTrue(self.parser.get_option("--noisy") is None)
361

362 363 364 365
        self.assertFalse(self.parser.has_option("-v"))
        self.assertFalse(self.parser.has_option("--verbose"))
        self.assertFalse(self.parser.has_option("-n"))
        self.assertFalse(self.parser.has_option("--noisy"))
366

367 368
        self.assertTrue(self.parser.has_option("-q"))
        self.assertTrue(self.parser.has_option("--silent"))
369 370 371

    def test_remove_short_opt(self):
        self.parser.remove_option("-n")
372
        self.assertTrueremoved()
373 374 375

    def test_remove_long_opt(self):
        self.parser.remove_option("--verbose")
376
        self.assertTrueremoved()
377 378

    def test_remove_nonexistent(self):
379 380 381
        self.assertRaises(self.parser.remove_option, ('foo',), None,
                          ValueError, "no such option 'foo'")

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    def test_refleak(self):
        # If an OptionParser is carrying around a reference to a large
        # object, various cycles can prevent it from being GC'd in
        # a timely fashion.  destroy() breaks the cycles to ensure stuff
        # can be cleaned up.
        big_thing = [42]
        refcount = sys.getrefcount(big_thing)
        parser = OptionParser()
        parser.add_option("-a", "--aaarggh")
        parser.big_thing = big_thing

        parser.destroy()
        #self.assertEqual(refcount, sys.getrefcount(big_thing))
        del parser
        self.assertEqual(refcount, sys.getrefcount(big_thing))


399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
class TestOptionValues(BaseTest):
    def setUp(self):
        pass

    def test_basics(self):
        values = Values()
        self.assertEqual(vars(values), {})
        self.assertEqual(values, {})
        self.assertNotEqual(values, {"foo": "bar"})
        self.assertNotEqual(values, "")

        dict = {"foo": "bar", "baz": 42}
        values = Values(defaults=dict)
        self.assertEqual(vars(values), dict)
        self.assertEqual(values, dict)
        self.assertNotEqual(values, {"foo": "bar"})
        self.assertNotEqual(values, {})
        self.assertNotEqual(values, "")
        self.assertNotEqual(values, [])


420 421 422 423
class TestTypeAliases(BaseTest):
    def setUp(self):
        self.parser = OptionParser()

424 425
    def test_str_aliases_string(self):
        self.parser.add_option("-s", type="str")
426
        self.assertEqual(self.parser.get_option("-s").type, "string")
427

428
    def test_type_object(self):
429
        self.parser.add_option("-s", type=str)
430
        self.assertEqual(self.parser.get_option("-s").type, "string")
431
        self.parser.add_option("-x", type=int)
432
        self.assertEqual(self.parser.get_option("-x").type, "int")
433

434 435 436 437 438 439 440 441 442 443

# Custom type for testing processing of default values.
_time_units = { 's' : 1, 'm' : 60, 'h' : 60*60, 'd' : 60*60*24 }

def _check_duration(option, opt, value):
    try:
        if value[-1].isdigit():
            return int(value)
        else:
            return int(value[:-1]) * _time_units[value[-1]]
Georg Brandl's avatar
Georg Brandl committed
444
    except (ValueError, IndexError):
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
        raise OptionValueError(
            'option %s: invalid duration: %r' % (opt, value))

class DurationOption(Option):
    TYPES = Option.TYPES + ('duration',)
    TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
    TYPE_CHECKER['duration'] = _check_duration

class TestDefaultValues(BaseTest):
    def setUp(self):
        self.parser = OptionParser()
        self.parser.add_option("-v", "--verbose", default=True)
        self.parser.add_option("-q", "--quiet", dest='verbose')
        self.parser.add_option("-n", type="int", default=37)
        self.parser.add_option("-m", type="int")
        self.parser.add_option("-s", default="foo")
        self.parser.add_option("-t")
        self.parser.add_option("-u", default=None)
        self.expected = { 'verbose': True,
                          'n': 37,
                          'm': None,
                          's': "foo",
                          't': None,
                          'u': None }

    def test_basic_defaults(self):
        self.assertEqual(self.parser.get_default_values(), self.expected)

    def test_mixed_defaults_post(self):
        self.parser.set_defaults(n=42, m=-100)
        self.expected.update({'n': 42, 'm': -100})
        self.assertEqual(self.parser.get_default_values(), self.expected)

    def test_mixed_defaults_pre(self):
        self.parser.set_defaults(x="barf", y="blah")
        self.parser.add_option("-x", default="frob")
        self.parser.add_option("-y")

        self.expected.update({'x': "frob", 'y': "blah"})
        self.assertEqual(self.parser.get_default_values(), self.expected)

        self.parser.remove_option("-y")
        self.parser.add_option("-y", default=None)
        self.expected.update({'y': None})
        self.assertEqual(self.parser.get_default_values(), self.expected)

    def test_process_default(self):
        self.parser.option_class = DurationOption
        self.parser.add_option("-d", type="duration", default=300)
        self.parser.add_option("-e", type="duration", default="6m")
        self.parser.set_defaults(n="42")
        self.expected.update({'d': 300, 'e': 360, 'n': 42})
        self.assertEqual(self.parser.get_default_values(), self.expected)

        self.parser.set_process_default_values(False)
        self.expected.update({'d': 300, 'e': "6m", 'n': "42"})
        self.assertEqual(self.parser.get_default_values(), self.expected)


class TestProgName(BaseTest):
    """
    Test that %prog expands to the right thing in usage, version,
    and help strings.
    """

    def assertUsage(self, parser, expected_usage):
        self.assertEqual(parser.get_usage(), expected_usage)

    def assertVersion(self, parser, expected_version):
        self.assertEqual(parser.get_version(), expected_version)


    def test_default_progname(self):
        # Make sure that program name taken from sys.argv[0] by default.
519 520
        save_argv = sys.argv[:]
        try:
521
            sys.argv[0] = os.path.join("foo", "bar", "baz.py")
522 523
            parser = OptionParser("%prog ...", version="%prog 1.2")
            expected_usage = "Usage: baz.py ...\n"
524 525 526
            self.assertUsage(parser, expected_usage)
            self.assertVersion(parser, "baz.py 1.2")
            self.assertHelp(parser,
527
                            expected_usage + "\n" +
528
                            "Options:\n"
529 530
                            "  --version   show program's version number and exit\n"
                            "  -h, --help  show this help message and exit\n")
531 532
        finally:
            sys.argv[:] = save_argv
533 534 535 536 537 538 539

    def test_custom_progname(self):
        parser = OptionParser(prog="thingy",
                              version="%prog 0.1",
                              usage="%prog arg arg")
        parser.remove_option("-h")
        parser.remove_option("--version")
540
        expected_usage = "Usage: thingy arg arg\n"
541 542 543 544 545 546 547 548 549
        self.assertUsage(parser, expected_usage)
        self.assertVersion(parser, "thingy 0.1")
        self.assertHelp(parser, expected_usage + "\n")


class TestExpandDefaults(BaseTest):
    def setUp(self):
        self.parser = OptionParser(prog="test")
        self.help_prefix = """\
550
Usage: test [options]
551

552
Options:
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
  -h, --help            show this help message and exit
"""
        self.file_help = "read from FILE [default: %default]"
        self.expected_help_file = self.help_prefix + \
            "  -f FILE, --file=FILE  read from FILE [default: foo.txt]\n"
        self.expected_help_none = self.help_prefix + \
            "  -f FILE, --file=FILE  read from FILE [default: none]\n"

    def test_option_default(self):
        self.parser.add_option("-f", "--file",
                               default="foo.txt",
                               help=self.file_help)
        self.assertHelp(self.parser, self.expected_help_file)

    def test_parser_default_1(self):
        self.parser.add_option("-f", "--file",
                               help=self.file_help)
        self.parser.set_default('file', "foo.txt")
        self.assertHelp(self.parser, self.expected_help_file)

    def test_parser_default_2(self):
        self.parser.add_option("-f", "--file",
                               help=self.file_help)
        self.parser.set_defaults(file="foo.txt")
        self.assertHelp(self.parser, self.expected_help_file)

    def test_no_default(self):
        self.parser.add_option("-f", "--file",
                               help=self.file_help)
        self.assertHelp(self.parser, self.expected_help_none)

    def test_default_none_1(self):
        self.parser.add_option("-f", "--file",
                               default=None,
                               help=self.file_help)
        self.assertHelp(self.parser, self.expected_help_none)
Tim Peters's avatar
Tim Peters committed
589

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
    def test_default_none_2(self):
        self.parser.add_option("-f", "--file",
                               help=self.file_help)
        self.parser.set_defaults(file=None)
        self.assertHelp(self.parser, self.expected_help_none)

    def test_float_default(self):
        self.parser.add_option(
            "-p", "--prob",
            help="blow up with probability PROB [default: %default]")
        self.parser.set_defaults(prob=0.43)
        expected_help = self.help_prefix + \
            "  -p PROB, --prob=PROB  blow up with probability PROB [default: 0.43]\n"
        self.assertHelp(self.parser, expected_help)

    def test_alt_expand(self):
        self.parser.add_option("-f", "--file",
                               default="foo.txt",
                               help="read from FILE [default: *DEFAULT*]")
        self.parser.formatter.default_tag = "*DEFAULT*"
        self.assertHelp(self.parser, self.expected_help_file)

    def test_no_expand(self):
        self.parser.add_option("-f", "--file",
                               default="foo.txt",
                               help="read from %default file")
        self.parser.formatter.default_tag = None
        expected_help = self.help_prefix + \
            "  -f FILE, --file=FILE  read from %default file\n"
        self.assertHelp(self.parser, expected_help)

621 622 623 624 625 626 627 628 629

# -- Test parser.parse_args() ------------------------------------------

class TestStandard(BaseTest):
    def setUp(self):
        options = [make_option("-a", type="string"),
                   make_option("-b", "--boo", type="int", dest='boo'),
                   make_option("--foo", action="append")]

630 631
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
                                               option_list=options)
632 633

    def test_required_value(self):
634
        self.assertParseFail(["-a"], "-a option requires an argument")
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710

    def test_invalid_integer(self):
        self.assertParseFail(["-b", "5x"],
                             "option -b: invalid integer value: '5x'")

    def test_no_such_option(self):
        self.assertParseFail(["--boo13"], "no such option: --boo13")

    def test_long_invalid_integer(self):
        self.assertParseFail(["--boo=x5"],
                             "option --boo: invalid integer value: 'x5'")

    def test_empty(self):
        self.assertParseOK([], {'a': None, 'boo': None, 'foo': None}, [])

    def test_shortopt_empty_longopt_append(self):
        self.assertParseOK(["-a", "", "--foo=blah", "--foo="],
                           {'a': "", 'boo': None, 'foo': ["blah", ""]},
                           [])

    def test_long_option_append(self):
        self.assertParseOK(["--foo", "bar", "--foo", "", "--foo=x"],
                           {'a': None,
                            'boo': None,
                            'foo': ["bar", "", "x"]},
                           [])

    def test_option_argument_joined(self):
        self.assertParseOK(["-abc"],
                           {'a': "bc", 'boo': None, 'foo': None},
                           [])

    def test_option_argument_split(self):
        self.assertParseOK(["-a", "34"],
                           {'a': "34", 'boo': None, 'foo': None},
                           [])

    def test_option_argument_joined_integer(self):
        self.assertParseOK(["-b34"],
                           {'a': None, 'boo': 34, 'foo': None},
                           [])

    def test_option_argument_split_negative_integer(self):
        self.assertParseOK(["-b", "-5"],
                           {'a': None, 'boo': -5, 'foo': None},
                           [])

    def test_long_option_argument_joined(self):
        self.assertParseOK(["--boo=13"],
                           {'a': None, 'boo': 13, 'foo': None},
                           [])

    def test_long_option_argument_split(self):
        self.assertParseOK(["--boo", "111"],
                           {'a': None, 'boo': 111, 'foo': None},
                           [])

    def test_long_option_short_option(self):
        self.assertParseOK(["--foo=bar", "-axyz"],
                           {'a': 'xyz', 'boo': None, 'foo': ["bar"]},
                           [])

    def test_abbrev_long_option(self):
        self.assertParseOK(["--f=bar", "-axyz"],
                           {'a': 'xyz', 'boo': None, 'foo': ["bar"]},
                           [])

    def test_defaults(self):
        (options, args) = self.parser.parse_args([])
        defaults = self.parser.get_default_values()
        self.assertEqual(vars(defaults), vars(options))

    def test_ambiguous_option(self):
        self.parser.add_option("--foz", action="store",
                               type="string", dest="foo")
        self.assertParseFail(["--f=bar"],
711
                             "ambiguous option: --f (--foo, --foz?)")
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732


    def test_short_and_long_option_split(self):
        self.assertParseOK(["-a", "xyz", "--foo", "bar"],
                           {'a': 'xyz', 'boo': None, 'foo': ["bar"]},
                           []),

    def test_short_option_split_long_option_append(self):
        self.assertParseOK(["--foo=bar", "-b", "123", "--foo", "baz"],
                           {'a': None, 'boo': 123, 'foo': ["bar", "baz"]},
                           [])

    def test_short_option_split_one_positional_arg(self):
        self.assertParseOK(["-a", "foo", "bar"],
                           {'a': "foo", 'boo': None, 'foo': None},
                           ["bar"]),

    def test_short_option_consumes_separator(self):
        self.assertParseOK(["-a", "--", "foo", "bar"],
                           {'a': "--", 'boo': None, 'foo': None},
                           ["foo", "bar"]),
733 734 735
        self.assertParseOK(["-a", "--", "--foo", "bar"],
                           {'a': "--", 'boo': None, 'foo': ["bar"]},
                           []),
736 737 738 739 740 741

    def test_short_option_joined_and_separator(self):
        self.assertParseOK(["-ab", "--", "--foo", "bar"],
                           {'a': "b", 'boo': None, 'foo': None},
                           ["--foo", "bar"]),

742
    def test_hyphen_becomes_positional_arg(self):
743 744 745 746 747 748 749 750 751 752 753 754 755 756
        self.assertParseOK(["-ab", "-", "--foo", "bar"],
                           {'a': "b", 'boo': None, 'foo': ["bar"]},
                           ["-"])

    def test_no_append_versus_append(self):
        self.assertParseOK(["-b3", "-b", "5", "--foo=bar", "--foo", "baz"],
                           {'a': None, 'boo': 5, 'foo': ["bar", "baz"]},
                           [])

    def test_option_consumes_optionlike_string(self):
        self.assertParseOK(["-a", "-b3"],
                           {'a': "-b3", 'boo': None, 'foo': None},
                           [])

757 758 759
    def test_combined_single_invalid_option(self):
        self.parser.add_option("-t", action="store_true")
        self.assertParseFail(["-test"],
760
                             "no such option: -e")
761

762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
class TestBool(BaseTest):
    def setUp(self):
        options = [make_option("-v",
                               "--verbose",
                               action="store_true",
                               dest="verbose",
                               default=''),
                   make_option("-q",
                               "--quiet",
                               action="store_false",
                               dest="verbose")]
        self.parser = OptionParser(option_list = options)

    def test_bool_default(self):
        self.assertParseOK([],
                           {'verbose': ''},
                           [])

    def test_bool_false(self):
        (options, args) = self.assertParseOK(["-q"],
                                             {'verbose': 0},
                                             [])
784
        self.assertTrue(options.verbose is False)
785 786 787 788 789

    def test_bool_true(self):
        (options, args) = self.assertParseOK(["-v"],
                                             {'verbose': 1},
                                             [])
790
        self.assertTrue(options.verbose is True)
791 792 793 794 795 796 797 798

    def test_bool_flicker_on_and_off(self):
        self.assertParseOK(["-qvq", "-q", "-v"],
                           {'verbose': 1},
                           [])

class TestChoice(BaseTest):
    def setUp(self):
799
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
        self.parser.add_option("-c", action="store", type="choice",
                               dest="choice", choices=["one", "two", "three"])

    def test_valid_choice(self):
        self.assertParseOK(["-c", "one", "xyz"],
                           {'choice': 'one'},
                           ["xyz"])

    def test_invalid_choice(self):
        self.assertParseFail(["-c", "four", "abc"],
                             "option -c: invalid choice: 'four' "
                             "(choose from 'one', 'two', 'three')")

    def test_add_choice_option(self):
        self.parser.add_option("-d", "--default",
                               choices=["four", "five", "six"])
        opt = self.parser.get_option("-d")
        self.assertEqual(opt.type, "choice")
        self.assertEqual(opt.action, "store")

class TestCount(BaseTest):
    def setUp(self):
822
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
        self.v_opt = make_option("-v", action="count", dest="verbose")
        self.parser.add_option(self.v_opt)
        self.parser.add_option("--verbose", type="int", dest="verbose")
        self.parser.add_option("-q", "--quiet",
                               action="store_const", dest="verbose", const=0)

    def test_empty(self):
        self.assertParseOK([], {'verbose': None}, [])

    def test_count_one(self):
        self.assertParseOK(["-v"], {'verbose': 1}, [])

    def test_count_three(self):
        self.assertParseOK(["-vvv"], {'verbose': 3}, [])

    def test_count_three_apart(self):
        self.assertParseOK(["-v", "-v", "-v"], {'verbose': 3}, [])

    def test_count_override_amount(self):
        self.assertParseOK(["-vvv", "--verbose=2"], {'verbose': 2}, [])

    def test_count_override_quiet(self):
        self.assertParseOK(["-vvv", "--verbose=2", "-q"], {'verbose': 0}, [])

    def test_count_overriding(self):
        self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"],
                           {'verbose': 1}, [])

    def test_count_interspersed_args(self):
        self.assertParseOK(["--quiet", "3", "-v"],
                           {'verbose': 1},
                           ["3"])

    def test_count_no_interspersed_args(self):
        self.parser.disable_interspersed_args()
        self.assertParseOK(["--quiet", "3", "-v"],
                           {'verbose': 0},
                           ["3", "-v"])

    def test_count_no_such_option(self):
        self.assertParseFail(["-q3", "-v"], "no such option: -3")

    def test_count_option_no_value(self):
        self.assertParseFail(["--quiet=3", "-v"],
                             "--quiet option does not take a value")

    def test_count_with_default(self):
        self.parser.set_default('verbose', 0)
        self.assertParseOK([], {'verbose':0}, [])

    def test_count_overriding_default(self):
        self.parser.set_default('verbose', 0)
        self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"],
                           {'verbose': 1}, [])

878
class TestMultipleArgs(BaseTest):
879
    def setUp(self):
880
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
        self.parser.add_option("-p", "--point",
                               action="store", nargs=3, type="float", dest="point")

    def test_nargs_with_positional_args(self):
        self.assertParseOK(["foo", "-p", "1", "2.5", "-4.3", "xyz"],
                           {'point': (1.0, 2.5, -4.3)},
                           ["foo", "xyz"])

    def test_nargs_long_opt(self):
        self.assertParseOK(["--point", "-1", "2.5", "-0", "xyz"],
                           {'point': (-1.0, 2.5, -0.0)},
                           ["xyz"])

    def test_nargs_invalid_float_value(self):
        self.assertParseFail(["-p", "1.0", "2x", "3.5"],
                             "option -p: "
                             "invalid floating-point value: '2x'")

    def test_nargs_required_values(self):
        self.assertParseFail(["--point", "1.0", "3.5"],
901
                             "--point option requires 3 arguments")
902

903
class TestMultipleArgsAppend(BaseTest):
904
    def setUp(self):
905
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
906 907 908 909
        self.parser.add_option("-p", "--point", action="store", nargs=3,
                               type="float", dest="point")
        self.parser.add_option("-f", "--foo", action="append", nargs=2,
                               type="int", dest="foo")
910 911
        self.parser.add_option("-z", "--zero", action="append_const",
                               dest="foo", const=(0, 0))
912 913 914 915 916 917 918 919

    def test_nargs_append(self):
        self.assertParseOK(["-f", "4", "-3", "blah", "--foo", "1", "666"],
                           {'point': None, 'foo': [(4, -3), (1, 666)]},
                           ["blah"])

    def test_nargs_append_required_values(self):
        self.assertParseFail(["-f4,3"],
920
                             "-f option requires 2 arguments")
921 922 923 924 925 926

    def test_nargs_append_simple(self):
        self.assertParseOK(["--foo=3", "4"],
                           {'point': None, 'foo':[(3, 4)]},
                           [])

927 928 929 930 931
    def test_nargs_append_const(self):
        self.assertParseOK(["--zero", "--foo", "3", "4", "-z"],
                           {'point': None, 'foo':[(0, 0), (3, 4), (0, 0)]},
                           [])

932 933
class TestVersion(BaseTest):
    def test_version(self):
934 935 936 937 938 939 940 941
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
                                               version="%prog 0.1")
        save_argv = sys.argv[:]
        try:
            sys.argv[0] = os.path.join(os.curdir, "foo", "bar")
            self.assertOutput(["--version"], "bar 0.1\n")
        finally:
            sys.argv[:] = save_argv
942 943

    def test_no_version(self):
944
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
        self.assertParseFail(["--version"],
                             "no such option: --version")

# -- Test conflicting default values and parser.parse_args() -----------

class TestConflictingDefaults(BaseTest):
    """Conflicting default values: the last one should win."""
    def setUp(self):
        self.parser = OptionParser(option_list=[
            make_option("-v", action="store_true", dest="verbose", default=1)])

    def test_conflict_default(self):
        self.parser.add_option("-q", action="store_false", dest="verbose",
                               default=0)
        self.assertParseOK([], {'verbose': 0}, [])

    def test_conflict_default_none(self):
        self.parser.add_option("-q", action="store_false", dest="verbose",
                               default=None)
        self.assertParseOK([], {'verbose': None}, [])

class TestOptionGroup(BaseTest):
    def setUp(self):
        self.parser = OptionParser(usage=SUPPRESS_USAGE)

    def test_option_group_create_instance(self):
        group = OptionGroup(self.parser, "Spam")
        self.parser.add_option_group(group)
        group.add_option("--spam", action="store_true",
                         help="spam spam spam spam")
        self.assertParseOK(["--spam"], {'spam': 1}, [])

    def test_add_group_no_group(self):
        self.assertTypeError(self.parser.add_option_group,
                             "not an OptionGroup instance: None", None)

    def test_add_group_invalid_arguments(self):
        self.assertTypeError(self.parser.add_option_group,
                             "invalid arguments", None, None)

    def test_add_group_wrong_parser(self):
        group = OptionGroup(self.parser, "Spam")
        group.parser = OptionParser()
988 989
        self.assertRaises(self.parser.add_option_group, (group,), None,
                          ValueError, "invalid OptionGroup (wrong parser)")
990 991 992 993 994 995

    def test_group_manipulate(self):
        group = self.parser.add_option_group("Group 2",
                                             description="Some more options")
        group.set_title("Bacon")
        group.add_option("--bacon", type="int")
996
        self.assertTrue(self.parser.get_option_group("--bacon"), group)
997 998 999 1000 1001

# -- Test extending and parser.parse_args() ----------------------------

class TestExtendAddTypes(BaseTest):
    def setUp(self):
1002 1003
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
                                               option_class=self.MyOption)
1004 1005 1006
        self.parser.add_option("-a", None, type="string", dest="a")
        self.parser.add_option("-f", "--file", type="file", dest="file")

1007
    def tearDown(self):
1008 1009 1010 1011
        if os.path.isdir(support.TESTFN):
            os.rmdir(support.TESTFN)
        elif os.path.isfile(support.TESTFN):
            os.unlink(support.TESTFN)
1012

1013
    class MyOption (Option):
1014
        def check_file(option, opt, value):
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
            if not os.path.exists(value):
                raise OptionValueError("%s: file does not exist" % value)
            elif not os.path.isfile(value):
                raise OptionValueError("%s: not a regular file" % value)
            return value

        TYPES = Option.TYPES + ("file",)
        TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
        TYPE_CHECKER["file"] = check_file

1025
    def test_filetype_ok(self):
1026 1027 1028
        open(support.TESTFN, "w").close()
        self.assertParseOK(["--file", support.TESTFN, "-afoo"],
                           {'file': support.TESTFN, 'a': 'foo'},
1029 1030
                           [])

1031
    def test_filetype_noexist(self):
1032
        self.assertParseFail(["--file", support.TESTFN, "-afoo"],
1033
                             "%s: file does not exist" %
1034
                             support.TESTFN)
1035

1036
    def test_filetype_notfile(self):
1037 1038
        os.mkdir(support.TESTFN)
        self.assertParseFail(["--file", support.TESTFN, "-afoo"],
1039
                             "%s: not a regular file" %
1040
                             support.TESTFN)
1041

1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053

class TestExtendAddActions(BaseTest):
    def setUp(self):
        options = [self.MyOption("-a", "--apple", action="extend",
                                 type="string", dest="apple")]
        self.parser = OptionParser(option_list=options)

    class MyOption (Option):
        ACTIONS = Option.ACTIONS + ("extend",)
        STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
        TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)

1054
        def take_action(self, action, dest, opt, value, values, parser):
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
            if action == "extend":
                lvalue = value.split(",")
                values.ensure_value(dest, []).extend(lvalue)
            else:
                Option.take_action(self, action, dest, opt, parser, value,
                                   values)

    def test_extend_add_action(self):
        self.assertParseOK(["-afoo,bar", "--apple=blah"],
                           {'apple': ["foo", "bar", "blah"]},
                           [])

    def test_extend_add_action_normal(self):
        self.assertParseOK(["-a", "foo", "-abar", "--apple=x,y"],
                           {'apple': ["foo", "bar", "x", "y"]},
                           [])

# -- Test callbacks and parser.parse_args() ----------------------------

class TestCallback(BaseTest):
    def setUp(self):
        options = [make_option("-x",
                               None,
                               action="callback",
                               callback=self.process_opt),
                   make_option("-f",
                               "--file",
                               action="callback",
                               callback=self.process_opt,
                               type="string",
                               dest="filename")]
        self.parser = OptionParser(option_list=options)

    def process_opt(self, option, opt, value, parser_):
        if opt == "-x":
            self.assertEqual(option._short_opts, ["-x"])
            self.assertEqual(option._long_opts, [])
1092 1093
            self.assertTrue(parser_ is self.parser)
            self.assertTrue(value is None)
1094 1095 1096 1097 1098 1099
            self.assertEqual(vars(parser_.values), {'filename': None})

            parser_.values.x = 42
        elif opt == "--file":
            self.assertEqual(option._short_opts, ["-f"])
            self.assertEqual(option._long_opts, ["--file"])
1100
            self.assertTrue(parser_ is self.parser)
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
            self.assertEqual(value, "foo")
            self.assertEqual(vars(parser_.values), {'filename': None, 'x': 42})

            setattr(parser_.values, option.dest, value)
        else:
            self.fail("Unknown option %r in process_opt." % opt)

    def test_callback(self):
        self.assertParseOK(["-x", "--file=foo"],
                           {'filename': "foo", 'x': 42},
                           [])

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
    def test_callback_help(self):
        # This test was prompted by SF bug #960515 -- the point is
        # not to inspect the help text, just to make sure that
        # format_help() doesn't crash.
        parser = OptionParser(usage=SUPPRESS_USAGE)
        parser.remove_option("-h")
        parser.add_option("-t", "--test", action="callback",
                          callback=lambda: None, type="string",
                          help="foo")

1123
        expected_help = ("Options:\n"
1124 1125 1126 1127 1128
                         "  -t TEST, --test=TEST  foo\n")
        self.assertHelp(parser, expected_help)


class TestCallbackExtraArgs(BaseTest):
1129 1130 1131 1132 1133 1134 1135
    def setUp(self):
        options = [make_option("-p", "--point", action="callback",
                               callback=self.process_tuple,
                               callback_args=(3, int), type="string",
                               dest="points", default=[])]
        self.parser = OptionParser(option_list=options)

1136
    def process_tuple(self, option, opt, value, parser_, len, type):
1137
        self.assertEqual(len, 3)
1138
        self.assertTrue(type is int)
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152

        if opt == "-p":
            self.assertEqual(value, "1,2,3")
        elif opt == "--point":
            self.assertEqual(value, "4,5,6")

        value = tuple(map(type, value.split(",")))
        getattr(parser_.values, option.dest).append(value)

    def test_callback_extra_args(self):
        self.assertParseOK(["-p1,2,3", "--point", "4,5,6"],
                           {'points': [(1,2,3), (4,5,6)]},
                           [])

1153
class TestCallbackMeddleArgs(BaseTest):
1154 1155 1156 1157 1158 1159 1160
    def setUp(self):
        options = [make_option(str(x), action="callback",
                               callback=self.process_n, dest='things')
                   for x in range(-1, -6, -1)]
        self.parser = OptionParser(option_list=options)

    # Callback that meddles in rargs, largs
1161
    def process_n(self, option, opt, value, parser_):
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
        # option is -3, -5, etc.
        nargs = int(opt[1:])
        rargs = parser_.rargs
        if len(rargs) < nargs:
            self.fail("Expected %d arguments for %s option." % (nargs, opt))
        dest = parser_.values.ensure_value(option.dest, [])
        dest.append(tuple(rargs[0:nargs]))
        parser_.largs.append(nargs)
        del rargs[0:nargs]

    def test_callback_meddle_args(self):
        self.assertParseOK(["-1", "foo", "-3", "bar", "baz", "qux"],
                           {'things': [("foo",), ("bar", "baz", "qux")]},
                           [1, 3])

    def test_callback_meddle_args_separator(self):
        self.assertParseOK(["-2", "foo", "--"],
                           {'things': [('foo', '--')]},
                           [2])

1182
class TestCallbackManyArgs(BaseTest):
1183 1184 1185 1186 1187 1188 1189
    def setUp(self):
        options = [make_option("-a", "--apple", action="callback", nargs=2,
                               callback=self.process_many, type="string"),
                   make_option("-b", "--bob", action="callback", nargs=3,
                               callback=self.process_many, type="int")]
        self.parser = OptionParser(option_list=options)

1190
    def process_many(self, option, opt, value, parser_):
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
        if opt == "-a":
            self.assertEqual(value, ("foo", "bar"))
        elif opt == "--apple":
            self.assertEqual(value, ("ding", "dong"))
        elif opt == "-b":
            self.assertEqual(value, (1, 2, 3))
        elif opt == "--bob":
            self.assertEqual(value, (-666, 42, 0))

    def test_many_args(self):
        self.assertParseOK(["-a", "foo", "bar", "--apple", "ding", "dong",
                            "-b", "1", "2", "3", "--bob", "-666", "42",
                            "0"],
1204
                           {"apple": None, "bob": None},
1205 1206
                           [])

1207
class TestCallbackCheckAbbrev(BaseTest):
1208 1209 1210 1211 1212
    def setUp(self):
        self.parser = OptionParser()
        self.parser.add_option("--foo-bar", action="callback",
                               callback=self.check_abbrev)

1213
    def check_abbrev(self, option, opt, value, parser):
1214 1215 1216 1217 1218
        self.assertEqual(opt, "--foo-bar")

    def test_abbrev_callback_expansion(self):
        self.assertParseOK(["--foo"], {}, [])

1219
class TestCallbackVarArgs(BaseTest):
1220 1221 1222 1223 1224
    def setUp(self):
        options = [make_option("-a", type="int", nargs=2, dest="a"),
                   make_option("-b", action="store_true", dest="b"),
                   make_option("-c", "--callback", action="callback",
                               callback=self.variable_args, dest="c")]
1225 1226
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
                                               option_list=options)
1227

1228
    def variable_args(self, option, opt, value, parser):
1229
        self.assertTrue(value is None)
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
        value = []
        rargs = parser.rargs
        while rargs:
            arg = rargs[0]
            if ((arg[:2] == "--" and len(arg) > 2) or
                (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
                break
            else:
                value.append(arg)
                del rargs[0]
        setattr(parser.values, option.dest, value)

    def test_variable_args(self):
        self.assertParseOK(["-a3", "-5", "--callback", "foo", "bar"],
                           {'a': (3, -5), 'b': None, 'c': ["foo", "bar"]},
                           [])

    def test_consume_separator_stop_at_option(self):
        self.assertParseOK(["-c", "37", "--", "xxx", "-b", "hello"],
                           {'a': None,
                            'b': True,
                            'c': ["37", "--", "xxx"]},
                           ["hello"])

    def test_positional_arg_and_variable_args(self):
        self.assertParseOK(["hello", "-c", "foo", "-", "bar"],
                           {'a': None,
                            'b': None,
                            'c':["foo", "-", "bar"]},
                           ["hello"])

    def test_stop_at_option(self):
        self.assertParseOK(["-c", "foo", "-b"],
                           {'a': None, 'b': True, 'c': ["foo"]},
                           [])

    def test_stop_at_invalid_option(self):
        self.assertParseFail(["-c", "3", "-5", "-a"], "no such option: -5")


# -- Test conflict handling and parser.parse_args() --------------------

class ConflictBase(BaseTest):
    def setUp(self):
        options = [make_option("-v", "--verbose", action="count",
                               dest="verbose", help="increment verbosity")]
1276 1277
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
                                               option_list=options)
1278

1279
    def show_version(self, option, opt, value, parser):
1280 1281 1282 1283
        parser.values.show_version = 1

class TestConflict(ConflictBase):
    """Use the default conflict resolution for Optik 1.2: error."""
1284
    def assertTrueconflict_error(self, func):
1285 1286 1287 1288 1289 1290
        err = self.assertRaises(
            func, ("-v", "--version"), {'action' : "callback",
                                        'callback' : self.show_version,
                                        'help' : "show version"},
            OptionConflictError,
            "option -v/--version: conflicting option string(s): -v")
1291 1292 1293 1294 1295

        self.assertEqual(err.msg, "conflicting option string(s): -v")
        self.assertEqual(err.option_id, "-v/--version")

    def test_conflict_error(self):
1296
        self.assertTrueconflict_error(self.parser.add_option)
1297 1298 1299

    def test_conflict_error_group(self):
        group = OptionGroup(self.parser, "Group 1")
1300
        self.assertTrueconflict_error(group.add_option)
1301 1302

    def test_no_such_conflict_handler(self):
1303 1304 1305
        self.assertRaises(
            self.parser.set_conflict_handler, ('foo',), None,
            ValueError, "invalid conflict_resolution value 'foo'")
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319


class TestConflictResolve(ConflictBase):
    def setUp(self):
        ConflictBase.setUp(self)
        self.parser.set_conflict_handler("resolve")
        self.parser.add_option("-v", "--version", action="callback",
                               callback=self.show_version, help="show version")

    def test_conflict_resolve(self):
        v_opt = self.parser.get_option("-v")
        verbose_opt = self.parser.get_option("--verbose")
        version_opt = self.parser.get_option("--version")

1320 1321
        self.assertTrue(v_opt is version_opt)
        self.assertTrue(v_opt is not verbose_opt)
1322 1323 1324 1325 1326 1327 1328
        self.assertEqual(v_opt._long_opts, ["--version"])
        self.assertEqual(version_opt._short_opts, ["-v"])
        self.assertEqual(version_opt._long_opts, ["--version"])
        self.assertEqual(verbose_opt._short_opts, [])
        self.assertEqual(verbose_opt._long_opts, ["--verbose"])

    def test_conflict_resolve_help(self):
1329
        self.assertOutput(["-h"], """\
1330
Options:
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
  --verbose      increment verbosity
  -h, --help     show this help message and exit
  -v, --version  show version
""")

    def test_conflict_resolve_short_opt(self):
        self.assertParseOK(["-v"],
                           {'verbose': None, 'show_version': 1},
                           [])

    def test_conflict_resolve_long_opt(self):
        self.assertParseOK(["--verbose"],
                           {'verbose': 1},
                           [])

    def test_conflict_resolve_long_opts(self):
        self.assertParseOK(["--verbose", "--version"],
                           {'verbose': 1, 'show_version': 1},
                           [])

class TestConflictOverride(BaseTest):
    def setUp(self):
1353
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
        self.parser.set_conflict_handler("resolve")
        self.parser.add_option("-n", "--dry-run",
                               action="store_true", dest="dry_run",
                               help="don't do anything")
        self.parser.add_option("--dry-run", "-n",
                               action="store_const", const=42, dest="dry_run",
                               help="dry run mode")

    def test_conflict_override_opts(self):
        opt = self.parser.get_option("--dry-run")
        self.assertEqual(opt._short_opts, ["-n"])
        self.assertEqual(opt._long_opts, ["--dry-run"])

    def test_conflict_override_help(self):
1368
        self.assertOutput(["-h"], """\
1369
Options:
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
  -h, --help     show this help message and exit
  -n, --dry-run  dry run mode
""")

    def test_conflict_override_args(self):
        self.assertParseOK(["-n"],
                           {'dry_run': 42},
                           [])

# -- Other testing. ----------------------------------------------------

1381
_expected_help_basic = """\
1382
Usage: bar.py [options]
1383

1384
Options:
1385 1386 1387 1388 1389 1390 1391 1392
  -a APPLE           throw APPLEs at basket
  -b NUM, --boo=NUM  shout "boo!" NUM times (in order to frighten away all the
                     evil spirits that cause trouble and mayhem)
  --foo=FOO          store FOO in the foo list for later fooing
  -h, --help         show this help message and exit
"""

_expected_help_long_opts_first = """\
1393
Usage: bar.py [options]
1394

1395
Options:
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
  -a APPLE           throw APPLEs at basket
  --boo=NUM, -b NUM  shout "boo!" NUM times (in order to frighten away all the
                     evil spirits that cause trouble and mayhem)
  --foo=FOO          store FOO in the foo list for later fooing
  --help, -h         show this help message and exit
"""

_expected_help_title_formatter = """\
Usage
=====
  bar.py [options]

1408
Options
1409 1410 1411 1412 1413 1414 1415 1416 1417
=======
-a APPLE           throw APPLEs at basket
--boo=NUM, -b NUM  shout "boo!" NUM times (in order to frighten away all the
                   evil spirits that cause trouble and mayhem)
--foo=FOO          store FOO in the foo list for later fooing
--help, -h         show this help message and exit
"""

_expected_help_short_lines = """\
1418
Usage: bar.py [options]
1419

1420
Options:
1421 1422 1423 1424 1425 1426 1427 1428 1429
  -a APPLE           throw APPLEs at basket
  -b NUM, --boo=NUM  shout "boo!" NUM times (in order to
                     frighten away all the evil spirits
                     that cause trouble and mayhem)
  --foo=FOO          store FOO in the foo list for later
                     fooing
  -h, --help         show this help message and exit
"""

1430 1431
class TestHelp(BaseTest):
    def setUp(self):
1432 1433 1434
        self.parser = self.make_parser(80)

    def make_parser(self, columns):
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
        options = [
            make_option("-a", type="string", dest='a',
                        metavar="APPLE", help="throw APPLEs at basket"),
            make_option("-b", "--boo", type="int", dest='boo',
                        metavar="NUM",
                        help=
                        "shout \"boo!\" NUM times (in order to frighten away "
                        "all the evil spirits that cause trouble and mayhem)"),
            make_option("--foo", action="append", type="string", dest='foo',
                        help="store FOO in the foo list for later fooing"),
            ]
1446 1447 1448 1449 1450

        # We need to set COLUMNS for the OptionParser constructor, but
        # we must restore its original value -- otherwise, this test
        # screws things up for other tests when it's part of the Python
        # test suite.
1451
        with support.EnvironmentVarGuard() as env:
1452
            env['COLUMNS'] = str(columns)
1453
            return InterceptingOptionParser(option_list=options)
1454 1455

    def assertHelpEquals(self, expected_output):
1456 1457 1458 1459 1460 1461 1462
        save_argv = sys.argv[:]
        try:
            # Make optparse believe bar.py is being executed.
            sys.argv[0] = os.path.join("foo", "bar.py")
            self.assertOutput(["-h"], expected_output)
        finally:
            sys.argv[:] = save_argv
1463 1464

    def test_help(self):
1465
        self.assertHelpEquals(_expected_help_basic)
1466 1467

    def test_help_old_usage(self):
1468
        self.parser.set_usage("Usage: %prog [options]")
1469
        self.assertHelpEquals(_expected_help_basic)
1470 1471 1472

    def test_help_long_opts_first(self):
        self.parser.formatter.short_first = 0
1473
        self.assertHelpEquals(_expected_help_long_opts_first)
1474 1475

    def test_help_title_formatter(self):
1476
        with support.EnvironmentVarGuard() as env:
1477
            env["COLUMNS"] = "80"
1478 1479
            self.parser.formatter = TitledHelpFormatter()
            self.assertHelpEquals(_expected_help_title_formatter)
1480

1481 1482 1483 1484 1485 1486
    def test_wrap_columns(self):
        # Ensure that wrapping respects $COLUMNS environment variable.
        # Need to reconstruct the parser, since that's the only time
        # we look at $COLUMNS.
        self.parser = self.make_parser(60)
        self.assertHelpEquals(_expected_help_short_lines)
1487

1488 1489
    def test_help_unicode(self):
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE)
1490 1491
        self.parser.add_option("-a", action="store_true", help="ol\u00E9!")
        expect = """\
1492 1493 1494 1495 1496 1497 1498 1499
Options:
  -h, --help  show this help message and exit
  -a          ol\u00E9!
"""
        self.assertHelpEquals(expect)

    def test_help_unicode_description(self):
        self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE,
1500 1501
                                               description="ol\u00E9!")
        expect = """\
1502 1503 1504 1505 1506 1507 1508
ol\u00E9!

Options:
  -h, --help  show this help message and exit
"""
        self.assertHelpEquals(expect)

1509 1510
    def test_help_description_groups(self):
        self.parser.set_description(
1511
            "This is the program description for %prog.  %prog has "
1512 1513 1514 1515 1516 1517 1518 1519 1520
            "an option group as well as single options.")

        group = OptionGroup(
            self.parser, "Dangerous Options",
            "Caution: use of these options is at your own risk.  "
            "It is believed that some of them bite.")
        group.add_option("-g", action="store_true", help="Group option.")
        self.parser.add_option_group(group)

1521 1522
        expect = """\
Usage: bar.py [options]
1523

1524 1525 1526
This is the program description for bar.py.  bar.py has an option group as
well as single options.

1527
Options:
1528 1529 1530 1531 1532
  -a APPLE           throw APPLEs at basket
  -b NUM, --boo=NUM  shout "boo!" NUM times (in order to frighten away all the
                     evil spirits that cause trouble and mayhem)
  --foo=FOO          store FOO in the foo list for later fooing
  -h, --help         show this help message and exit
1533 1534

  Dangerous Options:
1535 1536 1537 1538
    Caution: use of these options is at your own risk.  It is believed
    that some of them bite.

    -g               Group option.
1539
"""
1540

1541
        self.assertHelpEquals(expect)
1542

1543 1544
        self.parser.epilog = "Please report bugs to /dev/null."
        self.assertHelpEquals(expect + "\nPlease report bugs to /dev/null.\n")
Tim Peters's avatar
Tim Peters committed
1545

1546

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
class TestMatchAbbrev(BaseTest):
    def test_match_abbrev(self):
        self.assertEqual(_match_abbrev("--f",
                                       {"--foz": None,
                                        "--foo": None,
                                        "--fie": None,
                                        "--f": None}),
                         "--f")

    def test_match_abbrev_error(self):
        s = "--f"
        wordmap = {"--foz": None, "--foo": None, "--fie": None}
1559 1560
        self.assertRaises(
            _match_abbrev, (s, wordmap), None,
1561
            BadOptionError, "ambiguous option: --f (--fie, --foo, --foz?)")
1562

1563

1564 1565 1566 1567
class TestParseNumber(BaseTest):
    def setUp(self):
        self.parser = InterceptingOptionParser()
        self.parser.add_option("-n", type=int)
1568
        self.parser.add_option("-l", type=int)
1569 1570 1571 1572 1573 1574 1575

    def test_parse_num_fail(self):
        self.assertRaises(
            _parse_num, ("", int), {},
            ValueError,
            re.compile(r"invalid literal for int().*: '?'?"))
        self.assertRaises(
1576
            _parse_num, ("0xOoops", int), {},
1577
            ValueError,
1578
            re.compile(r"invalid literal for int().*: s?'?0xOoops'?"))
1579 1580 1581 1582

    def test_parse_num_ok(self):
        self.assertEqual(_parse_num("0", int), 0)
        self.assertEqual(_parse_num("0x10", int), 16)
1583 1584
        self.assertEqual(_parse_num("0XA", int), 10)
        self.assertEqual(_parse_num("010", int), 8)
1585
        self.assertEqual(_parse_num("0b11", int), 3)
1586
        self.assertEqual(_parse_num("0b", int), 0)
1587 1588 1589 1590 1591 1592 1593 1594 1595

    def test_numeric_options(self):
        self.assertParseOK(["-n", "42", "-l", "0x20"],
                           { "n": 42, "l": 0x20 }, [])
        self.assertParseOK(["-n", "0b0101", "-l010"],
                           { "n": 5, "l": 8 }, [])
        self.assertParseFail(["-n008"],
                             "option -n: invalid integer value: '008'")
        self.assertParseFail(["-l0b0123"],
1596
                             "option -l: invalid integer value: '0b0123'")
1597
        self.assertParseFail(["-l", "0x12x"],
1598
                             "option -l: invalid integer value: '0x12x'")
1599 1600


1601
def test_main():
1602
    support.run_unittest(__name__)
1603 1604

if __name__ == '__main__':
1605
    test_main()