/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_options.py

  • Committer: Marius Kruger
  • Date: 2010-07-10 21:28:56 UTC
  • mto: (5384.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5385.
  • Revision ID: marius.kruger@enerweb.co.za-20100710212856-uq4ji3go0u5se7hx
* Update documentation
* add NEWS

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
16
16
 
17
17
import re
18
18
 
19
 
from .. import (
20
 
    bzr,
 
19
from bzrlib import (
 
20
    bzrdir,
21
21
    commands,
22
 
    controldir,
23
22
    errors,
24
23
    option,
25
 
    registry,
26
24
    )
27
 
from ..builtins import cmd_commit
28
 
from ..commands import parse_args
29
 
from . import TestCase
30
 
from ..bzr import knitrepo
 
25
from bzrlib.builtins import cmd_commit
 
26
from bzrlib.commands import Command, parse_args
 
27
from bzrlib.tests import TestCase
 
28
from bzrlib.repofmt import knitrepo
31
29
 
32
30
 
33
31
def parse(options, args):
34
 
    parser = option.get_optparser(options)
 
32
    parser = option.get_optparser(dict((o.name, o) for o in options))
35
33
    return parser.parse_args(args)
36
34
 
37
35
 
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
 
                  'bugs': []}),
49
 
            parse_args(cmd_commit(), ['--help']))
50
 
        self.assertEqual(
51
 
            ([], {'author': [], 'exclude': [], 'fixes': [], 'message': 'biter',
52
 
                  'bugs': []}),
53
 
            parse_args(cmd_commit(), ['--message=biter']))
 
44
        self.assertEqual(parse_args(cmd_commit(), ['--help']),
 
45
           ([], {'author': [], 'exclude': [], 'fixes': [], 'help': True}))
 
46
        self.assertEqual(parse_args(cmd_commit(), ['--message=biter']),
 
47
           ([], {'author': [], 'exclude': [], 'fixes': [], 'message': 'biter'}))
54
48
 
55
49
    def test_no_more_opts(self):
56
50
        """Terminated options"""
57
 
        self.assertEqual(
58
 
            (['-file-with-dashes'], {
59
 
                'author': [], 'exclude': [], 'fixes': [], 'bugs': []}),
60
 
            parse_args(cmd_commit(), ['--', '-file-with-dashes']))
 
51
        self.assertEqual(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
 
52
                          (['-file-with-dashes'], {'author': [], 'exclude': [], 'fixes': []}))
61
53
 
62
54
    def test_option_help(self):
63
55
        """Options have help strings."""
64
56
        out, err = self.run_bzr('commit --help')
65
57
        self.assertContainsRe(out,
66
 
                              r'--file(.|\n)*Take commit message from this file\.')
 
58
                r'--file(.|\n)*Take commit message from this file\.')
67
59
        self.assertContainsRe(out, r'-h.*--help')
68
60
 
69
61
    def test_option_help_global(self):
71
63
        out, err = self.run_bzr('help status')
72
64
        self.assertContainsRe(out, r'--show-ids.*Show internal object.')
73
65
 
74
 
    def test_option_help_global_hidden(self):
75
 
        """Hidden global options have no help strings."""
76
 
        out, err = self.run_bzr('help log')
77
 
        self.assertNotContainsRe(out, r'--message')
78
 
 
79
66
    def test_option_arg_help(self):
80
67
        """Help message shows option arguments."""
81
68
        out, err = self.run_bzr('help commit')
96
83
        self.assertEqual((['-']), parse_args(cmd_commit(), ['-'])[0])
97
84
 
98
85
    def parse(self, options, args):
99
 
        parser = option.get_optparser(options)
 
86
        parser = option.get_optparser(dict((o.name, o) for o in options))
100
87
        return parser.parse_args(args)
101
88
 
102
89
    def test_conversion(self):
114
101
                          ['--number'])
115
102
        self.assertRaises(errors.BzrCommandError, self.parse, options,
116
103
                          ['--no-number'])
117
 
        self.assertRaises(errors.BzrCommandError, self.parse, options,
118
 
                          ['--number', 'a'])
119
104
 
120
105
    def test_is_hidden(self):
121
106
        self.assertTrue(option.Option('foo', hidden=True).is_hidden('foo'))
122
107
        self.assertFalse(option.Option('foo', hidden=False).is_hidden('foo'))
123
108
 
124
109
    def test_registry_conversion(self):
125
 
        registry = controldir.ControlDirFormatRegistry()
126
 
        bzr.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
127
 
        bzr.register_metadir(
128
 
            registry, 'two', 'RepositoryFormatKnit1', 'two help')
129
 
        bzr.register_metadir(registry, 'hidden', 'RepositoryFormatKnit1',
130
 
                             'two help', hidden=True)
 
110
        registry = bzrdir.BzrDirFormatRegistry()
 
111
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
112
        registry.register_metadir('two', 'RepositoryFormatKnit1', 'two help')
 
113
        registry.register_metadir('hidden', 'RepositoryFormatKnit1',
 
114
            'two help', hidden=True)
131
115
        registry.set_default('one')
132
116
        options = [option.RegistryOption('format', '', registry, str)]
133
117
        opts, args = self.parse(options, ['--format', 'one'])
134
 
        self.assertEqual({'format': 'one'}, opts)
 
118
        self.assertEqual({'format':'one'}, opts)
135
119
        opts, args = self.parse(options, ['--format', 'two'])
136
 
        self.assertEqual({'format': 'two'}, opts)
137
 
        self.assertRaises(option.BadOptionValue, self.parse, options,
 
120
        self.assertEqual({'format':'two'}, opts)
 
121
        self.assertRaises(errors.BadOptionValue, self.parse, options,
138
122
                          ['--format', 'three'])
139
123
        self.assertRaises(errors.BzrCommandError, self.parse, options,
140
124
                          ['--two'])
141
125
        options = [option.RegistryOption('format', '', registry, str,
142
 
                                         value_switches=True)]
 
126
                   value_switches=True)]
143
127
        opts, args = self.parse(options, ['--two'])
144
 
        self.assertEqual({'format': 'two'}, opts)
 
128
        self.assertEqual({'format':'two'}, opts)
145
129
        opts, args = self.parse(options, ['--two', '--one'])
146
 
        self.assertEqual({'format': 'one'}, opts)
 
130
        self.assertEqual({'format':'one'}, opts)
147
131
        opts, args = self.parse(options, ['--two', '--one',
148
132
                                          '--format', 'two'])
149
 
        self.assertEqual({'format': 'two'}, opts)
 
133
        self.assertEqual({'format':'two'}, opts)
150
134
        options = [option.RegistryOption('format', '', registry, str,
151
 
                                         enum_switch=False)]
 
135
                   enum_switch=False)]
152
136
        self.assertRaises(errors.BzrCommandError, self.parse, options,
153
137
                          ['--format', 'two'])
154
138
 
166
150
 
167
151
    def test_registry_converter(self):
168
152
        options = [option.RegistryOption('format', '',
169
 
                                         controldir.format_registry, controldir.format_registry.make_controldir)]
 
153
                   bzrdir.format_registry, bzrdir.format_registry.make_bzrdir)]
170
154
        opts, args = self.parse(options, ['--format', 'knit'])
171
155
        self.assertIsInstance(opts.format.repository_format,
172
156
                              knitrepo.RepositoryFormatKnit1)
173
157
 
174
158
    def test_lazy_registry(self):
175
159
        options = [option.RegistryOption('format', '',
176
 
                                         lazy_registry=(
177
 
                                             'breezy.controldir', 'format_registry'),
178
 
                                         converter=str)]
 
160
                   lazy_registry=('bzrlib.bzrdir','format_registry'),
 
161
                   converter=str)]
179
162
        opts, args = self.parse(options, ['--format', 'knit'])
180
163
        self.assertEqual({'format': 'knit'}, opts)
181
164
        self.assertRaises(
182
 
            option.BadOptionValue, self.parse, options, ['--format', 'BAD'])
 
165
            errors.BadOptionValue, self.parse, options, ['--format', 'BAD'])
183
166
 
184
167
    def test_from_kwargs(self):
185
168
        my_option = option.RegistryOption.from_kwargs('my-option',
186
 
                                                      help='test option', short='be short', be_long='go long')
 
169
            help='test option', short='be short', be_long='go long')
187
170
        self.assertEqual(['my-option'],
188
 
                         [x[0] for x in my_option.iter_switches()])
 
171
            [x[0] for x in my_option.iter_switches()])
189
172
        my_option = option.RegistryOption.from_kwargs('my-option',
190
 
                                                      help='test option', title="My option", short='be short',
191
 
                                                      be_long='go long', value_switches=True)
 
173
            help='test option', title="My option", short='be short',
 
174
            be_long='go long', value_switches=True)
192
175
        self.assertEqual(['my-option', 'be-long', 'short'],
193
 
                         [x[0] for x in my_option.iter_switches()])
 
176
            [x[0] for x in my_option.iter_switches()])
194
177
        self.assertEqual('test option', my_option.help)
195
178
 
196
179
    def test_help(self):
197
 
        registry = controldir.ControlDirFormatRegistry()
198
 
        bzr.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
199
 
        bzr.register_metadir(registry, 'two',
200
 
                             'breezy.bzr.knitrepo.RepositoryFormatKnit1',
201
 
                             'two help',
202
 
                             )
203
 
        bzr.register_metadir(registry, 'hidden', 'RepositoryFormat7', 'hidden help',
204
 
                             hidden=True)
 
180
        registry = bzrdir.BzrDirFormatRegistry()
 
181
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
182
        registry.register_metadir('two',
 
183
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
184
            'two help',
 
185
            )
 
186
        registry.register_metadir('hidden', 'RepositoryFormat7', 'hidden help',
 
187
            hidden=True)
205
188
        registry.set_default('one')
206
189
        options = [option.RegistryOption('format', 'format help', registry,
207
 
                                         str, value_switches=True, title='Formats')]
208
 
        parser = option.get_optparser(options)
 
190
                   str, value_switches=True, title='Formats')]
 
191
        parser = option.get_optparser(dict((o.name, o) for o in options))
209
192
        value = parser.format_option_help()
210
193
        self.assertContainsRe(value, 'format.*format help')
211
194
        self.assertContainsRe(value, 'one.*one help')
222
205
        opt = option.Option('hello', help='fg', type=int, argname='gar')
223
206
        self.assertEqual(list(opt.iter_switches()),
224
207
                         [('hello', None, 'GAR', 'fg')])
225
 
        registry = controldir.ControlDirFormatRegistry()
226
 
        bzr.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
227
 
        bzr.register_metadir(registry, 'two',
228
 
                             'breezy.bzr.knitrepo.RepositoryFormatKnit1',
229
 
                             'two help',
230
 
                             )
 
208
        registry = bzrdir.BzrDirFormatRegistry()
 
209
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
210
        registry.register_metadir('two',
 
211
                'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
212
                'two help',
 
213
                )
231
214
        registry.set_default('one')
232
215
        opt = option.RegistryOption('format', 'format help', registry,
233
216
                                    value_switches=False)
245
228
    def test_option_callback_bool(self):
246
229
        "Test booleans get True and False passed correctly to a callback."""
247
230
        cb_calls = []
248
 
 
249
231
        def cb(option, name, value, parser):
250
 
            cb_calls.append((option, name, value, parser))
 
232
            cb_calls.append((option,name,value,parser))
251
233
        options = [option.Option('hello', custom_callback=cb)]
252
234
        opts, args = self.parse(options, ['--hello', '--no-hello'])
253
235
        self.assertEqual(2, len(cb_calls))
254
 
        opt, name, value, parser = cb_calls[0]
 
236
        opt,name,value,parser = cb_calls[0]
255
237
        self.assertEqual('hello', name)
256
238
        self.assertTrue(value)
257
 
        opt, name, value, parser = cb_calls[1]
 
239
        opt,name,value,parser = cb_calls[1]
258
240
        self.assertEqual('hello', name)
259
241
        self.assertFalse(value)
260
242
 
261
243
    def test_option_callback_str(self):
262
244
        """Test callbacks work for string options both long and short."""
263
245
        cb_calls = []
264
 
 
265
246
        def cb(option, name, value, parser):
266
 
            cb_calls.append((option, name, value, parser))
 
247
            cb_calls.append((option,name,value,parser))
267
248
        options = [option.Option('hello', type=str, custom_callback=cb,
268
 
                                 short_name='h')]
 
249
            short_name='h')]
269
250
        opts, args = self.parse(options, ['--hello', 'world', '-h', 'mars'])
270
251
        self.assertEqual(2, len(cb_calls))
271
 
        opt, name, value, parser = cb_calls[0]
 
252
        opt,name,value,parser = cb_calls[0]
272
253
        self.assertEqual('hello', name)
273
254
        self.assertEqual('world', value)
274
 
        opt, name, value, parser = cb_calls[1]
 
255
        opt,name,value,parser = cb_calls[1]
275
256
        self.assertEqual('hello', name)
276
257
        self.assertEqual('mars', value)
277
258
 
280
261
    """Tests for ListOption, used to specify lists on the command-line."""
281
262
 
282
263
    def parse(self, options, args):
283
 
        parser = option.get_optparser(options)
 
264
        parser = option.get_optparser(dict((o.name, o) for o in options))
284
265
        return parser.parse_args(args)
285
266
 
286
267
    def test_list_option(self):
320
301
    def test_option_callback_list(self):
321
302
        """Test callbacks work for list options."""
322
303
        cb_calls = []
323
 
 
324
304
        def cb(option, name, value, parser):
325
305
            # Note that the value is a reference so copy to keep it
326
 
            cb_calls.append((option, name, value[:], parser))
 
306
            cb_calls.append((option,name,value[:],parser))
327
307
        options = [option.ListOption('hello', type=str, custom_callback=cb)]
328
308
        opts, args = self.parse(options, ['--hello=world', '--hello=mars',
329
 
                                          '--hello=-'])
 
309
            '--hello=-'])
330
310
        self.assertEqual(3, len(cb_calls))
331
 
        opt, name, value, parser = cb_calls[0]
 
311
        opt,name,value,parser = cb_calls[0]
332
312
        self.assertEqual('hello', name)
333
313
        self.assertEqual(['world'], value)
334
 
        opt, name, value, parser = cb_calls[1]
 
314
        opt,name,value,parser = cb_calls[1]
335
315
        self.assertEqual('hello', name)
336
316
        self.assertEqual(['world', 'mars'], value)
337
 
        opt, name, value, parser = cb_calls[2]
 
317
        opt,name,value,parser = cb_calls[2]
338
318
        self.assertEqual('hello', name)
339
319
        self.assertEqual([], value)
340
320
 
351
331
 
352
332
    def get_builtin_command_options(self):
353
333
        g = []
354
 
        commands.install_bzr_command_hooks()
355
 
        for cmd_name in sorted(commands.builtin_command_names()):
 
334
        for cmd_name in sorted(commands.all_command_names()):
356
335
            cmd = commands.get_cmd_object(cmd_name)
357
336
            for opt_name, opt in sorted(cmd.options().items()):
358
337
                g.append((cmd_name, opt))
359
 
        self.assertTrue(g)
360
338
        return g
361
339
 
 
340
    def test_global_options_used(self):
 
341
        # In the distant memory, options could only be declared globally.  Now
 
342
        # we prefer to declare them in the command, unless like -r they really
 
343
        # are used very widely with the exact same meaning.  So this checks
 
344
        # for any that should be garbage collected.
 
345
        g = dict(option.Option.OPTIONS.items())
 
346
        used_globals = {}
 
347
        msgs = []
 
348
        for cmd_name in sorted(commands.all_command_names()):
 
349
            cmd = commands.get_cmd_object(cmd_name)
 
350
            for option_or_name in sorted(cmd.takes_options):
 
351
                if not isinstance(option_or_name, basestring):
 
352
                    self.assertIsInstance(option_or_name, option.Option)
 
353
                elif not option_or_name in g:
 
354
                    msgs.append("apparent reference to undefined "
 
355
                        "global option %r from %r"
 
356
                        % (option_or_name, cmd))
 
357
                else:
 
358
                    used_globals.setdefault(option_or_name, []).append(cmd_name)
 
359
        unused_globals = set(g.keys()) - set(used_globals.keys())
 
360
        # not enforced because there might be plugins that use these globals
 
361
        ## for option_name in sorted(unused_globals):
 
362
        ##    msgs.append("unused global option %r" % option_name)
 
363
        ## for option_name, cmds in sorted(used_globals.items()):
 
364
        ##     if len(cmds) <= 1:
 
365
        ##         msgs.append("global option %r is only used by %r"
 
366
        ##                 % (option_name, cmds))
 
367
        if msgs:
 
368
            self.fail("problems with global option definitions:\n"
 
369
                    + '\n'.join(msgs))
 
370
 
362
371
    def test_option_grammar(self):
363
372
        msgs = []
364
373
        # Option help should be written in sentence form, and have a final
365
 
        # period with an optional bracketed suffix. All the text should be on
366
 
        # one line, because the display code will wrap it.
367
 
        option_re = re.compile(r'^[A-Z][^\n]+\.(?: \([^\n]+\))?$')
 
374
        # period and be all on a single line, because the display code will
 
375
        # wrap it.
 
376
        option_re = re.compile(r'^[A-Z][^\n]+\.$')
368
377
        for scope, opt in self.get_builtin_command_options():
369
 
            for name, _, _, helptxt in opt.iter_switches():
370
 
                if name != opt.name:
371
 
                    name = "/".join([opt.name, name])
372
 
                if not helptxt:
373
 
                    msgs.append('%-16s %-16s %s' %
374
 
                                ((scope or 'GLOBAL'), name, 'NO HELP'))
375
 
                elif not option_re.match(helptxt):
376
 
                    if name.startswith("format/"):
377
 
                        # Don't complain about the odd format registry help
378
 
                        continue
379
 
                    msgs.append('%-16s %-16s %s' %
380
 
                                ((scope or 'GLOBAL'), name, helptxt))
 
378
            if not opt.help:
 
379
                msgs.append('%-16s %-16s %s' %
 
380
                       ((scope or 'GLOBAL'), opt.name, 'NO HELP'))
 
381
            elif not option_re.match(opt.help):
 
382
                msgs.append('%-16s %-16s %s' %
 
383
                        ((scope or 'GLOBAL'), opt.name, opt.help))
381
384
        if msgs:
382
385
            self.fail("The following options don't match the style guide:\n"
383
 
                      + '\n'.join(msgs))
384
 
 
385
 
 
386
 
class TestOptionMisc(TestCase):
 
386
                    + '\n'.join(msgs))
387
387
 
388
388
    def test_is_hidden(self):
389
 
        registry = controldir.ControlDirFormatRegistry()
390
 
        bzr.register_metadir(registry, 'hidden', 'HiddenFormat',
391
 
                             'hidden help text', hidden=True)
392
 
        bzr.register_metadir(registry, 'visible', 'VisibleFormat',
393
 
                             'visible help text', hidden=False)
 
389
        registry = bzrdir.BzrDirFormatRegistry()
 
390
        registry.register_metadir('hidden', 'HiddenFormat',
 
391
            'hidden help text', hidden=True)
 
392
        registry.register_metadir('visible', 'VisibleFormat',
 
393
            'visible help text', hidden=False)
394
394
        format = option.RegistryOption('format', '', registry, str)
395
395
        self.assertTrue(format.is_hidden('hidden'))
396
396
        self.assertFalse(format.is_hidden('visible'))
397
397
 
398
 
    def test_short_name(self):
399
 
        registry = controldir.ControlDirFormatRegistry()
400
 
        opt = option.RegistryOption('format', help='', registry=registry)
401
 
        self.assertEqual(None, opt.short_name())
402
 
        opt = option.RegistryOption('format', short_name='F', help='',
403
 
                                    registry=registry)
404
 
        self.assertEqual('F', opt.short_name())
405
 
 
406
398
    def test_option_custom_help(self):
407
399
        the_opt = option.Option.OPTIONS['help']
408
400
        orig_help = the_opt.help[:]
411
403
        self.assertEqual('suggest lottery numbers', my_opt.help)
412
404
        self.assertEqual(orig_help, the_opt.help)
413
405
 
414
 
    def test_short_value_switches(self):
415
 
        reg = registry.Registry()
416
 
        reg.register('short', 'ShortChoice')
417
 
        reg.register('long', 'LongChoice')
418
 
        ropt = option.RegistryOption('choice', '', reg, value_switches=True,
419
 
                                     short_value_switches={'short': 's'})
420
 
        opts, args = parse([ropt], ['--short'])
421
 
        self.assertEqual('ShortChoice', opts.choice)
422
 
        opts, args = parse([ropt], ['-s'])
423
 
        self.assertEqual('ShortChoice', opts.choice)
424
 
 
425
406
 
426
407
class TestVerboseQuietLinkage(TestCase):
427
408
 
431
412
        self.assertEqual(level, option._verbosity_level)
432
413
 
433
414
    def test_verbose_quiet_linkage(self):
434
 
        parser = option.get_optparser(
435
 
            [v for k, v in sorted(option.Option.STD_OPTIONS.items())])
 
415
        parser = option.get_optparser(option.Option.STD_OPTIONS)
436
416
        self.check(parser, 0, [])
437
417
        self.check(parser, 1, ['-v'])
438
418
        self.check(parser, 2, ['-v', '-v'])