~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_options.py

(vila) Forbid more operations on ReadonlyTransportDecorator (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
import re
18
18
 
19
19
from bzrlib import (
20
20
    bzrdir,
21
21
    commands,
 
22
    controldir,
22
23
    errors,
23
24
    option,
 
25
    registry,
24
26
    )
25
27
from bzrlib.builtins import cmd_commit
26
 
from bzrlib.commands import Command, parse_args
 
28
from bzrlib.commands import parse_args
27
29
from bzrlib.tests import TestCase
28
30
from bzrlib.repofmt import knitrepo
29
31
 
41
43
        # XXX: Using cmd_commit makes these tests overly sensitive to changes
42
44
        # to cmd_commit, when they are meant to be about option parsing in
43
45
        # general.
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'}))
 
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']))
48
52
 
49
53
    def test_no_more_opts(self):
50
54
        """Terminated options"""
51
 
        self.assertEqual(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
52
 
                          (['-file-with-dashes'], {'exclude': [], 'fixes': []}))
 
55
        self.assertEqual(
 
56
            (['-file-with-dashes'], {'author': [], 'exclude': [], 'fixes': []}),
 
57
            parse_args(cmd_commit(), ['--', '-file-with-dashes']))
53
58
 
54
59
    def test_option_help(self):
55
60
        """Options have help strings."""
63
68
        out, err = self.run_bzr('help status')
64
69
        self.assertContainsRe(out, r'--show-ids.*Show internal object.')
65
70
 
 
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
 
66
76
    def test_option_arg_help(self):
67
77
        """Help message shows option arguments."""
68
78
        out, err = self.run_bzr('help commit')
102
112
        self.assertRaises(errors.BzrCommandError, self.parse, options,
103
113
                          ['--no-number'])
104
114
 
 
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
 
105
119
    def test_registry_conversion(self):
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',
 
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',
110
124
            'two help', hidden=True)
111
125
        registry.set_default('one')
112
126
        options = [option.RegistryOption('format', '', registry, str)]
146
160
 
147
161
    def test_registry_converter(self):
148
162
        options = [option.RegistryOption('format', '',
149
 
                   bzrdir.format_registry, bzrdir.format_registry.make_bzrdir)]
 
163
                   controldir.format_registry, controldir.format_registry.make_bzrdir)]
150
164
        opts, args = self.parse(options, ['--format', 'knit'])
151
165
        self.assertIsInstance(opts.format.repository_format,
152
166
                              knitrepo.RepositoryFormatKnit1)
153
167
 
 
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
 
154
177
    def test_from_kwargs(self):
155
178
        my_option = option.RegistryOption.from_kwargs('my-option',
156
179
            help='test option', short='be short', be_long='go long')
164
187
        self.assertEqual('test option', my_option.help)
165
188
 
166
189
    def test_help(self):
167
 
        registry = bzrdir.BzrDirFormatRegistry()
168
 
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
169
 
        registry.register_metadir('two',
 
190
        registry = controldir.ControlDirFormatRegistry()
 
191
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
 
192
        bzrdir.register_metadir(registry, 'two',
170
193
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
171
194
            'two help',
172
195
            )
173
 
        registry.register_metadir('hidden', 'RepositoryFormat7', 'hidden help',
 
196
        bzrdir.register_metadir(registry, 'hidden', 'RepositoryFormat7', 'hidden help',
174
197
            hidden=True)
175
198
        registry.set_default('one')
176
199
        options = [option.RegistryOption('format', 'format help', registry,
192
215
        opt = option.Option('hello', help='fg', type=int, argname='gar')
193
216
        self.assertEqual(list(opt.iter_switches()),
194
217
                         [('hello', None, 'GAR', 'fg')])
195
 
        registry = bzrdir.BzrDirFormatRegistry()
196
 
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
197
 
        registry.register_metadir('two',
 
218
        registry = controldir.ControlDirFormatRegistry()
 
219
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
 
220
        bzrdir.register_metadir(registry, 'two',
198
221
                'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
199
222
                'two help',
200
223
                )
305
328
        self.assertEqual('hello', name)
306
329
        self.assertEqual([], value)
307
330
 
 
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
 
308
338
 
309
339
class TestOptionDefinitions(TestCase):
310
340
    """Tests for options in the Bazaar codebase."""
311
341
 
312
342
    def get_builtin_command_options(self):
313
343
        g = []
314
 
        for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
315
 
            cmd = cmd_class()
 
344
        commands.install_bzr_command_hooks()
 
345
        for cmd_name in sorted(commands.builtin_command_names()):
 
346
            cmd = commands.get_cmd_object(cmd_name)
316
347
            for opt_name, opt in sorted(cmd.options().items()):
317
348
                g.append((cmd_name, opt))
 
349
        self.assert_(g)
318
350
        return g
319
351
 
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
 
 
350
352
    def test_option_grammar(self):
351
353
        msgs = []
352
354
        # Option help should be written in sentence form, and have a final
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))
 
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))
363
371
        if msgs:
364
372
            self.fail("The following options don't match the style guide:\n"
365
373
                    + '\n'.join(msgs))
366
374
 
 
375
 
 
376
class TestOptionMisc(TestCase):
 
377
 
367
378
    def test_is_hidden(self):
368
 
        registry = bzrdir.BzrDirFormatRegistry()
369
 
        registry.register_metadir('hidden', 'HiddenFormat',
 
379
        registry = controldir.ControlDirFormatRegistry()
 
380
        bzrdir.register_metadir(registry, 'hidden', 'HiddenFormat',
370
381
            'hidden help text', hidden=True)
371
 
        registry.register_metadir('visible', 'VisibleFormat',
 
382
        bzrdir.register_metadir(registry, 'visible', 'VisibleFormat',
372
383
            'visible help text', hidden=False)
373
384
        format = option.RegistryOption('format', '', registry, str)
374
385
        self.assertTrue(format.is_hidden('hidden'))
375
386
        self.assertFalse(format.is_hidden('visible'))
376
387
 
 
388
    def test_short_name(self):
 
389
        registry = controldir.ControlDirFormatRegistry()
 
390
        opt = option.RegistryOption('format', help='', registry=registry)
 
391
        self.assertEquals(None, opt.short_name())
 
392
        opt = option.RegistryOption('format', short_name='F', help='',
 
393
            registry=registry)
 
394
        self.assertEquals('F', opt.short_name())
 
395
 
377
396
    def test_option_custom_help(self):
378
397
        the_opt = option.Option.OPTIONS['help']
379
398
        orig_help = the_opt.help[:]
382
401
        self.assertEqual('suggest lottery numbers', my_opt.help)
383
402
        self.assertEqual(orig_help, the_opt.help)
384
403
 
 
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
 
385
415
 
386
416
class TestVerboseQuietLinkage(TestCase):
387
417