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
28
from bzrlib.builtins import cmd_commit, cmd_log, cmd_status
29
from bzrlib.commands import Command, parse_args
30
from bzrlib.tests import TestCase
31
from bzrlib.repofmt import knitrepo
34
def parse(options, args):
35
parser = option.get_optparser(dict((o.name, o) for o in options))
36
return parser.parse_args(args)
39
class OptionTests(TestCase):
40
"""Command-line option tests"""
42
def test_parse_args(self):
44
eq = self.assertEquals
45
eq(parse_args(cmd_commit(), ['--help']),
46
([], {'fixes': [], 'help': True}))
47
eq(parse_args(cmd_commit(), ['--message=biter']),
48
([], {'fixes': [], 'message': 'biter'}))
50
def test_no_more_opts(self):
51
"""Terminated options"""
52
self.assertEquals(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
53
(['-file-with-dashes'], {'fixes': []}))
55
def test_option_help(self):
56
"""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\.')
60
self.assertContainsRe(out, r'-h.*--help')
62
def test_option_help_global(self):
63
"""Global options have help strings."""
64
out, err = self.run_bzr('help status')
65
self.assertContainsRe(out, r'--show-ids.*Show internal object.')
67
def test_option_arg_help(self):
68
"""Help message shows option arguments."""
69
out, err = self.run_bzr('help commit')
70
self.assertEquals(err, '')
71
self.assertContainsRe(out, r'--file[ =]MSGFILE')
73
def test_unknown_short_opt(self):
74
out, err = self.run_bzr('help -r', retcode=3)
75
self.assertContainsRe(err, r'no such option')
77
def test_set_short_name(self):
78
o = option.Option('wiggle')
80
self.assertEqual(o.short_name(), 'w')
82
def test_allow_dash(self):
83
"""Test that we can pass a plain '-' as an argument."""
85
(['-'], {'fixes': []}), parse_args(cmd_commit(), ['-']))
87
def parse(self, options, args):
88
parser = option.get_optparser(dict((o.name, o) for o in options))
89
return parser.parse_args(args)
91
def test_conversion(self):
92
options = [option.Option('hello')]
93
opts, args = self.parse(options, ['--no-hello', '--hello'])
94
self.assertEqual(True, opts.hello)
95
opts, args = self.parse(options, [])
96
self.assertFalse(hasattr(opts, 'hello'))
97
opts, args = self.parse(options, ['--hello', '--no-hello'])
98
self.assertEqual(False, opts.hello)
99
options = [option.Option('number', type=int)]
100
opts, args = self.parse(options, ['--number', '6'])
101
self.assertEqual(6, opts.number)
102
self.assertRaises(errors.BzrCommandError, self.parse, options,
104
self.assertRaises(errors.BzrCommandError, self.parse, options,
107
def test_registry_conversion(self):
108
registry = bzrdir.BzrDirFormatRegistry()
109
registry.register_metadir('one', 'RepositoryFormat7', 'one help')
110
registry.register_metadir('two', 'RepositoryFormatKnit1', 'two help')
111
registry.register_metadir('hidden', 'RepositoryFormatKnit1',
112
'two help', hidden=True)
113
registry.set_default('one')
114
options = [option.RegistryOption('format', '', registry, str)]
115
opts, args = self.parse(options, ['--format', 'one'])
116
self.assertEqual({'format':'one'}, opts)
117
opts, args = self.parse(options, ['--format', 'two'])
118
self.assertEqual({'format':'two'}, opts)
119
self.assertRaises(errors.BadOptionValue, self.parse, options,
120
['--format', 'three'])
121
self.assertRaises(errors.BzrCommandError, self.parse, options,
123
options = [option.RegistryOption('format', '', registry, str,
124
value_switches=True)]
125
opts, args = self.parse(options, ['--two'])
126
self.assertEqual({'format':'two'}, opts)
127
opts, args = self.parse(options, ['--two', '--one'])
128
self.assertEqual({'format':'one'}, opts)
129
opts, args = self.parse(options, ['--two', '--one',
131
self.assertEqual({'format':'two'}, opts)
132
options = [option.RegistryOption('format', '', registry, str,
134
self.assertRaises(errors.BzrCommandError, self.parse, options,
137
def test_registry_converter(self):
138
options = [option.RegistryOption('format', '',
139
bzrdir.format_registry, bzrdir.format_registry.make_bzrdir)]
140
opts, args = self.parse(options, ['--format', 'knit'])
141
self.assertIsInstance(opts.format.repository_format,
142
knitrepo.RepositoryFormatKnit1)
144
def test_from_kwargs(self):
145
my_option = option.RegistryOption.from_kwargs('my-option',
146
help='test option', short='be short', be_long='go long')
147
self.assertEqual(['my-option'],
148
[x[0] for x in my_option.iter_switches()])
149
my_option = option.RegistryOption.from_kwargs('my-option',
150
help='test option', title="My option", short='be short',
151
be_long='go long', value_switches=True)
152
self.assertEqual(['my-option', 'be-long', 'short'],
153
[x[0] for x in my_option.iter_switches()])
154
self.assertEqual('test option', my_option.help)
157
registry = bzrdir.BzrDirFormatRegistry()
158
registry.register_metadir('one', 'RepositoryFormat7', 'one help')
159
registry.register_metadir('two',
160
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
163
registry.register_metadir('hidden', 'RepositoryFormat7', 'hidden help',
165
registry.set_default('one')
166
options = [option.RegistryOption('format', 'format help', registry,
167
str, value_switches=True, title='Formats')]
168
parser = option.get_optparser(dict((o.name, o) for o in options))
169
value = parser.format_option_help()
170
self.assertContainsRe(value, 'format.*format help')
171
self.assertContainsRe(value, 'one.*one help')
172
self.assertContainsRe(value, 'Formats:\n *--format')
173
self.assertNotContainsRe(value, 'hidden help')
175
def test_iter_switches(self):
176
opt = option.Option('hello', help='fg')
177
self.assertEqual(list(opt.iter_switches()),
178
[('hello', None, None, 'fg')])
179
opt = option.Option('hello', help='fg', type=int)
180
self.assertEqual(list(opt.iter_switches()),
181
[('hello', None, 'ARG', 'fg')])
182
opt = option.Option('hello', help='fg', type=int, argname='gar')
183
self.assertEqual(list(opt.iter_switches()),
184
[('hello', None, 'GAR', 'fg')])
185
registry = bzrdir.BzrDirFormatRegistry()
186
registry.register_metadir('one', 'RepositoryFormat7', 'one help')
187
registry.register_metadir('two',
188
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
191
registry.set_default('one')
192
opt = option.RegistryOption('format', 'format help', registry,
193
value_switches=False)
194
self.assertEqual(list(opt.iter_switches()),
195
[('format', None, 'ARG', 'format help')])
196
opt = option.RegistryOption('format', 'format help', registry,
198
self.assertEqual(list(opt.iter_switches()),
199
[('format', None, 'ARG', 'format help'),
200
('default', None, None, 'one help'),
201
('one', None, None, 'one help'),
202
('two', None, None, 'two help'),
205
def test_option_callback_bool(self):
206
"Test booleans get True and False passed correctly to a callback."""
208
def cb(option, name, value, parser):
209
cb_calls.append((option,name,value,parser))
210
options = [option.Option('hello', custom_callback=cb)]
211
opts, args = self.parse(options, ['--hello', '--no-hello'])
212
self.assertEqual(2, len(cb_calls))
213
opt,name,value,parser = cb_calls[0]
214
self.assertEqual('hello', name)
215
self.assertTrue(value)
216
opt,name,value,parser = cb_calls[1]
217
self.assertEqual('hello', name)
218
self.assertFalse(value)
220
def test_option_callback_str(self):
221
"""Test callbacks work for string options both long and short."""
223
def cb(option, name, value, parser):
224
cb_calls.append((option,name,value,parser))
225
options = [option.Option('hello', type=str, custom_callback=cb,
227
opts, args = self.parse(options, ['--hello', 'world', '-h', 'mars'])
228
self.assertEqual(2, len(cb_calls))
229
opt,name,value,parser = cb_calls[0]
230
self.assertEqual('hello', name)
231
self.assertEqual('world', value)
232
opt,name,value,parser = cb_calls[1]
233
self.assertEqual('hello', name)
234
self.assertEqual('mars', value)
237
class TestListOptions(TestCase):
238
"""Tests for ListOption, used to specify lists on the command-line."""
240
def parse(self, options, args):
241
parser = option.get_optparser(dict((o.name, o) for o in options))
242
return parser.parse_args(args)
244
def test_list_option(self):
245
options = [option.ListOption('hello', type=str)]
246
opts, args = self.parse(options, ['--hello=world', '--hello=sailor'])
247
self.assertEqual(['world', 'sailor'], opts.hello)
249
def test_list_option_no_arguments(self):
250
options = [option.ListOption('hello', type=str)]
251
opts, args = self.parse(options, [])
252
self.assertEqual([], opts.hello)
254
def test_list_option_with_int_type(self):
255
options = [option.ListOption('hello', type=int)]
256
opts, args = self.parse(options, ['--hello=2', '--hello=3'])
257
self.assertEqual([2, 3], opts.hello)
259
def test_list_option_with_int_type_can_be_reset(self):
260
options = [option.ListOption('hello', type=int)]
261
opts, args = self.parse(options, ['--hello=2', '--hello=3',
262
'--hello=-', '--hello=5'])
263
self.assertEqual([5], opts.hello)
265
def test_list_option_can_be_reset(self):
266
"""Passing an option of '-' to a list option should reset the list."""
267
options = [option.ListOption('hello', type=str)]
268
opts, args = self.parse(
269
options, ['--hello=a', '--hello=b', '--hello=-', '--hello=c'])
270
self.assertEqual(['c'], opts.hello)
272
def test_option_callback_list(self):
273
"""Test callbacks work for list options."""
275
def cb(option, name, value, parser):
276
# Note that the value is a reference so copy to keep it
277
cb_calls.append((option,name,value[:],parser))
278
options = [option.ListOption('hello', type=str, custom_callback=cb)]
279
opts, args = self.parse(options, ['--hello=world', '--hello=mars',
281
self.assertEqual(3, len(cb_calls))
282
opt,name,value,parser = cb_calls[0]
283
self.assertEqual('hello', name)
284
self.assertEqual(['world'], value)
285
opt,name,value,parser = cb_calls[1]
286
self.assertEqual('hello', name)
287
self.assertEqual(['world', 'mars'], value)
288
opt,name,value,parser = cb_calls[2]
289
self.assertEqual('hello', name)
290
self.assertEqual([], value)
293
class TestOptionDefinitions(TestCase):
294
"""Tests for options in the Bazaar codebase."""
296
def get_builtin_command_options(self):
298
for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
300
for opt_name, opt in sorted(cmd.options().items()):
301
g.append((cmd_name, opt))
304
def test_global_options_used(self):
305
# In the distant memory, options could only be declared globally. Now
306
# we prefer to declare them in the command, unless like -r they really
307
# are used very widely with the exact same meaning. So this checks
308
# for any that should be garbage collected.
309
g = dict(option.Option.OPTIONS.items())
312
for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
313
for option_or_name in sorted(cmd_class.takes_options):
314
if not isinstance(option_or_name, basestring):
315
self.assertIsInstance(option_or_name, option.Option)
316
elif not option_or_name in g:
317
msgs.append("apparent reference to undefined "
318
"global option %r from %r"
319
% (option_or_name, cmd_class))
321
used_globals.setdefault(option_or_name, []).append(cmd_name)
322
unused_globals = set(g.keys()) - set(used_globals.keys())
323
# not enforced because there might be plugins that use these globals
324
## for option_name in sorted(unused_globals):
325
## msgs.append("unused global option %r" % option_name)
326
## for option_name, cmds in sorted(used_globals.items()):
327
## if len(cmds) <= 1:
328
## msgs.append("global option %r is only used by %r"
329
## % (option_name, cmds))
331
self.fail("problems with global option definitions:\n"
334
def test_option_grammar(self):
336
# Option help should be written in sentence form, and have a final
337
# period and be all on a single line, because the display code will
339
option_re = re.compile(r'^[A-Z][^\n]+\.$')
340
for scope, option in self.get_builtin_command_options():
342
msgs.append('%-16s %-16s %s' %
343
((scope or 'GLOBAL'), option.name, 'NO HELP'))
344
elif not option_re.match(option.help):
345
msgs.append('%-16s %-16s %s' %
346
((scope or 'GLOBAL'), option.name, option.help))
348
self.fail("The following options don't match the style guide:\n"
351
def test_is_hidden(self):
352
registry = bzrdir.BzrDirFormatRegistry()
353
registry.register_metadir('hidden', 'HiddenFormat',
354
'hidden help text', hidden=True)
355
registry.register_metadir('visible', 'VisibleFormat',
356
'visible help text', hidden=False)
357
format = option.RegistryOption('format', '', registry, str)
358
self.assertTrue(format.is_hidden('hidden'))
359
self.assertFalse(format.is_hidden('visible'))
361
def test_option_custom_help(self):
362
the_opt = option.Option.OPTIONS['help']
363
orig_help = the_opt.help[:]
364
my_opt = option.custom_help('help', 'suggest lottery numbers')
365
# Confirm that my_opt has my help and the original is unchanged
366
self.assertEqual('suggest lottery numbers', my_opt.help)
367
self.assertEqual(orig_help, the_opt.help)
370
class TestVerboseQuietLinkage(TestCase):
372
def check(self, parser, level, args):
373
option._verbosity_level = 0
374
opts, args = parser.parse_args(args)
375
self.assertEqual(level, option._verbosity_level)
377
def test_verbose_quiet_linkage(self):
378
parser = option.get_optparser(option.Option.STD_OPTIONS)
379
self.check(parser, 0, [])
380
self.check(parser, 1, ['-v'])
381
self.check(parser, 2, ['-v', '-v'])
382
self.check(parser, -1, ['-q'])
383
self.check(parser, -2, ['-qq'])
384
self.check(parser, -1, ['-v', '-v', '-q'])
385
self.check(parser, 2, ['-q', '-v', '-v'])
386
self.check(parser, 0, ['--no-verbose'])
387
self.check(parser, 0, ['-v', '-q', '--no-quiet'])