~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_options.py

  • Committer: John Arbash Meinel
  • Author(s): Mark Hammond
  • Date: 2008-09-09 17:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 3697.
  • Revision ID: john@arbash-meinel.com-20080909170221-svim3jw2mrz0amp3
An updated transparent icon for bzr.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2012, 2016 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
import re
18
18
 
19
19
from bzrlib import (
20
20
    bzrdir,
21
21
    commands,
22
 
    controldir,
23
22
    errors,
24
23
    option,
25
 
    registry,
26
24
    )
27
25
from bzrlib.builtins import cmd_commit
28
 
from bzrlib.commands import parse_args
 
26
from bzrlib.commands import Command, parse_args
29
27
from bzrlib.tests import TestCase
30
28
from bzrlib.repofmt import knitrepo
31
29
 
43
41
        # XXX: Using cmd_commit makes these tests overly sensitive to changes
44
42
        # to cmd_commit, when they are meant to be about option parsing in
45
43
        # general.
46
 
        self.assertEqual(
47
 
           ([], {'author': [], 'exclude': [], 'fixes': [], 'help': True}),
48
 
           parse_args(cmd_commit(), ['--help']))
49
 
        self.assertEqual(
50
 
           ([], {'author': [], 'exclude': [], 'fixes': [], 'message': 'biter'}),
51
 
           parse_args(cmd_commit(), ['--message=biter']))
 
44
        self.assertEqual(parse_args(cmd_commit(), ['--help']),
 
45
           ([], {'exclude': [], 'fixes': [], 'help': True}))
 
46
        self.assertEqual(parse_args(cmd_commit(), ['--message=biter']),
 
47
           ([], {'exclude': [], 'fixes': [], 'message': 'biter'}))
52
48
 
53
49
    def test_no_more_opts(self):
54
50
        """Terminated options"""
55
 
        self.assertEqual(
56
 
            (['-file-with-dashes'], {'author': [], 'exclude': [], 'fixes': []}),
57
 
            parse_args(cmd_commit(), ['--', '-file-with-dashes']))
 
51
        self.assertEqual(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
 
52
                          (['-file-with-dashes'], {'exclude': [], 'fixes': []}))
58
53
 
59
54
    def test_option_help(self):
60
55
        """Options have help strings."""
68
63
        out, err = self.run_bzr('help status')
69
64
        self.assertContainsRe(out, r'--show-ids.*Show internal object.')
70
65
 
71
 
    def test_option_help_global_hidden(self):
72
 
        """Hidden global options have no help strings."""
73
 
        out, err = self.run_bzr('help log')
74
 
        self.assertNotContainsRe(out, r'--message')
75
 
 
76
66
    def test_option_arg_help(self):
77
67
        """Help message shows option arguments."""
78
68
        out, err = self.run_bzr('help commit')
112
102
        self.assertRaises(errors.BzrCommandError, self.parse, options,
113
103
                          ['--no-number'])
114
104
 
115
 
    def test_is_hidden(self):
116
 
        self.assertTrue(option.Option('foo', hidden=True).is_hidden('foo'))
117
 
        self.assertFalse(option.Option('foo', hidden=False).is_hidden('foo'))
118
 
 
119
105
    def test_registry_conversion(self):
120
 
        registry = controldir.ControlDirFormatRegistry()
121
 
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
122
 
        bzrdir.register_metadir(registry, 'two', 'RepositoryFormatKnit1', 'two help')
123
 
        bzrdir.register_metadir(registry, 'hidden', 'RepositoryFormatKnit1',
 
106
        registry = bzrdir.BzrDirFormatRegistry()
 
107
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
108
        registry.register_metadir('two', 'RepositoryFormatKnit1', 'two help')
 
109
        registry.register_metadir('hidden', 'RepositoryFormatKnit1',
124
110
            'two help', hidden=True)
125
111
        registry.set_default('one')
126
112
        options = [option.RegistryOption('format', '', registry, str)]
160
146
 
161
147
    def test_registry_converter(self):
162
148
        options = [option.RegistryOption('format', '',
163
 
                   controldir.format_registry, controldir.format_registry.make_bzrdir)]
 
149
                   bzrdir.format_registry, bzrdir.format_registry.make_bzrdir)]
164
150
        opts, args = self.parse(options, ['--format', 'knit'])
165
151
        self.assertIsInstance(opts.format.repository_format,
166
152
                              knitrepo.RepositoryFormatKnit1)
167
153
 
168
 
    def test_lazy_registry(self):
169
 
        options = [option.RegistryOption('format', '',
170
 
                   lazy_registry=('bzrlib.controldir','format_registry'),
171
 
                   converter=str)]
172
 
        opts, args = self.parse(options, ['--format', 'knit'])
173
 
        self.assertEqual({'format': 'knit'}, opts)
174
 
        self.assertRaises(
175
 
            errors.BadOptionValue, self.parse, options, ['--format', 'BAD'])
176
 
 
177
154
    def test_from_kwargs(self):
178
155
        my_option = option.RegistryOption.from_kwargs('my-option',
179
156
            help='test option', short='be short', be_long='go long')
187
164
        self.assertEqual('test option', my_option.help)
188
165
 
189
166
    def test_help(self):
190
 
        registry = controldir.ControlDirFormatRegistry()
191
 
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
192
 
        bzrdir.register_metadir(registry, 'two',
 
167
        registry = bzrdir.BzrDirFormatRegistry()
 
168
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
169
        registry.register_metadir('two',
193
170
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
194
171
            'two help',
195
172
            )
196
 
        bzrdir.register_metadir(registry, 'hidden', 'RepositoryFormat7', 'hidden help',
 
173
        registry.register_metadir('hidden', 'RepositoryFormat7', 'hidden help',
197
174
            hidden=True)
198
175
        registry.set_default('one')
199
176
        options = [option.RegistryOption('format', 'format help', registry,
215
192
        opt = option.Option('hello', help='fg', type=int, argname='gar')
216
193
        self.assertEqual(list(opt.iter_switches()),
217
194
                         [('hello', None, 'GAR', 'fg')])
218
 
        registry = controldir.ControlDirFormatRegistry()
219
 
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
220
 
        bzrdir.register_metadir(registry, 'two',
 
195
        registry = bzrdir.BzrDirFormatRegistry()
 
196
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
197
        registry.register_metadir('two',
221
198
                'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
222
199
                'two help',
223
200
                )
328
305
        self.assertEqual('hello', name)
329
306
        self.assertEqual([], value)
330
307
 
331
 
    def test_list_option_param_name(self):
332
 
        """Test list options can have their param_name set."""
333
 
        options = [option.ListOption('hello', type=str, param_name='greeting')]
334
 
        opts, args = self.parse(
335
 
            options, ['--hello=world', '--hello=sailor'])
336
 
        self.assertEqual(['world', 'sailor'], opts.greeting)
337
 
 
338
308
 
339
309
class TestOptionDefinitions(TestCase):
340
310
    """Tests for options in the Bazaar codebase."""
341
311
 
342
312
    def get_builtin_command_options(self):
343
313
        g = []
344
 
        commands.install_bzr_command_hooks()
345
 
        for cmd_name in sorted(commands.builtin_command_names()):
346
 
            cmd = commands.get_cmd_object(cmd_name)
 
314
        for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
 
315
            cmd = cmd_class()
347
316
            for opt_name, opt in sorted(cmd.options().items()):
348
317
                g.append((cmd_name, opt))
349
 
        self.assertTrue(g)
350
318
        return g
351
319
 
 
320
    def test_global_options_used(self):
 
321
        # In the distant memory, options could only be declared globally.  Now
 
322
        # we prefer to declare them in the command, unless like -r they really
 
323
        # are used very widely with the exact same meaning.  So this checks
 
324
        # for any that should be garbage collected.
 
325
        g = dict(option.Option.OPTIONS.items())
 
326
        used_globals = {}
 
327
        msgs = []
 
328
        for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
 
329
            for option_or_name in sorted(cmd_class.takes_options):
 
330
                if not isinstance(option_or_name, basestring):
 
331
                    self.assertIsInstance(option_or_name, option.Option)
 
332
                elif not option_or_name in g:
 
333
                    msgs.append("apparent reference to undefined "
 
334
                        "global option %r from %r"
 
335
                        % (option_or_name, cmd_class))
 
336
                else:
 
337
                    used_globals.setdefault(option_or_name, []).append(cmd_name)
 
338
        unused_globals = set(g.keys()) - set(used_globals.keys())
 
339
        # not enforced because there might be plugins that use these globals
 
340
        ## for option_name in sorted(unused_globals):
 
341
        ##    msgs.append("unused global option %r" % option_name)
 
342
        ## for option_name, cmds in sorted(used_globals.items()):
 
343
        ##     if len(cmds) <= 1:
 
344
        ##         msgs.append("global option %r is only used by %r"
 
345
        ##                 % (option_name, cmds))
 
346
        if msgs:
 
347
            self.fail("problems with global option definitions:\n"
 
348
                    + '\n'.join(msgs))
 
349
 
352
350
    def test_option_grammar(self):
353
351
        msgs = []
354
352
        # Option help should be written in sentence form, and have a final
355
 
        # period with an optional bracketed suffix. All the text should be on
356
 
        # one line, because the display code will wrap it.
357
 
        option_re = re.compile(r'^[A-Z][^\n]+\.(?: \([^\n]+\))?$')
358
 
        for scope, opt in self.get_builtin_command_options():
359
 
            for name, _, _, helptxt in opt.iter_switches():
360
 
                if name != opt.name:
361
 
                    name = "/".join([opt.name, name])
362
 
                if not helptxt:
363
 
                    msgs.append('%-16s %-16s %s' %
364
 
                           ((scope or 'GLOBAL'), name, 'NO HELP'))
365
 
                elif not option_re.match(helptxt):
366
 
                    if name.startswith("format/"):
367
 
                        # Don't complain about the odd format registry help
368
 
                        continue
369
 
                    msgs.append('%-16s %-16s %s' %
370
 
                            ((scope or 'GLOBAL'), name, helptxt))
 
353
        # period and be all on a single line, because the display code will
 
354
        # wrap it.
 
355
        option_re = re.compile(r'^[A-Z][^\n]+\.$')
 
356
        for scope, option in self.get_builtin_command_options():
 
357
            if not option.help:
 
358
                msgs.append('%-16s %-16s %s' %
 
359
                       ((scope or 'GLOBAL'), option.name, 'NO HELP'))
 
360
            elif not option_re.match(option.help):
 
361
                msgs.append('%-16s %-16s %s' %
 
362
                        ((scope or 'GLOBAL'), option.name, option.help))
371
363
        if msgs:
372
364
            self.fail("The following options don't match the style guide:\n"
373
365
                    + '\n'.join(msgs))
374
366
 
375
 
 
376
 
class TestOptionMisc(TestCase):
377
 
 
378
367
    def test_is_hidden(self):
379
 
        registry = controldir.ControlDirFormatRegistry()
380
 
        bzrdir.register_metadir(registry, 'hidden', 'HiddenFormat',
 
368
        registry = bzrdir.BzrDirFormatRegistry()
 
369
        registry.register_metadir('hidden', 'HiddenFormat',
381
370
            'hidden help text', hidden=True)
382
 
        bzrdir.register_metadir(registry, 'visible', 'VisibleFormat',
 
371
        registry.register_metadir('visible', 'VisibleFormat',
383
372
            'visible help text', hidden=False)
384
373
        format = option.RegistryOption('format', '', registry, str)
385
374
        self.assertTrue(format.is_hidden('hidden'))
386
375
        self.assertFalse(format.is_hidden('visible'))
387
376
 
388
 
    def test_short_name(self):
389
 
        registry = controldir.ControlDirFormatRegistry()
390
 
        opt = option.RegistryOption('format', help='', registry=registry)
391
 
        self.assertEqual(None, opt.short_name())
392
 
        opt = option.RegistryOption('format', short_name='F', help='',
393
 
            registry=registry)
394
 
        self.assertEqual('F', opt.short_name())
395
 
 
396
377
    def test_option_custom_help(self):
397
378
        the_opt = option.Option.OPTIONS['help']
398
379
        orig_help = the_opt.help[:]
401
382
        self.assertEqual('suggest lottery numbers', my_opt.help)
402
383
        self.assertEqual(orig_help, the_opt.help)
403
384
 
404
 
    def test_short_value_switches(self):
405
 
        reg = registry.Registry()
406
 
        reg.register('short', 'ShortChoice')
407
 
        reg.register('long', 'LongChoice')
408
 
        ropt = option.RegistryOption('choice', '', reg, value_switches=True,
409
 
            short_value_switches={'short': 's'})
410
 
        opts, args = parse([ropt], ['--short'])
411
 
        self.assertEqual('ShortChoice', opts.choice)
412
 
        opts, args = parse([ropt], ['-s'])
413
 
        self.assertEqual('ShortChoice', opts.choice)
414
 
 
415
385
 
416
386
class TestVerboseQuietLinkage(TestCase):
417
387