1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
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.
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.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25
from bzrlib.builtins import cmd_commit
26
from bzrlib.commands import Command, parse_args
27
from bzrlib.tests import TestCase
28
from bzrlib.repofmt import knitrepo
31
def parse(options, args):
32
parser = option.get_optparser(dict((o.name, o) for o in options))
33
return parser.parse_args(args)
36
class OptionTests(TestCase):
37
"""Command-line option tests"""
39
def test_parse_args(self):
41
# XXX: Using cmd_commit makes these tests overly sensitive to changes
42
# to cmd_commit, when they are meant to be about option parsing in
44
self.assertEqual(parse_args(cmd_commit(), ['--help']),
45
([], {'exclude': [], 'fixes': [], 'help': True}))
46
self.assertEqual(parse_args(cmd_commit(), ['--message=biter']),
47
([], {'exclude': [], 'fixes': [], 'message': 'biter'}))
49
def test_no_more_opts(self):
50
"""Terminated options"""
51
self.assertEqual(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
52
(['-file-with-dashes'], {'exclude': [], 'fixes': []}))
54
def test_option_help(self):
55
"""Options have help strings."""
56
out, err = self.run_bzr('commit --help')
57
self.assertContainsRe(out,
58
r'--file(.|\n)*Take commit message from this file\.')
59
self.assertContainsRe(out, r'-h.*--help')
61
def test_option_help_global(self):
62
"""Global options have help strings."""
63
out, err = self.run_bzr('help status')
64
self.assertContainsRe(out, r'--show-ids.*Show internal object.')
66
def test_option_arg_help(self):
67
"""Help message shows option arguments."""
68
out, err = self.run_bzr('help commit')
69
self.assertEqual(err, '')
70
self.assertContainsRe(out, r'--file[ =]MSGFILE')
72
def test_unknown_short_opt(self):
73
out, err = self.run_bzr('help -r', retcode=3)
74
self.assertContainsRe(err, r'no such option')
76
def test_set_short_name(self):
77
o = option.Option('wiggle')
79
self.assertEqual(o.short_name(), 'w')
81
def test_allow_dash(self):
82
"""Test that we can pass a plain '-' as an argument."""
83
self.assertEqual((['-']), parse_args(cmd_commit(), ['-'])[0])
85
def parse(self, options, args):
86
parser = option.get_optparser(dict((o.name, o) for o in options))
87
return parser.parse_args(args)
89
def test_conversion(self):
90
options = [option.Option('hello')]
91
opts, args = self.parse(options, ['--no-hello', '--hello'])
92
self.assertEqual(True, opts.hello)
93
opts, args = self.parse(options, [])
94
self.assertFalse(hasattr(opts, 'hello'))
95
opts, args = self.parse(options, ['--hello', '--no-hello'])
96
self.assertEqual(False, opts.hello)
97
options = [option.Option('number', type=int)]
98
opts, args = self.parse(options, ['--number', '6'])
99
self.assertEqual(6, opts.number)
100
self.assertRaises(errors.BzrCommandError, self.parse, options,
102
self.assertRaises(errors.BzrCommandError, self.parse, options,
105
def test_registry_conversion(self):
106
registry = bzrdir.BzrDirFormatRegistry()
107
registry.register_metadir('one', 'RepositoryFormat7', 'one help')
108
registry.register_metadir('two', 'RepositoryFormatKnit1', 'two help')
109
registry.register_metadir('hidden', 'RepositoryFormatKnit1',
110
'two help', hidden=True)
111
registry.set_default('one')
112
options = [option.RegistryOption('format', '', registry, str)]
113
opts, args = self.parse(options, ['--format', 'one'])
114
self.assertEqual({'format':'one'}, opts)
115
opts, args = self.parse(options, ['--format', 'two'])
116
self.assertEqual({'format':'two'}, opts)
117
self.assertRaises(errors.BadOptionValue, self.parse, options,
118
['--format', 'three'])
119
self.assertRaises(errors.BzrCommandError, self.parse, options,
121
options = [option.RegistryOption('format', '', registry, str,
122
value_switches=True)]
123
opts, args = self.parse(options, ['--two'])
124
self.assertEqual({'format':'two'}, opts)
125
opts, args = self.parse(options, ['--two', '--one'])
126
self.assertEqual({'format':'one'}, opts)
127
opts, args = self.parse(options, ['--two', '--one',
129
self.assertEqual({'format':'two'}, opts)
130
options = [option.RegistryOption('format', '', registry, str,
132
self.assertRaises(errors.BzrCommandError, self.parse, options,
135
def test_override(self):
136
options = [option.Option('hello', type=str),
137
option.Option('hi', type=str, param_name='hello')]
138
opts, args = self.parse(options, ['--hello', 'a', '--hello', 'b'])
139
self.assertEqual('b', opts.hello)
140
opts, args = self.parse(options, ['--hello', 'b', '--hello', 'a'])
141
self.assertEqual('a', opts.hello)
142
opts, args = self.parse(options, ['--hello', 'a', '--hi', 'b'])
143
self.assertEqual('b', opts.hello)
144
opts, args = self.parse(options, ['--hi', 'b', '--hello', 'a'])
145
self.assertEqual('a', opts.hello)
147
def test_registry_converter(self):
148
options = [option.RegistryOption('format', '',
149
bzrdir.format_registry, bzrdir.format_registry.make_bzrdir)]
150
opts, args = self.parse(options, ['--format', 'knit'])
151
self.assertIsInstance(opts.format.repository_format,
152
knitrepo.RepositoryFormatKnit1)
154
def test_from_kwargs(self):
155
my_option = option.RegistryOption.from_kwargs('my-option',
156
help='test option', short='be short', be_long='go long')
157
self.assertEqual(['my-option'],
158
[x[0] for x in my_option.iter_switches()])
159
my_option = option.RegistryOption.from_kwargs('my-option',
160
help='test option', title="My option", short='be short',
161
be_long='go long', value_switches=True)
162
self.assertEqual(['my-option', 'be-long', 'short'],
163
[x[0] for x in my_option.iter_switches()])
164
self.assertEqual('test option', my_option.help)
167
registry = bzrdir.BzrDirFormatRegistry()
168
registry.register_metadir('one', 'RepositoryFormat7', 'one help')
169
registry.register_metadir('two',
170
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
173
registry.register_metadir('hidden', 'RepositoryFormat7', 'hidden help',
175
registry.set_default('one')
176
options = [option.RegistryOption('format', 'format help', registry,
177
str, value_switches=True, title='Formats')]
178
parser = option.get_optparser(dict((o.name, o) for o in options))
179
value = parser.format_option_help()
180
self.assertContainsRe(value, 'format.*format help')
181
self.assertContainsRe(value, 'one.*one help')
182
self.assertContainsRe(value, 'Formats:\n *--format')
183
self.assertNotContainsRe(value, 'hidden help')
185
def test_iter_switches(self):
186
opt = option.Option('hello', help='fg')
187
self.assertEqual(list(opt.iter_switches()),
188
[('hello', None, None, 'fg')])
189
opt = option.Option('hello', help='fg', type=int)
190
self.assertEqual(list(opt.iter_switches()),
191
[('hello', None, 'ARG', 'fg')])
192
opt = option.Option('hello', help='fg', type=int, argname='gar')
193
self.assertEqual(list(opt.iter_switches()),
194
[('hello', None, 'GAR', 'fg')])
195
registry = bzrdir.BzrDirFormatRegistry()
196
registry.register_metadir('one', 'RepositoryFormat7', 'one help')
197
registry.register_metadir('two',
198
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
201
registry.set_default('one')
202
opt = option.RegistryOption('format', 'format help', registry,
203
value_switches=False)
204
self.assertEqual(list(opt.iter_switches()),
205
[('format', None, 'ARG', 'format help')])
206
opt = option.RegistryOption('format', 'format help', registry,
208
self.assertEqual(list(opt.iter_switches()),
209
[('format', None, 'ARG', 'format help'),
210
('default', None, None, 'one help'),
211
('one', None, None, 'one help'),
212
('two', None, None, 'two help'),
215
def test_option_callback_bool(self):
216
"Test booleans get True and False passed correctly to a callback."""
218
def cb(option, name, value, parser):
219
cb_calls.append((option,name,value,parser))
220
options = [option.Option('hello', custom_callback=cb)]
221
opts, args = self.parse(options, ['--hello', '--no-hello'])
222
self.assertEqual(2, len(cb_calls))
223
opt,name,value,parser = cb_calls[0]
224
self.assertEqual('hello', name)
225
self.assertTrue(value)
226
opt,name,value,parser = cb_calls[1]
227
self.assertEqual('hello', name)
228
self.assertFalse(value)
230
def test_option_callback_str(self):
231
"""Test callbacks work for string options both long and short."""
233
def cb(option, name, value, parser):
234
cb_calls.append((option,name,value,parser))
235
options = [option.Option('hello', type=str, custom_callback=cb,
237
opts, args = self.parse(options, ['--hello', 'world', '-h', 'mars'])
238
self.assertEqual(2, len(cb_calls))
239
opt,name,value,parser = cb_calls[0]
240
self.assertEqual('hello', name)
241
self.assertEqual('world', value)
242
opt,name,value,parser = cb_calls[1]
243
self.assertEqual('hello', name)
244
self.assertEqual('mars', value)
247
class TestListOptions(TestCase):
248
"""Tests for ListOption, used to specify lists on the command-line."""
250
def parse(self, options, args):
251
parser = option.get_optparser(dict((o.name, o) for o in options))
252
return parser.parse_args(args)
254
def test_list_option(self):
255
options = [option.ListOption('hello', type=str)]
256
opts, args = self.parse(options, ['--hello=world', '--hello=sailor'])
257
self.assertEqual(['world', 'sailor'], opts.hello)
259
def test_list_option_with_dash(self):
260
options = [option.ListOption('with-dash', type=str)]
261
opts, args = self.parse(options, ['--with-dash=world',
262
'--with-dash=sailor'])
263
self.assertEqual(['world', 'sailor'], opts.with_dash)
265
def test_list_option_no_arguments(self):
266
options = [option.ListOption('hello', type=str)]
267
opts, args = self.parse(options, [])
268
self.assertEqual([], opts.hello)
270
def test_list_option_with_int_type(self):
271
options = [option.ListOption('hello', type=int)]
272
opts, args = self.parse(options, ['--hello=2', '--hello=3'])
273
self.assertEqual([2, 3], opts.hello)
275
def test_list_option_with_int_type_can_be_reset(self):
276
options = [option.ListOption('hello', type=int)]
277
opts, args = self.parse(options, ['--hello=2', '--hello=3',
278
'--hello=-', '--hello=5'])
279
self.assertEqual([5], opts.hello)
281
def test_list_option_can_be_reset(self):
282
"""Passing an option of '-' to a list option should reset the list."""
283
options = [option.ListOption('hello', type=str)]
284
opts, args = self.parse(
285
options, ['--hello=a', '--hello=b', '--hello=-', '--hello=c'])
286
self.assertEqual(['c'], opts.hello)
288
def test_option_callback_list(self):
289
"""Test callbacks work for list options."""
291
def cb(option, name, value, parser):
292
# Note that the value is a reference so copy to keep it
293
cb_calls.append((option,name,value[:],parser))
294
options = [option.ListOption('hello', type=str, custom_callback=cb)]
295
opts, args = self.parse(options, ['--hello=world', '--hello=mars',
297
self.assertEqual(3, len(cb_calls))
298
opt,name,value,parser = cb_calls[0]
299
self.assertEqual('hello', name)
300
self.assertEqual(['world'], value)
301
opt,name,value,parser = cb_calls[1]
302
self.assertEqual('hello', name)
303
self.assertEqual(['world', 'mars'], value)
304
opt,name,value,parser = cb_calls[2]
305
self.assertEqual('hello', name)
306
self.assertEqual([], value)
309
class TestOptionDefinitions(TestCase):
310
"""Tests for options in the Bazaar codebase."""
312
def get_builtin_command_options(self):
314
for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
316
for opt_name, opt in sorted(cmd.options().items()):
317
g.append((cmd_name, opt))
320
def test_global_options_used(self):
321
# In the distant memory, options could only be declared globally. Now
322
# we prefer to declare them in the command, unless like -r they really
323
# are used very widely with the exact same meaning. So this checks
324
# for any that should be garbage collected.
325
g = dict(option.Option.OPTIONS.items())
328
for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
329
for option_or_name in sorted(cmd_class.takes_options):
330
if not isinstance(option_or_name, basestring):
331
self.assertIsInstance(option_or_name, option.Option)
332
elif not option_or_name in g:
333
msgs.append("apparent reference to undefined "
334
"global option %r from %r"
335
% (option_or_name, cmd_class))
337
used_globals.setdefault(option_or_name, []).append(cmd_name)
338
unused_globals = set(g.keys()) - set(used_globals.keys())
339
# not enforced because there might be plugins that use these globals
340
## for option_name in sorted(unused_globals):
341
## msgs.append("unused global option %r" % option_name)
342
## for option_name, cmds in sorted(used_globals.items()):
343
## if len(cmds) <= 1:
344
## msgs.append("global option %r is only used by %r"
345
## % (option_name, cmds))
347
self.fail("problems with global option definitions:\n"
350
def test_option_grammar(self):
352
# Option help should be written in sentence form, and have a final
353
# period and be all on a single line, because the display code will
355
option_re = re.compile(r'^[A-Z][^\n]+\.$')
356
for scope, option in self.get_builtin_command_options():
358
msgs.append('%-16s %-16s %s' %
359
((scope or 'GLOBAL'), option.name, 'NO HELP'))
360
elif not option_re.match(option.help):
361
msgs.append('%-16s %-16s %s' %
362
((scope or 'GLOBAL'), option.name, option.help))
364
self.fail("The following options don't match the style guide:\n"
367
def test_is_hidden(self):
368
registry = bzrdir.BzrDirFormatRegistry()
369
registry.register_metadir('hidden', 'HiddenFormat',
370
'hidden help text', hidden=True)
371
registry.register_metadir('visible', 'VisibleFormat',
372
'visible help text', hidden=False)
373
format = option.RegistryOption('format', '', registry, str)
374
self.assertTrue(format.is_hidden('hidden'))
375
self.assertFalse(format.is_hidden('visible'))
377
def test_option_custom_help(self):
378
the_opt = option.Option.OPTIONS['help']
379
orig_help = the_opt.help[:]
380
my_opt = option.custom_help('help', 'suggest lottery numbers')
381
# Confirm that my_opt has my help and the original is unchanged
382
self.assertEqual('suggest lottery numbers', my_opt.help)
383
self.assertEqual(orig_help, the_opt.help)
386
class TestVerboseQuietLinkage(TestCase):
388
def check(self, parser, level, args):
389
option._verbosity_level = 0
390
opts, args = parser.parse_args(args)
391
self.assertEqual(level, option._verbosity_level)
393
def test_verbose_quiet_linkage(self):
394
parser = option.get_optparser(option.Option.STD_OPTIONS)
395
self.check(parser, 0, [])
396
self.check(parser, 1, ['-v'])
397
self.check(parser, 2, ['-v', '-v'])
398
self.check(parser, -1, ['-q'])
399
self.check(parser, -2, ['-qq'])
400
self.check(parser, -1, ['-v', '-v', '-q'])
401
self.check(parser, 2, ['-q', '-v', '-v'])
402
self.check(parser, 0, ['--no-verbose'])
403
self.check(parser, 0, ['-v', '-q', '--no-quiet'])