/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: 2020-04-05 19:11:34 UTC
  • mto: (7490.7.16 work)
  • mto: This revision was merged to the branch mainline in revision 7501.
  • Revision ID: jelmer@jelmer.uk-20200405191134-0aebh8ikiwygxma5
Populate the .gitignore file.

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):
101
114
                          ['--number'])
102
115
        self.assertRaises(errors.BzrCommandError, self.parse, options,
103
116
                          ['--no-number'])
 
117
        self.assertRaises(errors.BzrCommandError, self.parse, options,
 
118
                          ['--number', 'a'])
104
119
 
105
120
    def test_is_hidden(self):
106
121
        self.assertTrue(option.Option('foo', hidden=True).is_hidden('foo'))
107
122
        self.assertFalse(option.Option('foo', hidden=False).is_hidden('foo'))
108
123
 
109
124
    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)
 
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)
115
131
        registry.set_default('one')
116
132
        options = [option.RegistryOption('format', '', registry, str)]
117
133
        opts, args = self.parse(options, ['--format', 'one'])
118
 
        self.assertEqual({'format':'one'}, opts)
 
134
        self.assertEqual({'format': 'one'}, opts)
119
135
        opts, args = self.parse(options, ['--format', 'two'])
120
 
        self.assertEqual({'format':'two'}, opts)
121
 
        self.assertRaises(errors.BadOptionValue, self.parse, options,
 
136
        self.assertEqual({'format': 'two'}, opts)
 
137
        self.assertRaises(option.BadOptionValue, self.parse, options,
122
138
                          ['--format', 'three'])
123
139
        self.assertRaises(errors.BzrCommandError, self.parse, options,
124
140
                          ['--two'])
125
141
        options = [option.RegistryOption('format', '', registry, str,
126
 
                   value_switches=True)]
 
142
                                         value_switches=True)]
127
143
        opts, args = self.parse(options, ['--two'])
128
 
        self.assertEqual({'format':'two'}, opts)
 
144
        self.assertEqual({'format': 'two'}, opts)
129
145
        opts, args = self.parse(options, ['--two', '--one'])
130
 
        self.assertEqual({'format':'one'}, opts)
 
146
        self.assertEqual({'format': 'one'}, opts)
131
147
        opts, args = self.parse(options, ['--two', '--one',
132
148
                                          '--format', 'two'])
133
 
        self.assertEqual({'format':'two'}, opts)
 
149
        self.assertEqual({'format': 'two'}, opts)
134
150
        options = [option.RegistryOption('format', '', registry, str,
135
 
                   enum_switch=False)]
 
151
                                         enum_switch=False)]
136
152
        self.assertRaises(errors.BzrCommandError, self.parse, options,
137
153
                          ['--format', 'two'])
138
154
 
150
166
 
151
167
    def test_registry_converter(self):
152
168
        options = [option.RegistryOption('format', '',
153
 
                   bzrdir.format_registry, bzrdir.format_registry.make_bzrdir)]
 
169
                                         controldir.format_registry, controldir.format_registry.make_controldir)]
154
170
        opts, args = self.parse(options, ['--format', 'knit'])
155
171
        self.assertIsInstance(opts.format.repository_format,
156
172
                              knitrepo.RepositoryFormatKnit1)
157
173
 
158
174
    def test_lazy_registry(self):
159
175
        options = [option.RegistryOption('format', '',
160
 
                   lazy_registry=('bzrlib.bzrdir','format_registry'),
161
 
                   converter=str)]
 
176
                                         lazy_registry=(
 
177
                                             'breezy.controldir', 'format_registry'),
 
178
                                         converter=str)]
162
179
        opts, args = self.parse(options, ['--format', 'knit'])
163
180
        self.assertEqual({'format': 'knit'}, opts)
164
181
        self.assertRaises(
165
 
            errors.BadOptionValue, self.parse, options, ['--format', 'BAD'])
 
182
            option.BadOptionValue, self.parse, options, ['--format', 'BAD'])
166
183
 
167
184
    def test_from_kwargs(self):
168
185
        my_option = option.RegistryOption.from_kwargs('my-option',
169
 
            help='test option', short='be short', be_long='go long')
 
186
                                                      help='test option', short='be short', be_long='go long')
170
187
        self.assertEqual(['my-option'],
171
 
            [x[0] for x in my_option.iter_switches()])
 
188
                         [x[0] for x in my_option.iter_switches()])
172
189
        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)
 
190
                                                      help='test option', title="My option", short='be short',
 
191
                                                      be_long='go long', value_switches=True)
175
192
        self.assertEqual(['my-option', 'be-long', 'short'],
176
 
            [x[0] for x in my_option.iter_switches()])
 
193
                         [x[0] for x in my_option.iter_switches()])
177
194
        self.assertEqual('test option', my_option.help)
178
195
 
179
196
    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)
 
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)
188
205
        registry.set_default('one')
189
206
        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))
 
207
                                         str, value_switches=True, title='Formats')]
 
208
        parser = option.get_optparser(options)
192
209
        value = parser.format_option_help()
193
210
        self.assertContainsRe(value, 'format.*format help')
194
211
        self.assertContainsRe(value, 'one.*one help')
205
222
        opt = option.Option('hello', help='fg', type=int, argname='gar')
206
223
        self.assertEqual(list(opt.iter_switches()),
207
224
                         [('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
 
                )
 
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
                             )
214
231
        registry.set_default('one')
215
232
        opt = option.RegistryOption('format', 'format help', registry,
216
233
                                    value_switches=False)
228
245
    def test_option_callback_bool(self):
229
246
        "Test booleans get True and False passed correctly to a callback."""
230
247
        cb_calls = []
 
248
 
231
249
        def cb(option, name, value, parser):
232
 
            cb_calls.append((option,name,value,parser))
 
250
            cb_calls.append((option, name, value, parser))
233
251
        options = [option.Option('hello', custom_callback=cb)]
234
252
        opts, args = self.parse(options, ['--hello', '--no-hello'])
235
253
        self.assertEqual(2, len(cb_calls))
236
 
        opt,name,value,parser = cb_calls[0]
 
254
        opt, name, value, parser = cb_calls[0]
237
255
        self.assertEqual('hello', name)
238
256
        self.assertTrue(value)
239
 
        opt,name,value,parser = cb_calls[1]
 
257
        opt, name, value, parser = cb_calls[1]
240
258
        self.assertEqual('hello', name)
241
259
        self.assertFalse(value)
242
260
 
243
261
    def test_option_callback_str(self):
244
262
        """Test callbacks work for string options both long and short."""
245
263
        cb_calls = []
 
264
 
246
265
        def cb(option, name, value, parser):
247
 
            cb_calls.append((option,name,value,parser))
 
266
            cb_calls.append((option, name, value, parser))
248
267
        options = [option.Option('hello', type=str, custom_callback=cb,
249
 
            short_name='h')]
 
268
                                 short_name='h')]
250
269
        opts, args = self.parse(options, ['--hello', 'world', '-h', 'mars'])
251
270
        self.assertEqual(2, len(cb_calls))
252
 
        opt,name,value,parser = cb_calls[0]
 
271
        opt, name, value, parser = cb_calls[0]
253
272
        self.assertEqual('hello', name)
254
273
        self.assertEqual('world', value)
255
 
        opt,name,value,parser = cb_calls[1]
 
274
        opt, name, value, parser = cb_calls[1]
256
275
        self.assertEqual('hello', name)
257
276
        self.assertEqual('mars', value)
258
277
 
261
280
    """Tests for ListOption, used to specify lists on the command-line."""
262
281
 
263
282
    def parse(self, options, args):
264
 
        parser = option.get_optparser(dict((o.name, o) for o in options))
 
283
        parser = option.get_optparser(options)
265
284
        return parser.parse_args(args)
266
285
 
267
286
    def test_list_option(self):
301
320
    def test_option_callback_list(self):
302
321
        """Test callbacks work for list options."""
303
322
        cb_calls = []
 
323
 
304
324
        def cb(option, name, value, parser):
305
325
            # Note that the value is a reference so copy to keep it
306
 
            cb_calls.append((option,name,value[:],parser))
 
326
            cb_calls.append((option, name, value[:], parser))
307
327
        options = [option.ListOption('hello', type=str, custom_callback=cb)]
308
328
        opts, args = self.parse(options, ['--hello=world', '--hello=mars',
309
 
            '--hello=-'])
 
329
                                          '--hello=-'])
310
330
        self.assertEqual(3, len(cb_calls))
311
 
        opt,name,value,parser = cb_calls[0]
 
331
        opt, name, value, parser = cb_calls[0]
312
332
        self.assertEqual('hello', name)
313
333
        self.assertEqual(['world'], value)
314
 
        opt,name,value,parser = cb_calls[1]
 
334
        opt, name, value, parser = cb_calls[1]
315
335
        self.assertEqual('hello', name)
316
336
        self.assertEqual(['world', 'mars'], value)
317
 
        opt,name,value,parser = cb_calls[2]
 
337
        opt, name, value, parser = cb_calls[2]
318
338
        self.assertEqual('hello', name)
319
339
        self.assertEqual([], value)
320
340
 
331
351
 
332
352
    def get_builtin_command_options(self):
333
353
        g = []
334
 
        for cmd_name in sorted(commands.all_command_names()):
 
354
        commands.install_bzr_command_hooks()
 
355
        for cmd_name in sorted(commands.builtin_command_names()):
335
356
            cmd = commands.get_cmd_object(cmd_name)
336
357
            for opt_name, opt in sorted(cmd.options().items()):
337
358
                g.append((cmd_name, opt))
 
359
        self.assertTrue(g)
338
360
        return g
339
361
 
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
362
    def test_option_grammar(self):
372
363
        msgs = []
373
364
        # 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]+\.$')
 
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]+\))?$')
377
368
        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))
 
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))
384
381
        if msgs:
385
382
            self.fail("The following options don't match the style guide:\n"
386
 
                    + '\n'.join(msgs))
 
383
                      + '\n'.join(msgs))
 
384
 
 
385
 
 
386
class TestOptionMisc(TestCase):
387
387
 
388
388
    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)
 
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)
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
 
398
406
    def test_option_custom_help(self):
399
407
        the_opt = option.Option.OPTIONS['help']
400
408
        orig_help = the_opt.help[:]
403
411
        self.assertEqual('suggest lottery numbers', my_opt.help)
404
412
        self.assertEqual(orig_help, the_opt.help)
405
413
 
 
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
 
406
425
 
407
426
class TestVerboseQuietLinkage(TestCase):
408
427
 
412
431
        self.assertEqual(level, option._verbosity_level)
413
432
 
414
433
    def test_verbose_quiet_linkage(self):
415
 
        parser = option.get_optparser(option.Option.STD_OPTIONS)
 
434
        parser = option.get_optparser(
 
435
            [v for k, v in sorted(option.Option.STD_OPTIONS.items())])
416
436
        self.check(parser, 0, [])
417
437
        self.check(parser, 1, ['-v'])
418
438
        self.check(parser, 2, ['-v', '-v'])