1
# Copyright (C) 2005-2012, 2016 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29
from ..builtins import cmd_commit
30
from ..commands import parse_args
31
from . import TestCase
32
from ..bzr import knitrepo
35
def parse(options, args):
36
parser = option.get_optparser(dict((o.name, o) for o in options))
37
return parser.parse_args(args)
40
class OptionTests(TestCase):
41
"""Command-line option tests"""
43
def test_parse_args(self):
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
49
([], {'author': [], 'exclude': [], 'fixes': [], 'help': True}),
50
parse_args(cmd_commit(), ['--help']))
52
([], {'author': [], 'exclude': [], 'fixes': [], 'message': 'biter'}),
53
parse_args(cmd_commit(), ['--message=biter']))
55
def test_no_more_opts(self):
56
"""Terminated options"""
58
(['-file-with-dashes'], {'author': [], 'exclude': [], 'fixes': []}),
59
parse_args(cmd_commit(), ['--', '-file-with-dashes']))
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')
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.')
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')
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')
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')
88
def test_set_short_name(self):
89
o = option.Option('wiggle')
91
self.assertEqual(o.short_name(), 'w')
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])
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)
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,
114
self.assertRaises(errors.BzrCommandError, self.parse, options,
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'))
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,
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',
145
self.assertEqual({'format':'two'}, opts)
146
options = [option.RegistryOption('format', '', registry, str,
148
self.assertRaises(errors.BzrCommandError, self.parse, options,
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)
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)
170
def test_lazy_registry(self):
171
options = [option.RegistryOption('format', '',
172
lazy_registry=('breezy.controldir','format_registry'),
174
opts, args = self.parse(options, ['--format', 'knit'])
175
self.assertEqual({'format': 'knit'}, opts)
177
errors.BadOptionValue, self.parse, options, ['--format', 'BAD'])
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)
192
registry = controldir.ControlDirFormatRegistry()
193
bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
194
bzrdir.register_metadir(registry, 'two',
195
'breezy.bzr.knitrepo.RepositoryFormatKnit1',
198
bzrdir.register_metadir(registry, 'hidden', 'RepositoryFormat7', 'hidden help',
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')
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',
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,
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'),
240
def test_option_callback_bool(self):
241
"Test booleans get True and False passed correctly to a callback."""
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)
255
def test_option_callback_str(self):
256
"""Test callbacks work for string options both long and short."""
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,
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)
272
class TestListOptions(TestCase):
273
"""Tests for ListOption, used to specify lists on the command-line."""
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)
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)
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)
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)
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)
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)
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)
313
def test_option_callback_list(self):
314
"""Test callbacks work for list options."""
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',
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)
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)
341
class TestOptionDefinitions(TestCase):
342
"""Tests for options in the Bazaar codebase."""
344
def get_builtin_command_options(self):
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))
354
def test_option_grammar(self):
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():
363
name = "/".join([opt.name, name])
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
371
msgs.append('%-16s %-16s %s' %
372
((scope or 'GLOBAL'), name, helptxt))
374
self.fail("The following options don't match the style guide:\n"
378
class TestOptionMisc(TestCase):
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'))
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='',
396
self.assertEqual('F', opt.short_name())
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)
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)
418
class TestVerboseQuietLinkage(TestCase):
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)
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'])