~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_options.py

  • Committer: Andrew Bennetts
  • Date: 2010-10-08 08:15:14 UTC
  • mto: This revision was merged to the branch mainline in revision 5498.
  • Revision ID: andrew.bennetts@canonical.com-20101008081514-dviqzrdfwyzsqbz2
Split NEWS into per-release doc/en/release-notes/bzr-*.txt

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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
 
    builtins,
21
20
    bzrdir,
22
21
    commands,
 
22
    controldir,
23
23
    errors,
24
24
    option,
25
 
    repository,
26
 
    symbol_versioning,
27
25
    )
28
 
from bzrlib.builtins import cmd_commit, cmd_log, cmd_status
 
26
from bzrlib.builtins import cmd_commit
29
27
from bzrlib.commands import Command, parse_args
30
28
from bzrlib.tests import TestCase
31
29
from bzrlib.repofmt import knitrepo
41
39
 
42
40
    def test_parse_args(self):
43
41
        """Option parser"""
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'}))
 
42
        # XXX: Using cmd_commit makes these tests overly sensitive to changes
 
43
        # to cmd_commit, when they are meant to be about option parsing in
 
44
        # general.
 
45
        self.assertEqual(parse_args(cmd_commit(), ['--help']),
 
46
           ([], {'author': [], 'exclude': [], 'fixes': [], 'help': True}))
 
47
        self.assertEqual(parse_args(cmd_commit(), ['--message=biter']),
 
48
           ([], {'author': [], 'exclude': [], 'fixes': [], 'message': 'biter'}))
49
49
 
50
50
    def test_no_more_opts(self):
51
51
        """Terminated options"""
52
 
        self.assertEquals(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
53
 
                          (['-file-with-dashes'], {'fixes': []}))
 
52
        self.assertEqual(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
 
53
                          (['-file-with-dashes'], {'author': [], 'exclude': [], 'fixes': []}))
54
54
 
55
55
    def test_option_help(self):
56
56
        """Options have help strings."""
67
67
    def test_option_arg_help(self):
68
68
        """Help message shows option arguments."""
69
69
        out, err = self.run_bzr('help commit')
70
 
        self.assertEquals(err, '')
 
70
        self.assertEqual(err, '')
71
71
        self.assertContainsRe(out, r'--file[ =]MSGFILE')
72
72
 
73
73
    def test_unknown_short_opt(self):
81
81
 
82
82
    def test_allow_dash(self):
83
83
        """Test that we can pass a plain '-' as an argument."""
84
 
        self.assertEqual(
85
 
            (['-'], {'fixes': []}), parse_args(cmd_commit(), ['-']))
 
84
        self.assertEqual((['-']), parse_args(cmd_commit(), ['-'])[0])
86
85
 
87
86
    def parse(self, options, args):
88
87
        parser = option.get_optparser(dict((o.name, o) for o in options))
93
92
        opts, args = self.parse(options, ['--no-hello', '--hello'])
94
93
        self.assertEqual(True, opts.hello)
95
94
        opts, args = self.parse(options, [])
96
 
        self.assertEqual(option.OptionParser.DEFAULT_VALUE, opts.hello)
 
95
        self.assertFalse(hasattr(opts, 'hello'))
97
96
        opts, args = self.parse(options, ['--hello', '--no-hello'])
98
97
        self.assertEqual(False, opts.hello)
99
98
        options = [option.Option('number', type=int)]
104
103
        self.assertRaises(errors.BzrCommandError, self.parse, options,
105
104
                          ['--no-number'])
106
105
 
 
106
    def test_is_hidden(self):
 
107
        self.assertTrue(option.Option('foo', hidden=True).is_hidden('foo'))
 
108
        self.assertFalse(option.Option('foo', hidden=False).is_hidden('foo'))
 
109
 
107
110
    def test_registry_conversion(self):
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',
 
111
        registry = controldir.ControlDirFormatRegistry()
 
112
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
 
113
        bzrdir.register_metadir(registry, 'two', 'RepositoryFormatKnit1', 'two help')
 
114
        bzrdir.register_metadir(registry, 'hidden', 'RepositoryFormatKnit1',
112
115
            'two help', hidden=True)
113
116
        registry.set_default('one')
114
117
        options = [option.RegistryOption('format', '', registry, str)]
153
156
        self.assertIsInstance(opts.format.repository_format,
154
157
                              knitrepo.RepositoryFormatKnit1)
155
158
 
 
159
    def test_lazy_registry(self):
 
160
        options = [option.RegistryOption('format', '',
 
161
                   lazy_registry=('bzrlib.bzrdir','format_registry'),
 
162
                   converter=str)]
 
163
        opts, args = self.parse(options, ['--format', 'knit'])
 
164
        self.assertEqual({'format': 'knit'}, opts)
 
165
        self.assertRaises(
 
166
            errors.BadOptionValue, self.parse, options, ['--format', 'BAD'])
 
167
 
156
168
    def test_from_kwargs(self):
157
169
        my_option = option.RegistryOption.from_kwargs('my-option',
158
170
            help='test option', short='be short', be_long='go long')
166
178
        self.assertEqual('test option', my_option.help)
167
179
 
168
180
    def test_help(self):
169
 
        registry = bzrdir.BzrDirFormatRegistry()
170
 
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
171
 
        registry.register_metadir('two',
 
181
        registry = controldir.ControlDirFormatRegistry()
 
182
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
 
183
        bzrdir.register_metadir(registry, 'two',
172
184
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
173
185
            'two help',
174
186
            )
175
 
        registry.register_metadir('hidden', 'RepositoryFormat7', 'hidden help',
 
187
        bzrdir.register_metadir(registry, 'hidden', 'RepositoryFormat7', 'hidden help',
176
188
            hidden=True)
177
189
        registry.set_default('one')
178
190
        options = [option.RegistryOption('format', 'format help', registry,
194
206
        opt = option.Option('hello', help='fg', type=int, argname='gar')
195
207
        self.assertEqual(list(opt.iter_switches()),
196
208
                         [('hello', None, 'GAR', 'fg')])
197
 
        registry = bzrdir.BzrDirFormatRegistry()
198
 
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
199
 
        registry.register_metadir('two',
 
209
        registry = controldir.ControlDirFormatRegistry()
 
210
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
 
211
        bzrdir.register_metadir(registry, 'two',
200
212
                'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
201
213
                'two help',
202
214
                )
214
226
                          ('two', None, None, 'two help'),
215
227
                          ])
216
228
 
 
229
    def test_option_callback_bool(self):
 
230
        "Test booleans get True and False passed correctly to a callback."""
 
231
        cb_calls = []
 
232
        def cb(option, name, value, parser):
 
233
            cb_calls.append((option,name,value,parser))
 
234
        options = [option.Option('hello', custom_callback=cb)]
 
235
        opts, args = self.parse(options, ['--hello', '--no-hello'])
 
236
        self.assertEqual(2, len(cb_calls))
 
237
        opt,name,value,parser = cb_calls[0]
 
238
        self.assertEqual('hello', name)
 
239
        self.assertTrue(value)
 
240
        opt,name,value,parser = cb_calls[1]
 
241
        self.assertEqual('hello', name)
 
242
        self.assertFalse(value)
 
243
 
 
244
    def test_option_callback_str(self):
 
245
        """Test callbacks work for string options both long and short."""
 
246
        cb_calls = []
 
247
        def cb(option, name, value, parser):
 
248
            cb_calls.append((option,name,value,parser))
 
249
        options = [option.Option('hello', type=str, custom_callback=cb,
 
250
            short_name='h')]
 
251
        opts, args = self.parse(options, ['--hello', 'world', '-h', 'mars'])
 
252
        self.assertEqual(2, len(cb_calls))
 
253
        opt,name,value,parser = cb_calls[0]
 
254
        self.assertEqual('hello', name)
 
255
        self.assertEqual('world', value)
 
256
        opt,name,value,parser = cb_calls[1]
 
257
        self.assertEqual('hello', name)
 
258
        self.assertEqual('mars', value)
 
259
 
217
260
 
218
261
class TestListOptions(TestCase):
219
262
    """Tests for ListOption, used to specify lists on the command-line."""
227
270
        opts, args = self.parse(options, ['--hello=world', '--hello=sailor'])
228
271
        self.assertEqual(['world', 'sailor'], opts.hello)
229
272
 
 
273
    def test_list_option_with_dash(self):
 
274
        options = [option.ListOption('with-dash', type=str)]
 
275
        opts, args = self.parse(options, ['--with-dash=world',
 
276
                                          '--with-dash=sailor'])
 
277
        self.assertEqual(['world', 'sailor'], opts.with_dash)
 
278
 
230
279
    def test_list_option_no_arguments(self):
231
280
        options = [option.ListOption('hello', type=str)]
232
281
        opts, args = self.parse(options, [])
250
299
            options, ['--hello=a', '--hello=b', '--hello=-', '--hello=c'])
251
300
        self.assertEqual(['c'], opts.hello)
252
301
 
 
302
    def test_option_callback_list(self):
 
303
        """Test callbacks work for list options."""
 
304
        cb_calls = []
 
305
        def cb(option, name, value, parser):
 
306
            # Note that the value is a reference so copy to keep it
 
307
            cb_calls.append((option,name,value[:],parser))
 
308
        options = [option.ListOption('hello', type=str, custom_callback=cb)]
 
309
        opts, args = self.parse(options, ['--hello=world', '--hello=mars',
 
310
            '--hello=-'])
 
311
        self.assertEqual(3, len(cb_calls))
 
312
        opt,name,value,parser = cb_calls[0]
 
313
        self.assertEqual('hello', name)
 
314
        self.assertEqual(['world'], value)
 
315
        opt,name,value,parser = cb_calls[1]
 
316
        self.assertEqual('hello', name)
 
317
        self.assertEqual(['world', 'mars'], value)
 
318
        opt,name,value,parser = cb_calls[2]
 
319
        self.assertEqual('hello', name)
 
320
        self.assertEqual([], value)
 
321
 
 
322
    def test_list_option_param_name(self):
 
323
        """Test list options can have their param_name set."""
 
324
        options = [option.ListOption('hello', type=str, param_name='greeting')]
 
325
        opts, args = self.parse(
 
326
            options, ['--hello=world', '--hello=sailor'])
 
327
        self.assertEqual(['world', 'sailor'], opts.greeting)
 
328
 
253
329
 
254
330
class TestOptionDefinitions(TestCase):
255
331
    """Tests for options in the Bazaar codebase."""
256
332
 
257
333
    def get_builtin_command_options(self):
258
334
        g = []
259
 
        for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
260
 
            cmd = cmd_class()
 
335
        for cmd_name in sorted(commands.all_command_names()):
 
336
            cmd = commands.get_cmd_object(cmd_name)
261
337
            for opt_name, opt in sorted(cmd.options().items()):
262
338
                g.append((cmd_name, opt))
263
339
        return g
270
346
        g = dict(option.Option.OPTIONS.items())
271
347
        used_globals = {}
272
348
        msgs = []
273
 
        for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
274
 
            for option_or_name in sorted(cmd_class.takes_options):
 
349
        for cmd_name in sorted(commands.all_command_names()):
 
350
            cmd = commands.get_cmd_object(cmd_name)
 
351
            for option_or_name in sorted(cmd.takes_options):
275
352
                if not isinstance(option_or_name, basestring):
276
353
                    self.assertIsInstance(option_or_name, option.Option)
277
354
                elif not option_or_name in g:
278
355
                    msgs.append("apparent reference to undefined "
279
356
                        "global option %r from %r"
280
 
                        % (option_or_name, cmd_class))
 
357
                        % (option_or_name, cmd))
281
358
                else:
282
359
                    used_globals.setdefault(option_or_name, []).append(cmd_name)
283
360
        unused_globals = set(g.keys()) - set(used_globals.keys())
298
375
        # period and be all on a single line, because the display code will
299
376
        # wrap it.
300
377
        option_re = re.compile(r'^[A-Z][^\n]+\.$')
301
 
        for scope, option in self.get_builtin_command_options():
302
 
            if not option.help:
303
 
                msgs.append('%-16s %-16s %s' %
304
 
                       ((scope or 'GLOBAL'), option.name, 'NO HELP'))
305
 
            elif not option_re.match(option.help):
306
 
                msgs.append('%-16s %-16s %s' %
307
 
                        ((scope or 'GLOBAL'), option.name, option.help))
 
378
        for scope, opt in self.get_builtin_command_options():
 
379
            if not opt.help:
 
380
                msgs.append('%-16s %-16s %s' %
 
381
                       ((scope or 'GLOBAL'), opt.name, 'NO HELP'))
 
382
            elif not option_re.match(opt.help):
 
383
                msgs.append('%-16s %-16s %s' %
 
384
                        ((scope or 'GLOBAL'), opt.name, opt.help))
308
385
        if msgs:
309
386
            self.fail("The following options don't match the style guide:\n"
310
387
                    + '\n'.join(msgs))
311
388
 
312
389
    def test_is_hidden(self):
313
 
        registry = bzrdir.BzrDirFormatRegistry()
314
 
        registry.register_metadir('hidden', 'HiddenFormat',
 
390
        registry = controldir.ControlDirFormatRegistry()
 
391
        bzrdir.register_metadir(registry, 'hidden', 'HiddenFormat',
315
392
            'hidden help text', hidden=True)
316
 
        registry.register_metadir('visible', 'VisibleFormat',
 
393
        bzrdir.register_metadir(registry, 'visible', 'VisibleFormat',
317
394
            'visible help text', hidden=False)
318
395
        format = option.RegistryOption('format', '', registry, str)
319
396
        self.assertTrue(format.is_hidden('hidden'))
320
397
        self.assertFalse(format.is_hidden('visible'))
 
398
 
 
399
    def test_option_custom_help(self):
 
400
        the_opt = option.Option.OPTIONS['help']
 
401
        orig_help = the_opt.help[:]
 
402
        my_opt = option.custom_help('help', 'suggest lottery numbers')
 
403
        # Confirm that my_opt has my help and the original is unchanged
 
404
        self.assertEqual('suggest lottery numbers', my_opt.help)
 
405
        self.assertEqual(orig_help, the_opt.help)
 
406
 
 
407
 
 
408
class TestVerboseQuietLinkage(TestCase):
 
409
 
 
410
    def check(self, parser, level, args):
 
411
        option._verbosity_level = 0
 
412
        opts, args = parser.parse_args(args)
 
413
        self.assertEqual(level, option._verbosity_level)
 
414
 
 
415
    def test_verbose_quiet_linkage(self):
 
416
        parser = option.get_optparser(option.Option.STD_OPTIONS)
 
417
        self.check(parser, 0, [])
 
418
        self.check(parser, 1, ['-v'])
 
419
        self.check(parser, 2, ['-v', '-v'])
 
420
        self.check(parser, -1, ['-q'])
 
421
        self.check(parser, -2, ['-qq'])
 
422
        self.check(parser, -1, ['-v', '-v', '-q'])
 
423
        self.check(parser, 2, ['-q', '-v', '-v'])
 
424
        self.check(parser, 0, ['--no-verbose'])
 
425
        self.check(parser, 0, ['-v', '-q', '--no-quiet'])