~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_options.py

  • Committer: Robert Collins
  • Date: 2007-04-19 02:27:44 UTC
  • mto: This revision was merged to the branch mainline in revision 2426.
  • Revision ID: robertc@robertcollins.net-20070419022744-pfdqz42kp1wizh43
``make docs`` now creates a man page at ``man1/bzr.1`` fixing bug 107388.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 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
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
import re
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
16
 
19
17
from bzrlib import (
 
18
    builtins,
20
19
    bzrdir,
21
 
    commands,
22
 
    controldir,
23
20
    errors,
24
21
    option,
 
22
    repository,
 
23
    symbol_versioning,
25
24
    )
26
 
from bzrlib.builtins import cmd_commit
27
 
from bzrlib.commands import parse_args
 
25
from bzrlib.builtins import cmd_commit, cmd_log, cmd_status
 
26
from bzrlib.commands import Command, parse_args
28
27
from bzrlib.tests import TestCase
29
28
from bzrlib.repofmt import knitrepo
30
29
 
31
 
 
32
30
def parse(options, args):
33
31
    parser = option.get_optparser(dict((o.name, o) for o in options))
34
32
    return parser.parse_args(args)
35
33
 
36
 
 
37
34
class OptionTests(TestCase):
38
35
    """Command-line option tests"""
39
36
 
40
37
    def test_parse_args(self):
41
38
        """Option parser"""
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'}))
 
39
        eq = self.assertEquals
 
40
        eq(parse_args(cmd_commit(), ['--help']),
 
41
           ([], {'help': True}))
 
42
        eq(parse_args(cmd_commit(), ['--message=biter']),
 
43
           ([], {'message': 'biter'}))
 
44
        ## eq(parse_args(cmd_log(),  '-r 500'.split()),
 
45
        ##   ([], {'revision': RevisionSpec_int(500)}))
49
46
 
50
47
    def test_no_more_opts(self):
51
48
        """Terminated options"""
52
 
        self.assertEqual(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
53
 
                          (['-file-with-dashes'], {'author': [], 'exclude': [], 'fixes': []}))
 
49
        self.assertEquals(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
 
50
                          (['-file-with-dashes'], {}))
54
51
 
55
52
    def test_option_help(self):
56
53
        """Options have help strings."""
57
 
        out, err = self.run_bzr('commit --help')
58
 
        self.assertContainsRe(out,
59
 
                r'--file(.|\n)*Take commit message from this file\.')
 
54
        out, err = self.run_bzr_captured(['commit', '--help'])
 
55
        self.assertContainsRe(out, r'--file(.|\n)*file containing commit'
 
56
                                   ' message')
60
57
        self.assertContainsRe(out, r'-h.*--help')
61
58
 
62
59
    def test_option_help_global(self):
63
60
        """Global options have help strings."""
64
 
        out, err = self.run_bzr('help status')
65
 
        self.assertContainsRe(out, r'--show-ids.*Show internal object.')
 
61
        out, err = self.run_bzr_captured(['help', 'status'])
 
62
        self.assertContainsRe(out, r'--show-ids.*show internal object')
66
63
 
67
64
    def test_option_arg_help(self):
68
65
        """Help message shows option arguments."""
69
 
        out, err = self.run_bzr('help commit')
70
 
        self.assertEqual(err, '')
 
66
        out, err = self.run_bzr_captured(['help', 'commit'])
 
67
        self.assertEquals(err, '')
71
68
        self.assertContainsRe(out, r'--file[ =]MSGFILE')
72
69
 
73
70
    def test_unknown_short_opt(self):
74
 
        out, err = self.run_bzr('help -r', retcode=3)
 
71
        out, err = self.run_bzr_captured(['help', '-r'], retcode=3)
75
72
        self.assertContainsRe(err, r'no such option')
76
73
 
 
74
    def test_get_short_name(self):
 
75
        file_opt = option.Option.OPTIONS['file']
 
76
        self.assertEquals(file_opt.short_name(), 'F')
 
77
        force_opt = option.Option.OPTIONS['force']
 
78
        self.assertEquals(force_opt.short_name(), None)
 
79
 
77
80
    def test_set_short_name(self):
78
81
        o = option.Option('wiggle')
79
82
        o.set_short_name('w')
80
83
        self.assertEqual(o.short_name(), 'w')
81
84
 
 
85
    def test_old_short_names(self):
 
86
        # test the deprecated method for getting and setting short option
 
87
        # names
 
88
        expected_warning = (
 
89
            "access to SHORT_OPTIONS was deprecated in version 0.14."
 
90
            " Set the short option name when constructing the Option.",
 
91
            DeprecationWarning, 2)
 
92
        _warnings = []
 
93
        def capture_warning(message, category, stacklevel=None):
 
94
            _warnings.append((message, category, stacklevel))
 
95
        old_warning_method = symbol_versioning.warn
 
96
        try:
 
97
            # an example of the kind of thing plugins might want to do through
 
98
            # the old interface - make a new option and then give it a short
 
99
            # name.
 
100
            symbol_versioning.set_warning_method(capture_warning)
 
101
            example_opt = option.Option('example', help='example option')
 
102
            option.Option.SHORT_OPTIONS['w'] = example_opt
 
103
            self.assertEqual(example_opt.short_name(), 'w')
 
104
            self.assertEqual([expected_warning], _warnings)
 
105
            # now check that it can actually be parsed with the registered
 
106
            # value
 
107
            opts, args = parse([example_opt], ['-w', 'foo'])
 
108
            self.assertEqual(opts.example, True)
 
109
            self.assertEqual(args, ['foo'])
 
110
        finally:
 
111
            symbol_versioning.set_warning_method(old_warning_method)
 
112
 
82
113
    def test_allow_dash(self):
83
114
        """Test that we can pass a plain '-' as an argument."""
84
 
        self.assertEqual((['-']), parse_args(cmd_commit(), ['-'])[0])
 
115
        self.assertEqual((['-'], {}), parse_args(cmd_commit(), ['-']))
85
116
 
86
117
    def parse(self, options, args):
87
118
        parser = option.get_optparser(dict((o.name, o) for o in options))
92
123
        opts, args = self.parse(options, ['--no-hello', '--hello'])
93
124
        self.assertEqual(True, opts.hello)
94
125
        opts, args = self.parse(options, [])
95
 
        self.assertFalse(hasattr(opts, 'hello'))
 
126
        self.assertEqual(option.OptionParser.DEFAULT_VALUE, opts.hello)
96
127
        opts, args = self.parse(options, ['--hello', '--no-hello'])
97
128
        self.assertEqual(False, opts.hello)
98
129
        options = [option.Option('number', type=int)]
103
134
        self.assertRaises(errors.BzrCommandError, self.parse, options,
104
135
                          ['--no-number'])
105
136
 
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
 
 
110
137
    def test_registry_conversion(self):
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',
 
138
        registry = bzrdir.BzrDirFormatRegistry()
 
139
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
140
        registry.register_metadir('two', 'RepositoryFormatKnit1', 'two help')
 
141
        registry.register_metadir('hidden', 'RepositoryFormatKnit1',
115
142
            'two help', hidden=True)
116
143
        registry.set_default('one')
117
144
        options = [option.RegistryOption('format', '', registry, str)]
137
164
        self.assertRaises(errors.BzrCommandError, self.parse, options,
138
165
                          ['--format', 'two'])
139
166
 
140
 
    def test_override(self):
141
 
        options = [option.Option('hello', type=str),
142
 
                   option.Option('hi', type=str, param_name='hello')]
143
 
        opts, args = self.parse(options, ['--hello', 'a', '--hello', 'b'])
144
 
        self.assertEqual('b', opts.hello)
145
 
        opts, args = self.parse(options, ['--hello', 'b', '--hello', 'a'])
146
 
        self.assertEqual('a', opts.hello)
147
 
        opts, args = self.parse(options, ['--hello', 'a', '--hi', 'b'])
148
 
        self.assertEqual('b', opts.hello)
149
 
        opts, args = self.parse(options, ['--hi', 'b', '--hello', 'a'])
150
 
        self.assertEqual('a', opts.hello)
151
 
 
152
167
    def test_registry_converter(self):
153
168
        options = [option.RegistryOption('format', '',
154
169
                   bzrdir.format_registry, bzrdir.format_registry.make_bzrdir)]
156
171
        self.assertIsInstance(opts.format.repository_format,
157
172
                              knitrepo.RepositoryFormatKnit1)
158
173
 
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
 
 
168
174
    def test_from_kwargs(self):
169
175
        my_option = option.RegistryOption.from_kwargs('my-option',
170
176
            help='test option', short='be short', be_long='go long')
175
181
            be_long='go long', value_switches=True)
176
182
        self.assertEqual(['my-option', 'be-long', 'short'],
177
183
            [x[0] for x in my_option.iter_switches()])
178
 
        self.assertEqual('test option', my_option.help)
179
184
 
180
185
    def test_help(self):
181
 
        registry = controldir.ControlDirFormatRegistry()
182
 
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
183
 
        bzrdir.register_metadir(registry, 'two',
 
186
        registry = bzrdir.BzrDirFormatRegistry()
 
187
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
188
        registry.register_metadir('two',
184
189
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
185
190
            'two help',
186
191
            )
187
 
        bzrdir.register_metadir(registry, 'hidden', 'RepositoryFormat7', 'hidden help',
 
192
        registry.register_metadir('hidden', 'RepositoryFormat7', 'hidden help',
188
193
            hidden=True)
189
194
        registry.set_default('one')
190
195
        options = [option.RegistryOption('format', 'format help', registry,
206
211
        opt = option.Option('hello', help='fg', type=int, argname='gar')
207
212
        self.assertEqual(list(opt.iter_switches()),
208
213
                         [('hello', None, 'GAR', 'fg')])
209
 
        registry = controldir.ControlDirFormatRegistry()
210
 
        bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
211
 
        bzrdir.register_metadir(registry, 'two',
 
214
        registry = bzrdir.BzrDirFormatRegistry()
 
215
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
216
        registry.register_metadir('two',
212
217
                'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
213
218
                'two help',
214
219
                )
226
231
                          ('two', None, None, 'two help'),
227
232
                          ])
228
233
 
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
 
 
260
 
 
261
 
class TestListOptions(TestCase):
262
 
    """Tests for ListOption, used to specify lists on the command-line."""
263
 
 
264
 
    def parse(self, options, args):
265
 
        parser = option.get_optparser(dict((o.name, o) for o in options))
266
 
        return parser.parse_args(args)
267
 
 
268
 
    def test_list_option(self):
269
 
        options = [option.ListOption('hello', type=str)]
270
 
        opts, args = self.parse(options, ['--hello=world', '--hello=sailor'])
271
 
        self.assertEqual(['world', 'sailor'], opts.hello)
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
 
 
279
 
    def test_list_option_no_arguments(self):
280
 
        options = [option.ListOption('hello', type=str)]
281
 
        opts, args = self.parse(options, [])
282
 
        self.assertEqual([], opts.hello)
283
 
 
284
 
    def test_list_option_with_int_type(self):
285
 
        options = [option.ListOption('hello', type=int)]
286
 
        opts, args = self.parse(options, ['--hello=2', '--hello=3'])
287
 
        self.assertEqual([2, 3], opts.hello)
288
 
 
289
 
    def test_list_option_with_int_type_can_be_reset(self):
290
 
        options = [option.ListOption('hello', type=int)]
291
 
        opts, args = self.parse(options, ['--hello=2', '--hello=3',
292
 
                                          '--hello=-', '--hello=5'])
293
 
        self.assertEqual([5], opts.hello)
294
 
 
295
 
    def test_list_option_can_be_reset(self):
296
 
        """Passing an option of '-' to a list option should reset the list."""
297
 
        options = [option.ListOption('hello', type=str)]
298
 
        opts, args = self.parse(
299
 
            options, ['--hello=a', '--hello=b', '--hello=-', '--hello=c'])
300
 
        self.assertEqual(['c'], opts.hello)
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
 
 
329
 
 
330
 
class TestOptionDefinitions(TestCase):
331
 
    """Tests for options in the Bazaar codebase."""
332
 
 
333
 
    def get_builtin_command_options(self):
334
 
        g = []
335
 
        for cmd_name in sorted(commands.all_command_names()):
336
 
            cmd = commands.get_cmd_object(cmd_name)
337
 
            for opt_name, opt in sorted(cmd.options().items()):
338
 
                g.append((cmd_name, opt))
339
 
        return g
340
 
 
341
 
    def test_global_options_used(self):
342
 
        # In the distant memory, options could only be declared globally.  Now
343
 
        # we prefer to declare them in the command, unless like -r they really
344
 
        # are used very widely with the exact same meaning.  So this checks
345
 
        # for any that should be garbage collected.
346
 
        g = dict(option.Option.OPTIONS.items())
347
 
        used_globals = {}
348
 
        msgs = []
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):
352
 
                if not isinstance(option_or_name, basestring):
353
 
                    self.assertIsInstance(option_or_name, option.Option)
354
 
                elif not option_or_name in g:
355
 
                    msgs.append("apparent reference to undefined "
356
 
                        "global option %r from %r"
357
 
                        % (option_or_name, cmd))
358
 
                else:
359
 
                    used_globals.setdefault(option_or_name, []).append(cmd_name)
360
 
        unused_globals = set(g.keys()) - set(used_globals.keys())
361
 
        # not enforced because there might be plugins that use these globals
362
 
        ## for option_name in sorted(unused_globals):
363
 
        ##    msgs.append("unused global option %r" % option_name)
364
 
        ## for option_name, cmds in sorted(used_globals.items()):
365
 
        ##     if len(cmds) <= 1:
366
 
        ##         msgs.append("global option %r is only used by %r"
367
 
        ##                 % (option_name, cmds))
368
 
        if msgs:
369
 
            self.fail("problems with global option definitions:\n"
370
 
                    + '\n'.join(msgs))
371
 
 
372
 
    def test_option_grammar(self):
373
 
        msgs = []
374
 
        # Option help should be written in sentence form, and have a final
375
 
        # period and be all on a single line, because the display code will
376
 
        # wrap it.
377
 
        option_re = re.compile(r'^[A-Z][^\n]+\.$')
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))
385
 
        if msgs:
386
 
            self.fail("The following options don't match the style guide:\n"
387
 
                    + '\n'.join(msgs))
388
 
 
389
 
    def test_is_hidden(self):
390
 
        registry = controldir.ControlDirFormatRegistry()
391
 
        bzrdir.register_metadir(registry, 'hidden', 'HiddenFormat',
392
 
            'hidden help text', hidden=True)
393
 
        bzrdir.register_metadir(registry, 'visible', 'VisibleFormat',
394
 
            'visible help text', hidden=False)
395
 
        format = option.RegistryOption('format', '', registry, str)
396
 
        self.assertTrue(format.is_hidden('hidden'))
397
 
        self.assertFalse(format.is_hidden('visible'))
398
 
 
399
 
    def test_short_name(self):
400
 
        registry = controldir.ControlDirFormatRegistry()
401
 
        opt = option.RegistryOption('format', help='', registry=registry)
402
 
        self.assertEquals(None, opt.short_name())
403
 
        opt = option.RegistryOption('format', short_name='F', help='',
404
 
            registry=registry)
405
 
        self.assertEquals('F', opt.short_name())
406
 
 
407
 
    def test_option_custom_help(self):
408
 
        the_opt = option.Option.OPTIONS['help']
409
 
        orig_help = the_opt.help[:]
410
 
        my_opt = option.custom_help('help', 'suggest lottery numbers')
411
 
        # Confirm that my_opt has my help and the original is unchanged
412
 
        self.assertEqual('suggest lottery numbers', my_opt.help)
413
 
        self.assertEqual(orig_help, the_opt.help)
414
 
 
415
 
 
416
 
class TestVerboseQuietLinkage(TestCase):
417
 
 
418
 
    def check(self, parser, level, args):
419
 
        option._verbosity_level = 0
420
 
        opts, args = parser.parse_args(args)
421
 
        self.assertEqual(level, option._verbosity_level)
422
 
 
423
 
    def test_verbose_quiet_linkage(self):
424
 
        parser = option.get_optparser(option.Option.STD_OPTIONS)
425
 
        self.check(parser, 0, [])
426
 
        self.check(parser, 1, ['-v'])
427
 
        self.check(parser, 2, ['-v', '-v'])
428
 
        self.check(parser, -1, ['-q'])
429
 
        self.check(parser, -2, ['-qq'])
430
 
        self.check(parser, -1, ['-v', '-v', '-q'])
431
 
        self.check(parser, 2, ['-q', '-v', '-v'])
432
 
        self.check(parser, 0, ['--no-verbose'])
433
 
        self.check(parser, 0, ['-v', '-q', '--no-quiet'])
 
234
#     >>> parse_args('log -r 500'.split())
 
235
#     (['log'], {'revision': [<RevisionSpec_int 500>]})
 
236
#     >>> parse_args('log -r500..600'.split())
 
237
#     (['log'], {'revision': [<RevisionSpec_int 500>, <RevisionSpec_int 600>]})
 
238
#     >>> parse_args('log -vr500..600'.split())
 
239
#     (['log'], {'verbose': True, 'revision': [<RevisionSpec_int 500>, <RevisionSpec_int 600>]})
 
240
#     >>> parse_args('log -rrevno:500..600'.split()) #the r takes an argument
 
241
#     (['log'], {'revision': [<RevisionSpec_revno revno:500>, <RevisionSpec_int 600>]})