~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_options.py

  • Committer: John Arbash Meinel
  • Date: 2008-07-09 21:42:24 UTC
  • mto: This revision was merged to the branch mainline in revision 3543.
  • Revision ID: john@arbash-meinel.com-20080709214224-r75k87r6a01pfc3h
Restore a real weave merge to 'bzr merge --weave'.

To do so efficiently, we only add the simple LCAs to the final weave
object, unless we run into complexities with the merge graph.
This gives the same effective result as adding all the texts,
with the advantage of not having to extract all of them.

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
    builtins,
20
21
    bzrdir,
21
22
    commands,
22
 
    controldir,
23
23
    errors,
24
24
    option,
25
 
    registry,
 
25
    repository,
 
26
    symbol_versioning,
26
27
    )
27
 
from bzrlib.builtins import cmd_commit
28
 
from bzrlib.commands import parse_args
 
28
from bzrlib.builtins import cmd_commit, cmd_log, cmd_status
 
29
from bzrlib.commands import Command, parse_args
29
30
from bzrlib.tests import TestCase
30
31
from bzrlib.repofmt import knitrepo
31
32
 
40
41
 
41
42
    def test_parse_args(self):
42
43
        """Option parser"""
43
 
        # XXX: Using cmd_commit makes these tests overly sensitive to changes
44
 
        # to cmd_commit, when they are meant to be about option parsing in
45
 
        # 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
        eq = self.assertEquals
 
45
        eq(parse_args(cmd_commit(), ['--help']),
 
46
           ([], {'fixes': [], 'help': True}))
 
47
        eq(parse_args(cmd_commit(), ['--message=biter']),
 
48
           ([], {'fixes': [], 'message': 'biter'}))
52
49
 
53
50
    def test_no_more_opts(self):
54
51
        """Terminated options"""
55
 
        self.assertEqual(
56
 
            (['-file-with-dashes'], {'author': [], 'exclude': [], 'fixes': []}),
57
 
            parse_args(cmd_commit(), ['--', '-file-with-dashes']))
 
52
        self.assertEquals(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
 
53
                          (['-file-with-dashes'], {'fixes': []}))
58
54
 
59
55
    def test_option_help(self):
60
56
        """Options have help strings."""
68
64
        out, err = self.run_bzr('help status')
69
65
        self.assertContainsRe(out, r'--show-ids.*Show internal object.')
70
66
 
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
67
    def test_option_arg_help(self):
77
68
        """Help message shows option arguments."""
78
69
        out, err = self.run_bzr('help commit')
79
 
        self.assertEqual(err, '')
 
70
        self.assertEquals(err, '')
80
71
        self.assertContainsRe(out, r'--file[ =]MSGFILE')
81
72
 
82
73
    def test_unknown_short_opt(self):
90
81
 
91
82
    def test_allow_dash(self):
92
83
        """Test that we can pass a plain '-' as an argument."""
93
 
        self.assertEqual((['-']), parse_args(cmd_commit(), ['-'])[0])
 
84
        self.assertEqual(
 
85
            (['-'], {'fixes': []}), parse_args(cmd_commit(), ['-']))
94
86
 
95
87
    def parse(self, options, args):
96
88
        parser = option.get_optparser(dict((o.name, o) for o in options))
112
104
        self.assertRaises(errors.BzrCommandError, self.parse, options,
113
105
                          ['--no-number'])
114
106
 
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
107
    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',
 
108
        registry = bzrdir.BzrDirFormatRegistry()
 
109
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
110
        registry.register_metadir('two', 'RepositoryFormatKnit1', 'two help')
 
111
        registry.register_metadir('hidden', 'RepositoryFormatKnit1',
124
112
            'two help', hidden=True)
125
113
        registry.set_default('one')
126
114
        options = [option.RegistryOption('format', '', registry, str)]
160
148
 
161
149
    def test_registry_converter(self):
162
150
        options = [option.RegistryOption('format', '',
163
 
                   controldir.format_registry, controldir.format_registry.make_bzrdir)]
 
151
                   bzrdir.format_registry, bzrdir.format_registry.make_bzrdir)]
164
152
        opts, args = self.parse(options, ['--format', 'knit'])
165
153
        self.assertIsInstance(opts.format.repository_format,
166
154
                              knitrepo.RepositoryFormatKnit1)
167
155
 
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
156
    def test_from_kwargs(self):
178
157
        my_option = option.RegistryOption.from_kwargs('my-option',
179
158
            help='test option', short='be short', be_long='go long')
187
166
        self.assertEqual('test option', my_option.help)
188
167
 
189
168
    def test_help(self):
190
 
        registry = controldir.ControlDirFormatRegistry()
191
 
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
192
 
        bzrdir.register_metadir(registry, 'two',
 
169
        registry = bzrdir.BzrDirFormatRegistry()
 
170
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
171
        registry.register_metadir('two',
193
172
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
194
173
            'two help',
195
174
            )
196
 
        bzrdir.register_metadir(registry, 'hidden', 'RepositoryFormat7', 'hidden help',
 
175
        registry.register_metadir('hidden', 'RepositoryFormat7', 'hidden help',
197
176
            hidden=True)
198
177
        registry.set_default('one')
199
178
        options = [option.RegistryOption('format', 'format help', registry,
215
194
        opt = option.Option('hello', help='fg', type=int, argname='gar')
216
195
        self.assertEqual(list(opt.iter_switches()),
217
196
                         [('hello', None, 'GAR', 'fg')])
218
 
        registry = controldir.ControlDirFormatRegistry()
219
 
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
220
 
        bzrdir.register_metadir(registry, 'two',
 
197
        registry = bzrdir.BzrDirFormatRegistry()
 
198
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
199
        registry.register_metadir('two',
221
200
                'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
222
201
                'two help',
223
202
                )
279
258
        opts, args = self.parse(options, ['--hello=world', '--hello=sailor'])
280
259
        self.assertEqual(['world', 'sailor'], opts.hello)
281
260
 
282
 
    def test_list_option_with_dash(self):
283
 
        options = [option.ListOption('with-dash', type=str)]
284
 
        opts, args = self.parse(options, ['--with-dash=world',
285
 
                                          '--with-dash=sailor'])
286
 
        self.assertEqual(['world', 'sailor'], opts.with_dash)
287
 
 
288
261
    def test_list_option_no_arguments(self):
289
262
        options = [option.ListOption('hello', type=str)]
290
263
        opts, args = self.parse(options, [])
328
301
        self.assertEqual('hello', name)
329
302
        self.assertEqual([], value)
330
303
 
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
304
 
339
305
class TestOptionDefinitions(TestCase):
340
306
    """Tests for options in the Bazaar codebase."""
341
307
 
342
308
    def get_builtin_command_options(self):
343
309
        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)
 
310
        for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
 
311
            cmd = cmd_class()
347
312
            for opt_name, opt in sorted(cmd.options().items()):
348
313
                g.append((cmd_name, opt))
349
 
        self.assertTrue(g)
350
314
        return g
351
315
 
 
316
    def test_global_options_used(self):
 
317
        # In the distant memory, options could only be declared globally.  Now
 
318
        # we prefer to declare them in the command, unless like -r they really
 
319
        # are used very widely with the exact same meaning.  So this checks
 
320
        # for any that should be garbage collected.
 
321
        g = dict(option.Option.OPTIONS.items())
 
322
        used_globals = {}
 
323
        msgs = []
 
324
        for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
 
325
            for option_or_name in sorted(cmd_class.takes_options):
 
326
                if not isinstance(option_or_name, basestring):
 
327
                    self.assertIsInstance(option_or_name, option.Option)
 
328
                elif not option_or_name in g:
 
329
                    msgs.append("apparent reference to undefined "
 
330
                        "global option %r from %r"
 
331
                        % (option_or_name, cmd_class))
 
332
                else:
 
333
                    used_globals.setdefault(option_or_name, []).append(cmd_name)
 
334
        unused_globals = set(g.keys()) - set(used_globals.keys())
 
335
        # not enforced because there might be plugins that use these globals
 
336
        ## for option_name in sorted(unused_globals):
 
337
        ##    msgs.append("unused global option %r" % option_name)
 
338
        ## for option_name, cmds in sorted(used_globals.items()):
 
339
        ##     if len(cmds) <= 1:
 
340
        ##         msgs.append("global option %r is only used by %r"
 
341
        ##                 % (option_name, cmds))
 
342
        if msgs:
 
343
            self.fail("problems with global option definitions:\n"
 
344
                    + '\n'.join(msgs))
 
345
 
352
346
    def test_option_grammar(self):
353
347
        msgs = []
354
348
        # 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))
 
349
        # period and be all on a single line, because the display code will
 
350
        # wrap it.
 
351
        option_re = re.compile(r'^[A-Z][^\n]+\.$')
 
352
        for scope, option in self.get_builtin_command_options():
 
353
            if not option.help:
 
354
                msgs.append('%-16s %-16s %s' %
 
355
                       ((scope or 'GLOBAL'), option.name, 'NO HELP'))
 
356
            elif not option_re.match(option.help):
 
357
                msgs.append('%-16s %-16s %s' %
 
358
                        ((scope or 'GLOBAL'), option.name, option.help))
371
359
        if msgs:
372
360
            self.fail("The following options don't match the style guide:\n"
373
361
                    + '\n'.join(msgs))
374
362
 
375
 
 
376
 
class TestOptionMisc(TestCase):
377
 
 
378
363
    def test_is_hidden(self):
379
 
        registry = controldir.ControlDirFormatRegistry()
380
 
        bzrdir.register_metadir(registry, 'hidden', 'HiddenFormat',
 
364
        registry = bzrdir.BzrDirFormatRegistry()
 
365
        registry.register_metadir('hidden', 'HiddenFormat',
381
366
            'hidden help text', hidden=True)
382
 
        bzrdir.register_metadir(registry, 'visible', 'VisibleFormat',
 
367
        registry.register_metadir('visible', 'VisibleFormat',
383
368
            'visible help text', hidden=False)
384
369
        format = option.RegistryOption('format', '', registry, str)
385
370
        self.assertTrue(format.is_hidden('hidden'))
386
371
        self.assertFalse(format.is_hidden('visible'))
387
372
 
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
373
    def test_option_custom_help(self):
397
374
        the_opt = option.Option.OPTIONS['help']
398
375
        orig_help = the_opt.help[:]
401
378
        self.assertEqual('suggest lottery numbers', my_opt.help)
402
379
        self.assertEqual(orig_help, the_opt.help)
403
380
 
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
381
 
416
382
class TestVerboseQuietLinkage(TestCase):
417
383