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
27
from ..builtins import cmd_commit
28
from ..commands import parse_args
29
from . import TestCase
30
from ..bzr import knitrepo
33
def parse(options, args):
34
parser = option.get_optparser(options)
35
return parser.parse_args(args)
38
class OptionTests(TestCase):
39
"""Command-line option tests"""
41
def test_parse_args(self):
43
# XXX: Using cmd_commit makes these tests overly sensitive to changes
44
# to cmd_commit, when they are meant to be about option parsing in
47
([], {'author': [], 'exclude': [], 'fixes': [], 'help': True,
49
parse_args(cmd_commit(), ['--help']))
51
([], {'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'], {
59
'author': [], 'exclude': [], 'fixes': [], 'bugs': []}),
60
parse_args(cmd_commit(), ['--', '-file-with-dashes']))
62
def test_option_help(self):
63
"""Options have help strings."""
64
out, err = self.run_bzr('commit --help')
65
self.assertContainsRe(out,
66
r'--file(.|\n)*Take commit message from this file\.')
67
self.assertContainsRe(out, r'-h.*--help')
69
def test_option_help_global(self):
70
"""Global options have help strings."""
71
out, err = self.run_bzr('help status')
72
self.assertContainsRe(out, r'--show-ids.*Show internal object.')
74
def test_option_help_global_hidden(self):
75
"""Hidden global options have no help strings."""
76
out, err = self.run_bzr('help log')
77
self.assertNotContainsRe(out, r'--message')
79
def test_option_arg_help(self):
80
"""Help message shows option arguments."""
81
out, err = self.run_bzr('help commit')
82
self.assertEqual(err, '')
83
self.assertContainsRe(out, r'--file[ =]MSGFILE')
85
def test_unknown_short_opt(self):
86
out, err = self.run_bzr('help -r', retcode=3)
87
self.assertContainsRe(err, r'no such option')
89
def test_set_short_name(self):
90
o = option.Option('wiggle')
92
self.assertEqual(o.short_name(), 'w')
94
def test_allow_dash(self):
95
"""Test that we can pass a plain '-' as an argument."""
96
self.assertEqual((['-']), parse_args(cmd_commit(), ['-'])[0])
98
def parse(self, options, args):
99
parser = option.get_optparser(options)
100
return parser.parse_args(args)
102
def test_conversion(self):
103
options = [option.Option('hello')]
104
opts, args = self.parse(options, ['--no-hello', '--hello'])
105
self.assertEqual(True, opts.hello)
106
opts, args = self.parse(options, [])
107
self.assertFalse(hasattr(opts, 'hello'))
108
opts, args = self.parse(options, ['--hello', '--no-hello'])
109
self.assertEqual(False, opts.hello)
110
options = [option.Option('number', type=int)]
111
opts, args = self.parse(options, ['--number', '6'])
112
self.assertEqual(6, opts.number)
113
self.assertRaises(errors.BzrCommandError, self.parse, options,
115
self.assertRaises(errors.BzrCommandError, self.parse, options,
118
def test_is_hidden(self):
119
self.assertTrue(option.Option('foo', hidden=True).is_hidden('foo'))
120
self.assertFalse(option.Option('foo', hidden=False).is_hidden('foo'))
122
def test_registry_conversion(self):
123
registry = controldir.ControlDirFormatRegistry()
124
bzr.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
125
bzr.register_metadir(
126
registry, 'two', 'RepositoryFormatKnit1', 'two help')
127
bzr.register_metadir(registry, 'hidden', 'RepositoryFormatKnit1',
128
'two help', hidden=True)
129
registry.set_default('one')
130
options = [option.RegistryOption('format', '', registry, str)]
131
opts, args = self.parse(options, ['--format', 'one'])
132
self.assertEqual({'format': 'one'}, opts)
133
opts, args = self.parse(options, ['--format', 'two'])
134
self.assertEqual({'format': 'two'}, opts)
135
self.assertRaises(option.BadOptionValue, self.parse, options,
136
['--format', 'three'])
137
self.assertRaises(errors.BzrCommandError, self.parse, options,
139
options = [option.RegistryOption('format', '', registry, str,
140
value_switches=True)]
141
opts, args = self.parse(options, ['--two'])
142
self.assertEqual({'format': 'two'}, opts)
143
opts, args = self.parse(options, ['--two', '--one'])
144
self.assertEqual({'format': 'one'}, opts)
145
opts, args = self.parse(options, ['--two', '--one',
147
self.assertEqual({'format': 'two'}, opts)
148
options = [option.RegistryOption('format', '', registry, str,
150
self.assertRaises(errors.BzrCommandError, self.parse, options,
153
def test_override(self):
154
options = [option.Option('hello', type=str),
155
option.Option('hi', type=str, param_name='hello')]
156
opts, args = self.parse(options, ['--hello', 'a', '--hello', 'b'])
157
self.assertEqual('b', opts.hello)
158
opts, args = self.parse(options, ['--hello', 'b', '--hello', 'a'])
159
self.assertEqual('a', opts.hello)
160
opts, args = self.parse(options, ['--hello', 'a', '--hi', 'b'])
161
self.assertEqual('b', opts.hello)
162
opts, args = self.parse(options, ['--hi', 'b', '--hello', 'a'])
163
self.assertEqual('a', opts.hello)
165
def test_registry_converter(self):
166
options = [option.RegistryOption('format', '',
167
controldir.format_registry, controldir.format_registry.make_controldir)]
168
opts, args = self.parse(options, ['--format', 'knit'])
169
self.assertIsInstance(opts.format.repository_format,
170
knitrepo.RepositoryFormatKnit1)
172
def test_lazy_registry(self):
173
options = [option.RegistryOption('format', '',
175
'breezy.controldir', 'format_registry'),
177
opts, args = self.parse(options, ['--format', 'knit'])
178
self.assertEqual({'format': 'knit'}, opts)
180
option.BadOptionValue, self.parse, options, ['--format', 'BAD'])
182
def test_from_kwargs(self):
183
my_option = option.RegistryOption.from_kwargs('my-option',
184
help='test option', short='be short', be_long='go long')
185
self.assertEqual(['my-option'],
186
[x[0] for x in my_option.iter_switches()])
187
my_option = option.RegistryOption.from_kwargs('my-option',
188
help='test option', title="My option", short='be short',
189
be_long='go long', value_switches=True)
190
self.assertEqual(['my-option', 'be-long', 'short'],
191
[x[0] for x in my_option.iter_switches()])
192
self.assertEqual('test option', my_option.help)
195
registry = controldir.ControlDirFormatRegistry()
196
bzr.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
197
bzr.register_metadir(registry, 'two',
198
'breezy.bzr.knitrepo.RepositoryFormatKnit1',
201
bzr.register_metadir(registry, 'hidden', 'RepositoryFormat7', 'hidden help',
203
registry.set_default('one')
204
options = [option.RegistryOption('format', 'format help', registry,
205
str, value_switches=True, title='Formats')]
206
parser = option.get_optparser(options)
207
value = parser.format_option_help()
208
self.assertContainsRe(value, 'format.*format help')
209
self.assertContainsRe(value, 'one.*one help')
210
self.assertContainsRe(value, 'Formats:\n *--format')
211
self.assertNotContainsRe(value, 'hidden help')
213
def test_iter_switches(self):
214
opt = option.Option('hello', help='fg')
215
self.assertEqual(list(opt.iter_switches()),
216
[('hello', None, None, 'fg')])
217
opt = option.Option('hello', help='fg', type=int)
218
self.assertEqual(list(opt.iter_switches()),
219
[('hello', None, 'ARG', 'fg')])
220
opt = option.Option('hello', help='fg', type=int, argname='gar')
221
self.assertEqual(list(opt.iter_switches()),
222
[('hello', None, 'GAR', 'fg')])
223
registry = controldir.ControlDirFormatRegistry()
224
bzr.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
225
bzr.register_metadir(registry, 'two',
226
'breezy.bzr.knitrepo.RepositoryFormatKnit1',
229
registry.set_default('one')
230
opt = option.RegistryOption('format', 'format help', registry,
231
value_switches=False)
232
self.assertEqual(list(opt.iter_switches()),
233
[('format', None, 'ARG', 'format help')])
234
opt = option.RegistryOption('format', 'format help', registry,
236
self.assertEqual(list(opt.iter_switches()),
237
[('format', None, 'ARG', 'format help'),
238
('default', None, None, 'one help'),
239
('one', None, None, 'one help'),
240
('two', None, None, 'two help'),
243
def test_option_callback_bool(self):
244
"Test booleans get True and False passed correctly to a callback."""
247
def cb(option, name, value, parser):
248
cb_calls.append((option, name, value, parser))
249
options = [option.Option('hello', custom_callback=cb)]
250
opts, args = self.parse(options, ['--hello', '--no-hello'])
251
self.assertEqual(2, len(cb_calls))
252
opt, name, value, parser = cb_calls[0]
253
self.assertEqual('hello', name)
254
self.assertTrue(value)
255
opt, name, value, parser = cb_calls[1]
256
self.assertEqual('hello', name)
257
self.assertFalse(value)
259
def test_option_callback_str(self):
260
"""Test callbacks work for string options both long and short."""
263
def cb(option, name, value, parser):
264
cb_calls.append((option, name, value, parser))
265
options = [option.Option('hello', type=str, custom_callback=cb,
267
opts, args = self.parse(options, ['--hello', 'world', '-h', 'mars'])
268
self.assertEqual(2, len(cb_calls))
269
opt, name, value, parser = cb_calls[0]
270
self.assertEqual('hello', name)
271
self.assertEqual('world', value)
272
opt, name, value, parser = cb_calls[1]
273
self.assertEqual('hello', name)
274
self.assertEqual('mars', value)
277
class TestListOptions(TestCase):
278
"""Tests for ListOption, used to specify lists on the command-line."""
280
def parse(self, options, args):
281
parser = option.get_optparser(options)
282
return parser.parse_args(args)
284
def test_list_option(self):
285
options = [option.ListOption('hello', type=str)]
286
opts, args = self.parse(options, ['--hello=world', '--hello=sailor'])
287
self.assertEqual(['world', 'sailor'], opts.hello)
289
def test_list_option_with_dash(self):
290
options = [option.ListOption('with-dash', type=str)]
291
opts, args = self.parse(options, ['--with-dash=world',
292
'--with-dash=sailor'])
293
self.assertEqual(['world', 'sailor'], opts.with_dash)
295
def test_list_option_no_arguments(self):
296
options = [option.ListOption('hello', type=str)]
297
opts, args = self.parse(options, [])
298
self.assertEqual([], opts.hello)
300
def test_list_option_with_int_type(self):
301
options = [option.ListOption('hello', type=int)]
302
opts, args = self.parse(options, ['--hello=2', '--hello=3'])
303
self.assertEqual([2, 3], opts.hello)
305
def test_list_option_with_int_type_can_be_reset(self):
306
options = [option.ListOption('hello', type=int)]
307
opts, args = self.parse(options, ['--hello=2', '--hello=3',
308
'--hello=-', '--hello=5'])
309
self.assertEqual([5], opts.hello)
311
def test_list_option_can_be_reset(self):
312
"""Passing an option of '-' to a list option should reset the list."""
313
options = [option.ListOption('hello', type=str)]
314
opts, args = self.parse(
315
options, ['--hello=a', '--hello=b', '--hello=-', '--hello=c'])
316
self.assertEqual(['c'], opts.hello)
318
def test_option_callback_list(self):
319
"""Test callbacks work for list options."""
322
def cb(option, name, value, parser):
323
# Note that the value is a reference so copy to keep it
324
cb_calls.append((option, name, value[:], parser))
325
options = [option.ListOption('hello', type=str, custom_callback=cb)]
326
opts, args = self.parse(options, ['--hello=world', '--hello=mars',
328
self.assertEqual(3, len(cb_calls))
329
opt, name, value, parser = cb_calls[0]
330
self.assertEqual('hello', name)
331
self.assertEqual(['world'], value)
332
opt, name, value, parser = cb_calls[1]
333
self.assertEqual('hello', name)
334
self.assertEqual(['world', 'mars'], value)
335
opt, name, value, parser = cb_calls[2]
336
self.assertEqual('hello', name)
337
self.assertEqual([], value)
339
def test_list_option_param_name(self):
340
"""Test list options can have their param_name set."""
341
options = [option.ListOption('hello', type=str, param_name='greeting')]
342
opts, args = self.parse(
343
options, ['--hello=world', '--hello=sailor'])
344
self.assertEqual(['world', 'sailor'], opts.greeting)
347
class TestOptionDefinitions(TestCase):
348
"""Tests for options in the Bazaar codebase."""
350
def get_builtin_command_options(self):
352
commands.install_bzr_command_hooks()
353
for cmd_name in sorted(commands.builtin_command_names()):
354
cmd = commands.get_cmd_object(cmd_name)
355
for opt_name, opt in sorted(cmd.options().items()):
356
g.append((cmd_name, opt))
360
def test_option_grammar(self):
362
# Option help should be written in sentence form, and have a final
363
# period with an optional bracketed suffix. All the text should be on
364
# one line, because the display code will wrap it.
365
option_re = re.compile(r'^[A-Z][^\n]+\.(?: \([^\n]+\))?$')
366
for scope, opt in self.get_builtin_command_options():
367
for name, _, _, helptxt in opt.iter_switches():
369
name = "/".join([opt.name, name])
371
msgs.append('%-16s %-16s %s' %
372
((scope or 'GLOBAL'), name, 'NO HELP'))
373
elif not option_re.match(helptxt):
374
if name.startswith("format/"):
375
# Don't complain about the odd format registry help
377
msgs.append('%-16s %-16s %s' %
378
((scope or 'GLOBAL'), name, helptxt))
380
self.fail("The following options don't match the style guide:\n"
384
class TestOptionMisc(TestCase):
386
def test_is_hidden(self):
387
registry = controldir.ControlDirFormatRegistry()
388
bzr.register_metadir(registry, 'hidden', 'HiddenFormat',
389
'hidden help text', hidden=True)
390
bzr.register_metadir(registry, 'visible', 'VisibleFormat',
391
'visible help text', hidden=False)
392
format = option.RegistryOption('format', '', registry, str)
393
self.assertTrue(format.is_hidden('hidden'))
394
self.assertFalse(format.is_hidden('visible'))
396
def test_short_name(self):
397
registry = controldir.ControlDirFormatRegistry()
398
opt = option.RegistryOption('format', help='', registry=registry)
399
self.assertEqual(None, opt.short_name())
400
opt = option.RegistryOption('format', short_name='F', help='',
402
self.assertEqual('F', opt.short_name())
404
def test_option_custom_help(self):
405
the_opt = option.Option.OPTIONS['help']
406
orig_help = the_opt.help[:]
407
my_opt = option.custom_help('help', 'suggest lottery numbers')
408
# Confirm that my_opt has my help and the original is unchanged
409
self.assertEqual('suggest lottery numbers', my_opt.help)
410
self.assertEqual(orig_help, the_opt.help)
412
def test_short_value_switches(self):
413
reg = registry.Registry()
414
reg.register('short', 'ShortChoice')
415
reg.register('long', 'LongChoice')
416
ropt = option.RegistryOption('choice', '', reg, value_switches=True,
417
short_value_switches={'short': 's'})
418
opts, args = parse([ropt], ['--short'])
419
self.assertEqual('ShortChoice', opts.choice)
420
opts, args = parse([ropt], ['-s'])
421
self.assertEqual('ShortChoice', opts.choice)
424
class TestVerboseQuietLinkage(TestCase):
426
def check(self, parser, level, args):
427
option._verbosity_level = 0
428
opts, args = parser.parse_args(args)
429
self.assertEqual(level, option._verbosity_level)
431
def test_verbose_quiet_linkage(self):
432
parser = option.get_optparser(
433
[v for k, v in sorted(option.Option.STD_OPTIONS.items())])
434
self.check(parser, 0, [])
435
self.check(parser, 1, ['-v'])
436
self.check(parser, 2, ['-v', '-v'])
437
self.check(parser, -1, ['-q'])
438
self.check(parser, -2, ['-qq'])
439
self.check(parser, -1, ['-v', '-v', '-q'])
440
self.check(parser, 2, ['-q', '-v', '-v'])
441
self.check(parser, 0, ['--no-verbose'])
442
self.check(parser, 0, ['-v', '-q', '--no-quiet'])