/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: 2017-06-10 16:40:42 UTC
  • mfrom: (6653.6.7 rename-controldir)
  • mto: This revision was merged to the branch mainline in revision 6690.
  • Revision ID: jelmer@jelmer.uk-20170610164042-zrxqgy2htyduvke2
MergeĀ rename-controldirĀ branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2012, 2016 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
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
 
16
 
 
17
import re
 
18
 
 
19
from .. import (
 
20
    commands,
 
21
    controldir,
 
22
    errors,
 
23
    option,
 
24
    registry,
 
25
    )
 
26
from ..bzr import (
 
27
    bzrdir,
 
28
    )
 
29
from ..builtins import cmd_commit
 
30
from ..commands import parse_args
 
31
from . import TestCase
 
32
from ..bzr import knitrepo
 
33
 
 
34
 
 
35
def parse(options, args):
 
36
    parser = option.get_optparser(dict((o.name, o) for o in options))
 
37
    return parser.parse_args(args)
 
38
 
 
39
 
 
40
class OptionTests(TestCase):
 
41
    """Command-line option tests"""
 
42
 
 
43
    def test_parse_args(self):
 
44
        """Option parser"""
 
45
        # XXX: Using cmd_commit makes these tests overly sensitive to changes
 
46
        # to cmd_commit, when they are meant to be about option parsing in
 
47
        # general.
 
48
        self.assertEqual(
 
49
           ([], {'author': [], 'exclude': [], 'fixes': [], 'help': True}),
 
50
           parse_args(cmd_commit(), ['--help']))
 
51
        self.assertEqual(
 
52
           ([], {'author': [], 'exclude': [], 'fixes': [], 'message': 'biter'}),
 
53
           parse_args(cmd_commit(), ['--message=biter']))
 
54
 
 
55
    def test_no_more_opts(self):
 
56
        """Terminated options"""
 
57
        self.assertEqual(
 
58
            (['-file-with-dashes'], {'author': [], 'exclude': [], 'fixes': []}),
 
59
            parse_args(cmd_commit(), ['--', '-file-with-dashes']))
 
60
 
 
61
    def test_option_help(self):
 
62
        """Options have help strings."""
 
63
        out, err = self.run_bzr('commit --help')
 
64
        self.assertContainsRe(out,
 
65
                r'--file(.|\n)*Take commit message from this file\.')
 
66
        self.assertContainsRe(out, r'-h.*--help')
 
67
 
 
68
    def test_option_help_global(self):
 
69
        """Global options have help strings."""
 
70
        out, err = self.run_bzr('help status')
 
71
        self.assertContainsRe(out, r'--show-ids.*Show internal object.')
 
72
 
 
73
    def test_option_help_global_hidden(self):
 
74
        """Hidden global options have no help strings."""
 
75
        out, err = self.run_bzr('help log')
 
76
        self.assertNotContainsRe(out, r'--message')
 
77
 
 
78
    def test_option_arg_help(self):
 
79
        """Help message shows option arguments."""
 
80
        out, err = self.run_bzr('help commit')
 
81
        self.assertEqual(err, '')
 
82
        self.assertContainsRe(out, r'--file[ =]MSGFILE')
 
83
 
 
84
    def test_unknown_short_opt(self):
 
85
        out, err = self.run_bzr('help -r', retcode=3)
 
86
        self.assertContainsRe(err, r'no such option')
 
87
 
 
88
    def test_set_short_name(self):
 
89
        o = option.Option('wiggle')
 
90
        o.set_short_name('w')
 
91
        self.assertEqual(o.short_name(), 'w')
 
92
 
 
93
    def test_allow_dash(self):
 
94
        """Test that we can pass a plain '-' as an argument."""
 
95
        self.assertEqual((['-']), parse_args(cmd_commit(), ['-'])[0])
 
96
 
 
97
    def parse(self, options, args):
 
98
        parser = option.get_optparser(dict((o.name, o) for o in options))
 
99
        return parser.parse_args(args)
 
100
 
 
101
    def test_conversion(self):
 
102
        options = [option.Option('hello')]
 
103
        opts, args = self.parse(options, ['--no-hello', '--hello'])
 
104
        self.assertEqual(True, opts.hello)
 
105
        opts, args = self.parse(options, [])
 
106
        self.assertFalse(hasattr(opts, 'hello'))
 
107
        opts, args = self.parse(options, ['--hello', '--no-hello'])
 
108
        self.assertEqual(False, opts.hello)
 
109
        options = [option.Option('number', type=int)]
 
110
        opts, args = self.parse(options, ['--number', '6'])
 
111
        self.assertEqual(6, opts.number)
 
112
        self.assertRaises(errors.BzrCommandError, self.parse, options,
 
113
                          ['--number'])
 
114
        self.assertRaises(errors.BzrCommandError, self.parse, options,
 
115
                          ['--no-number'])
 
116
 
 
117
    def test_is_hidden(self):
 
118
        self.assertTrue(option.Option('foo', hidden=True).is_hidden('foo'))
 
119
        self.assertFalse(option.Option('foo', hidden=False).is_hidden('foo'))
 
120
 
 
121
    def test_registry_conversion(self):
 
122
        registry = controldir.ControlDirFormatRegistry()
 
123
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
 
124
        bzrdir.register_metadir(registry, 'two', 'RepositoryFormatKnit1', 'two help')
 
125
        bzrdir.register_metadir(registry, 'hidden', 'RepositoryFormatKnit1',
 
126
            'two help', hidden=True)
 
127
        registry.set_default('one')
 
128
        options = [option.RegistryOption('format', '', registry, str)]
 
129
        opts, args = self.parse(options, ['--format', 'one'])
 
130
        self.assertEqual({'format':'one'}, opts)
 
131
        opts, args = self.parse(options, ['--format', 'two'])
 
132
        self.assertEqual({'format':'two'}, opts)
 
133
        self.assertRaises(errors.BadOptionValue, self.parse, options,
 
134
                          ['--format', 'three'])
 
135
        self.assertRaises(errors.BzrCommandError, self.parse, options,
 
136
                          ['--two'])
 
137
        options = [option.RegistryOption('format', '', registry, str,
 
138
                   value_switches=True)]
 
139
        opts, args = self.parse(options, ['--two'])
 
140
        self.assertEqual({'format':'two'}, opts)
 
141
        opts, args = self.parse(options, ['--two', '--one'])
 
142
        self.assertEqual({'format':'one'}, opts)
 
143
        opts, args = self.parse(options, ['--two', '--one',
 
144
                                          '--format', 'two'])
 
145
        self.assertEqual({'format':'two'}, opts)
 
146
        options = [option.RegistryOption('format', '', registry, str,
 
147
                   enum_switch=False)]
 
148
        self.assertRaises(errors.BzrCommandError, self.parse, options,
 
149
                          ['--format', 'two'])
 
150
 
 
151
    def test_override(self):
 
152
        options = [option.Option('hello', type=str),
 
153
                   option.Option('hi', type=str, param_name='hello')]
 
154
        opts, args = self.parse(options, ['--hello', 'a', '--hello', 'b'])
 
155
        self.assertEqual('b', opts.hello)
 
156
        opts, args = self.parse(options, ['--hello', 'b', '--hello', 'a'])
 
157
        self.assertEqual('a', opts.hello)
 
158
        opts, args = self.parse(options, ['--hello', 'a', '--hi', 'b'])
 
159
        self.assertEqual('b', opts.hello)
 
160
        opts, args = self.parse(options, ['--hi', 'b', '--hello', 'a'])
 
161
        self.assertEqual('a', opts.hello)
 
162
 
 
163
    def test_registry_converter(self):
 
164
        options = [option.RegistryOption('format', '',
 
165
                   controldir.format_registry, controldir.format_registry.make_controldir)]
 
166
        opts, args = self.parse(options, ['--format', 'knit'])
 
167
        self.assertIsInstance(opts.format.repository_format,
 
168
                              knitrepo.RepositoryFormatKnit1)
 
169
 
 
170
    def test_lazy_registry(self):
 
171
        options = [option.RegistryOption('format', '',
 
172
                   lazy_registry=('breezy.controldir','format_registry'),
 
173
                   converter=str)]
 
174
        opts, args = self.parse(options, ['--format', 'knit'])
 
175
        self.assertEqual({'format': 'knit'}, opts)
 
176
        self.assertRaises(
 
177
            errors.BadOptionValue, self.parse, options, ['--format', 'BAD'])
 
178
 
 
179
    def test_from_kwargs(self):
 
180
        my_option = option.RegistryOption.from_kwargs('my-option',
 
181
            help='test option', short='be short', be_long='go long')
 
182
        self.assertEqual(['my-option'],
 
183
            [x[0] for x in my_option.iter_switches()])
 
184
        my_option = option.RegistryOption.from_kwargs('my-option',
 
185
            help='test option', title="My option", short='be short',
 
186
            be_long='go long', value_switches=True)
 
187
        self.assertEqual(['my-option', 'be-long', 'short'],
 
188
            [x[0] for x in my_option.iter_switches()])
 
189
        self.assertEqual('test option', my_option.help)
 
190
 
 
191
    def test_help(self):
 
192
        registry = controldir.ControlDirFormatRegistry()
 
193
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
 
194
        bzrdir.register_metadir(registry, 'two',
 
195
            'breezy.bzr.knitrepo.RepositoryFormatKnit1',
 
196
            'two help',
 
197
            )
 
198
        bzrdir.register_metadir(registry, 'hidden', 'RepositoryFormat7', 'hidden help',
 
199
            hidden=True)
 
200
        registry.set_default('one')
 
201
        options = [option.RegistryOption('format', 'format help', registry,
 
202
                   str, value_switches=True, title='Formats')]
 
203
        parser = option.get_optparser(dict((o.name, o) for o in options))
 
204
        value = parser.format_option_help()
 
205
        self.assertContainsRe(value, 'format.*format help')
 
206
        self.assertContainsRe(value, 'one.*one help')
 
207
        self.assertContainsRe(value, 'Formats:\n *--format')
 
208
        self.assertNotContainsRe(value, 'hidden help')
 
209
 
 
210
    def test_iter_switches(self):
 
211
        opt = option.Option('hello', help='fg')
 
212
        self.assertEqual(list(opt.iter_switches()),
 
213
                         [('hello', None, None, 'fg')])
 
214
        opt = option.Option('hello', help='fg', type=int)
 
215
        self.assertEqual(list(opt.iter_switches()),
 
216
                         [('hello', None, 'ARG', 'fg')])
 
217
        opt = option.Option('hello', help='fg', type=int, argname='gar')
 
218
        self.assertEqual(list(opt.iter_switches()),
 
219
                         [('hello', None, 'GAR', 'fg')])
 
220
        registry = controldir.ControlDirFormatRegistry()
 
221
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
 
222
        bzrdir.register_metadir(registry, 'two',
 
223
                'breezy.bzr.knitrepo.RepositoryFormatKnit1',
 
224
                'two help',
 
225
                )
 
226
        registry.set_default('one')
 
227
        opt = option.RegistryOption('format', 'format help', registry,
 
228
                                    value_switches=False)
 
229
        self.assertEqual(list(opt.iter_switches()),
 
230
                         [('format', None, 'ARG', 'format help')])
 
231
        opt = option.RegistryOption('format', 'format help', registry,
 
232
                                    value_switches=True)
 
233
        self.assertEqual(list(opt.iter_switches()),
 
234
                         [('format', None, 'ARG', 'format help'),
 
235
                          ('default', None, None, 'one help'),
 
236
                          ('one', None, None, 'one help'),
 
237
                          ('two', None, None, 'two help'),
 
238
                          ])
 
239
 
 
240
    def test_option_callback_bool(self):
 
241
        "Test booleans get True and False passed correctly to a callback."""
 
242
        cb_calls = []
 
243
        def cb(option, name, value, parser):
 
244
            cb_calls.append((option,name,value,parser))
 
245
        options = [option.Option('hello', custom_callback=cb)]
 
246
        opts, args = self.parse(options, ['--hello', '--no-hello'])
 
247
        self.assertEqual(2, len(cb_calls))
 
248
        opt,name,value,parser = cb_calls[0]
 
249
        self.assertEqual('hello', name)
 
250
        self.assertTrue(value)
 
251
        opt,name,value,parser = cb_calls[1]
 
252
        self.assertEqual('hello', name)
 
253
        self.assertFalse(value)
 
254
 
 
255
    def test_option_callback_str(self):
 
256
        """Test callbacks work for string options both long and short."""
 
257
        cb_calls = []
 
258
        def cb(option, name, value, parser):
 
259
            cb_calls.append((option,name,value,parser))
 
260
        options = [option.Option('hello', type=str, custom_callback=cb,
 
261
            short_name='h')]
 
262
        opts, args = self.parse(options, ['--hello', 'world', '-h', 'mars'])
 
263
        self.assertEqual(2, len(cb_calls))
 
264
        opt,name,value,parser = cb_calls[0]
 
265
        self.assertEqual('hello', name)
 
266
        self.assertEqual('world', value)
 
267
        opt,name,value,parser = cb_calls[1]
 
268
        self.assertEqual('hello', name)
 
269
        self.assertEqual('mars', value)
 
270
 
 
271
 
 
272
class TestListOptions(TestCase):
 
273
    """Tests for ListOption, used to specify lists on the command-line."""
 
274
 
 
275
    def parse(self, options, args):
 
276
        parser = option.get_optparser(dict((o.name, o) for o in options))
 
277
        return parser.parse_args(args)
 
278
 
 
279
    def test_list_option(self):
 
280
        options = [option.ListOption('hello', type=str)]
 
281
        opts, args = self.parse(options, ['--hello=world', '--hello=sailor'])
 
282
        self.assertEqual(['world', 'sailor'], opts.hello)
 
283
 
 
284
    def test_list_option_with_dash(self):
 
285
        options = [option.ListOption('with-dash', type=str)]
 
286
        opts, args = self.parse(options, ['--with-dash=world',
 
287
                                          '--with-dash=sailor'])
 
288
        self.assertEqual(['world', 'sailor'], opts.with_dash)
 
289
 
 
290
    def test_list_option_no_arguments(self):
 
291
        options = [option.ListOption('hello', type=str)]
 
292
        opts, args = self.parse(options, [])
 
293
        self.assertEqual([], opts.hello)
 
294
 
 
295
    def test_list_option_with_int_type(self):
 
296
        options = [option.ListOption('hello', type=int)]
 
297
        opts, args = self.parse(options, ['--hello=2', '--hello=3'])
 
298
        self.assertEqual([2, 3], opts.hello)
 
299
 
 
300
    def test_list_option_with_int_type_can_be_reset(self):
 
301
        options = [option.ListOption('hello', type=int)]
 
302
        opts, args = self.parse(options, ['--hello=2', '--hello=3',
 
303
                                          '--hello=-', '--hello=5'])
 
304
        self.assertEqual([5], opts.hello)
 
305
 
 
306
    def test_list_option_can_be_reset(self):
 
307
        """Passing an option of '-' to a list option should reset the list."""
 
308
        options = [option.ListOption('hello', type=str)]
 
309
        opts, args = self.parse(
 
310
            options, ['--hello=a', '--hello=b', '--hello=-', '--hello=c'])
 
311
        self.assertEqual(['c'], opts.hello)
 
312
 
 
313
    def test_option_callback_list(self):
 
314
        """Test callbacks work for list options."""
 
315
        cb_calls = []
 
316
        def cb(option, name, value, parser):
 
317
            # Note that the value is a reference so copy to keep it
 
318
            cb_calls.append((option,name,value[:],parser))
 
319
        options = [option.ListOption('hello', type=str, custom_callback=cb)]
 
320
        opts, args = self.parse(options, ['--hello=world', '--hello=mars',
 
321
            '--hello=-'])
 
322
        self.assertEqual(3, len(cb_calls))
 
323
        opt,name,value,parser = cb_calls[0]
 
324
        self.assertEqual('hello', name)
 
325
        self.assertEqual(['world'], value)
 
326
        opt,name,value,parser = cb_calls[1]
 
327
        self.assertEqual('hello', name)
 
328
        self.assertEqual(['world', 'mars'], value)
 
329
        opt,name,value,parser = cb_calls[2]
 
330
        self.assertEqual('hello', name)
 
331
        self.assertEqual([], value)
 
332
 
 
333
    def test_list_option_param_name(self):
 
334
        """Test list options can have their param_name set."""
 
335
        options = [option.ListOption('hello', type=str, param_name='greeting')]
 
336
        opts, args = self.parse(
 
337
            options, ['--hello=world', '--hello=sailor'])
 
338
        self.assertEqual(['world', 'sailor'], opts.greeting)
 
339
 
 
340
 
 
341
class TestOptionDefinitions(TestCase):
 
342
    """Tests for options in the Bazaar codebase."""
 
343
 
 
344
    def get_builtin_command_options(self):
 
345
        g = []
 
346
        commands.install_bzr_command_hooks()
 
347
        for cmd_name in sorted(commands.builtin_command_names()):
 
348
            cmd = commands.get_cmd_object(cmd_name)
 
349
            for opt_name, opt in sorted(cmd.options().items()):
 
350
                g.append((cmd_name, opt))
 
351
        self.assertTrue(g)
 
352
        return g
 
353
 
 
354
    def test_option_grammar(self):
 
355
        msgs = []
 
356
        # Option help should be written in sentence form, and have a final
 
357
        # period with an optional bracketed suffix. All the text should be on
 
358
        # one line, because the display code will wrap it.
 
359
        option_re = re.compile(r'^[A-Z][^\n]+\.(?: \([^\n]+\))?$')
 
360
        for scope, opt in self.get_builtin_command_options():
 
361
            for name, _, _, helptxt in opt.iter_switches():
 
362
                if name != opt.name:
 
363
                    name = "/".join([opt.name, name])
 
364
                if not helptxt:
 
365
                    msgs.append('%-16s %-16s %s' %
 
366
                           ((scope or 'GLOBAL'), name, 'NO HELP'))
 
367
                elif not option_re.match(helptxt):
 
368
                    if name.startswith("format/"):
 
369
                        # Don't complain about the odd format registry help
 
370
                        continue
 
371
                    msgs.append('%-16s %-16s %s' %
 
372
                            ((scope or 'GLOBAL'), name, helptxt))
 
373
        if msgs:
 
374
            self.fail("The following options don't match the style guide:\n"
 
375
                    + '\n'.join(msgs))
 
376
 
 
377
 
 
378
class TestOptionMisc(TestCase):
 
379
 
 
380
    def test_is_hidden(self):
 
381
        registry = controldir.ControlDirFormatRegistry()
 
382
        bzrdir.register_metadir(registry, 'hidden', 'HiddenFormat',
 
383
            'hidden help text', hidden=True)
 
384
        bzrdir.register_metadir(registry, 'visible', 'VisibleFormat',
 
385
            'visible help text', hidden=False)
 
386
        format = option.RegistryOption('format', '', registry, str)
 
387
        self.assertTrue(format.is_hidden('hidden'))
 
388
        self.assertFalse(format.is_hidden('visible'))
 
389
 
 
390
    def test_short_name(self):
 
391
        registry = controldir.ControlDirFormatRegistry()
 
392
        opt = option.RegistryOption('format', help='', registry=registry)
 
393
        self.assertEqual(None, opt.short_name())
 
394
        opt = option.RegistryOption('format', short_name='F', help='',
 
395
            registry=registry)
 
396
        self.assertEqual('F', opt.short_name())
 
397
 
 
398
    def test_option_custom_help(self):
 
399
        the_opt = option.Option.OPTIONS['help']
 
400
        orig_help = the_opt.help[:]
 
401
        my_opt = option.custom_help('help', 'suggest lottery numbers')
 
402
        # Confirm that my_opt has my help and the original is unchanged
 
403
        self.assertEqual('suggest lottery numbers', my_opt.help)
 
404
        self.assertEqual(orig_help, the_opt.help)
 
405
 
 
406
    def test_short_value_switches(self):
 
407
        reg = registry.Registry()
 
408
        reg.register('short', 'ShortChoice')
 
409
        reg.register('long', 'LongChoice')
 
410
        ropt = option.RegistryOption('choice', '', reg, value_switches=True,
 
411
            short_value_switches={'short': 's'})
 
412
        opts, args = parse([ropt], ['--short'])
 
413
        self.assertEqual('ShortChoice', opts.choice)
 
414
        opts, args = parse([ropt], ['-s'])
 
415
        self.assertEqual('ShortChoice', opts.choice)
 
416
 
 
417
 
 
418
class TestVerboseQuietLinkage(TestCase):
 
419
 
 
420
    def check(self, parser, level, args):
 
421
        option._verbosity_level = 0
 
422
        opts, args = parser.parse_args(args)
 
423
        self.assertEqual(level, option._verbosity_level)
 
424
 
 
425
    def test_verbose_quiet_linkage(self):
 
426
        parser = option.get_optparser(option.Option.STD_OPTIONS)
 
427
        self.check(parser, 0, [])
 
428
        self.check(parser, 1, ['-v'])
 
429
        self.check(parser, 2, ['-v', '-v'])
 
430
        self.check(parser, -1, ['-q'])
 
431
        self.check(parser, -2, ['-qq'])
 
432
        self.check(parser, -1, ['-v', '-v', '-q'])
 
433
        self.check(parser, 2, ['-q', '-v', '-v'])
 
434
        self.check(parser, 0, ['--no-verbose'])
 
435
        self.check(parser, 0, ['-v', '-q', '--no-quiet'])