/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 breezy/tests/test_options.py

  • Committer: Jelmer Vernooij
  • Date: 2018-11-17 17:17:02 UTC
  • mto: This revision was merged to the branch mainline in revision 7187.
  • Revision ID: jelmer@jelmer.uk-20181117171702-4tm0yznbaw3rq3es
More beees.

Show diffs side-by-side

added added

removed removed

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