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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
17
from bzrlib import (
25
from bzrlib.builtins import cmd_commit
25
from bzrlib.builtins import cmd_commit, cmd_log, cmd_status
26
26
from bzrlib.commands import Command, parse_args
27
27
from bzrlib.tests import TestCase
28
28
from bzrlib.repofmt import knitrepo
31
30
def parse(options, args):
32
31
parser = option.get_optparser(dict((o.name, o) for o in options))
33
32
return parser.parse_args(args)
36
34
class OptionTests(TestCase):
37
35
"""Command-line option tests"""
39
37
def test_parse_args(self):
40
38
"""Option parser"""
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
([], {'author': [], 'exclude': [], 'fixes': [], 'help': True}))
46
self.assertEqual(parse_args(cmd_commit(), ['--message=biter']),
47
([], {'author': [], 'exclude': [], 'fixes': [], 'message': 'biter'}))
39
eq = self.assertEquals
40
eq(parse_args(cmd_commit(), ['--help']),
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
47
def test_no_more_opts(self):
50
48
"""Terminated options"""
51
self.assertEqual(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
52
(['-file-with-dashes'], {'author': [], 'exclude': [], 'fixes': []}))
49
self.assertEquals(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
50
(['-file-with-dashes'], {}))
54
52
def test_option_help(self):
55
53
"""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\.')
54
out, err = self.run_bzr_captured(['commit', '--help'])
55
self.assertContainsRe(out, r'--file(.|\n)*file containing commit'
59
57
self.assertContainsRe(out, r'-h.*--help')
61
59
def test_option_help_global(self):
62
60
"""Global options have help strings."""
63
out, err = self.run_bzr('help status')
64
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
64
def test_option_arg_help(self):
67
65
"""Help message shows option arguments."""
68
out, err = self.run_bzr('help commit')
69
self.assertEqual(err, '')
66
out, err = self.run_bzr_captured(['help', 'commit'])
67
self.assertEquals(err, '')
70
68
self.assertContainsRe(out, r'--file[ =]MSGFILE')
72
70
def test_unknown_short_opt(self):
73
out, err = self.run_bzr('help -r', retcode=3)
71
out, err = self.run_bzr_captured(['help', '-r'], retcode=3)
74
72
self.assertContainsRe(err, r'no such option')
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)
76
80
def test_set_short_name(self):
77
81
o = option.Option('wiggle')
78
82
o.set_short_name('w')
79
83
self.assertEqual(o.short_name(), 'w')
85
def test_old_short_names(self):
86
# test the deprecated method for getting and setting short option
89
"access to SHORT_OPTIONS was deprecated in version 0.14."
90
" Set the short option name when constructing the Option.",
91
DeprecationWarning, 2)
93
def capture_warning(message, category, stacklevel=None):
94
_warnings.append((message, category, stacklevel))
95
old_warning_method = symbol_versioning.warn
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
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
107
opts, args = parse([example_opt], ['-w', 'foo'])
108
self.assertEqual(opts.example, True)
109
self.assertEqual(args, ['foo'])
111
symbol_versioning.set_warning_method(old_warning_method)
81
113
def test_allow_dash(self):
82
114
"""Test that we can pass a plain '-' as an argument."""
83
self.assertEqual((['-']), parse_args(cmd_commit(), ['-'])[0])
115
self.assertEqual((['-'], {}), parse_args(cmd_commit(), ['-']))
85
117
def parse(self, options, args):
86
118
parser = option.get_optparser(dict((o.name, o) for o in options))
225
231
('two', None, None, 'two help'),
228
def test_option_callback_bool(self):
229
"Test booleans get True and False passed correctly to a callback."""
231
def cb(option, name, value, parser):
232
cb_calls.append((option,name,value,parser))
233
options = [option.Option('hello', custom_callback=cb)]
234
opts, args = self.parse(options, ['--hello', '--no-hello'])
235
self.assertEqual(2, len(cb_calls))
236
opt,name,value,parser = cb_calls[0]
237
self.assertEqual('hello', name)
238
self.assertTrue(value)
239
opt,name,value,parser = cb_calls[1]
240
self.assertEqual('hello', name)
241
self.assertFalse(value)
243
def test_option_callback_str(self):
244
"""Test callbacks work for string options both long and short."""
246
def cb(option, name, value, parser):
247
cb_calls.append((option,name,value,parser))
248
options = [option.Option('hello', type=str, custom_callback=cb,
250
opts, args = self.parse(options, ['--hello', 'world', '-h', 'mars'])
251
self.assertEqual(2, len(cb_calls))
252
opt,name,value,parser = cb_calls[0]
253
self.assertEqual('hello', name)
254
self.assertEqual('world', value)
255
opt,name,value,parser = cb_calls[1]
256
self.assertEqual('hello', name)
257
self.assertEqual('mars', value)
260
class TestListOptions(TestCase):
261
"""Tests for ListOption, used to specify lists on the command-line."""
263
def parse(self, options, args):
264
parser = option.get_optparser(dict((o.name, o) for o in options))
265
return parser.parse_args(args)
267
def test_list_option(self):
268
options = [option.ListOption('hello', type=str)]
269
opts, args = self.parse(options, ['--hello=world', '--hello=sailor'])
270
self.assertEqual(['world', 'sailor'], opts.hello)
272
def test_list_option_with_dash(self):
273
options = [option.ListOption('with-dash', type=str)]
274
opts, args = self.parse(options, ['--with-dash=world',
275
'--with-dash=sailor'])
276
self.assertEqual(['world', 'sailor'], opts.with_dash)
278
def test_list_option_no_arguments(self):
279
options = [option.ListOption('hello', type=str)]
280
opts, args = self.parse(options, [])
281
self.assertEqual([], opts.hello)
283
def test_list_option_with_int_type(self):
284
options = [option.ListOption('hello', type=int)]
285
opts, args = self.parse(options, ['--hello=2', '--hello=3'])
286
self.assertEqual([2, 3], opts.hello)
288
def test_list_option_with_int_type_can_be_reset(self):
289
options = [option.ListOption('hello', type=int)]
290
opts, args = self.parse(options, ['--hello=2', '--hello=3',
291
'--hello=-', '--hello=5'])
292
self.assertEqual([5], opts.hello)
294
def test_list_option_can_be_reset(self):
295
"""Passing an option of '-' to a list option should reset the list."""
296
options = [option.ListOption('hello', type=str)]
297
opts, args = self.parse(
298
options, ['--hello=a', '--hello=b', '--hello=-', '--hello=c'])
299
self.assertEqual(['c'], opts.hello)
301
def test_option_callback_list(self):
302
"""Test callbacks work for list options."""
304
def cb(option, name, value, parser):
305
# Note that the value is a reference so copy to keep it
306
cb_calls.append((option,name,value[:],parser))
307
options = [option.ListOption('hello', type=str, custom_callback=cb)]
308
opts, args = self.parse(options, ['--hello=world', '--hello=mars',
310
self.assertEqual(3, len(cb_calls))
311
opt,name,value,parser = cb_calls[0]
312
self.assertEqual('hello', name)
313
self.assertEqual(['world'], value)
314
opt,name,value,parser = cb_calls[1]
315
self.assertEqual('hello', name)
316
self.assertEqual(['world', 'mars'], value)
317
opt,name,value,parser = cb_calls[2]
318
self.assertEqual('hello', name)
319
self.assertEqual([], value)
322
class TestOptionDefinitions(TestCase):
323
"""Tests for options in the Bazaar codebase."""
325
def get_builtin_command_options(self):
327
for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
329
for opt_name, opt in sorted(cmd.options().items()):
330
g.append((cmd_name, opt))
333
def test_global_options_used(self):
334
# In the distant memory, options could only be declared globally. Now
335
# we prefer to declare them in the command, unless like -r they really
336
# are used very widely with the exact same meaning. So this checks
337
# for any that should be garbage collected.
338
g = dict(option.Option.OPTIONS.items())
341
for cmd_name, cmd_class in sorted(commands.get_all_cmds()):
342
for option_or_name in sorted(cmd_class.takes_options):
343
if not isinstance(option_or_name, basestring):
344
self.assertIsInstance(option_or_name, option.Option)
345
elif not option_or_name in g:
346
msgs.append("apparent reference to undefined "
347
"global option %r from %r"
348
% (option_or_name, cmd_class))
350
used_globals.setdefault(option_or_name, []).append(cmd_name)
351
unused_globals = set(g.keys()) - set(used_globals.keys())
352
# not enforced because there might be plugins that use these globals
353
## for option_name in sorted(unused_globals):
354
## msgs.append("unused global option %r" % option_name)
355
## for option_name, cmds in sorted(used_globals.items()):
356
## if len(cmds) <= 1:
357
## msgs.append("global option %r is only used by %r"
358
## % (option_name, cmds))
360
self.fail("problems with global option definitions:\n"
363
def test_option_grammar(self):
365
# Option help should be written in sentence form, and have a final
366
# period and be all on a single line, because the display code will
368
option_re = re.compile(r'^[A-Z][^\n]+\.$')
369
for scope, opt in self.get_builtin_command_options():
371
msgs.append('%-16s %-16s %s' %
372
((scope or 'GLOBAL'), opt.name, 'NO HELP'))
373
elif not option_re.match(opt.help):
374
msgs.append('%-16s %-16s %s' %
375
((scope or 'GLOBAL'), opt.name, opt.help))
377
self.fail("The following options don't match the style guide:\n"
380
def test_is_hidden(self):
381
registry = bzrdir.BzrDirFormatRegistry()
382
registry.register_metadir('hidden', 'HiddenFormat',
383
'hidden help text', hidden=True)
384
registry.register_metadir('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_option_custom_help(self):
391
the_opt = option.Option.OPTIONS['help']
392
orig_help = the_opt.help[:]
393
my_opt = option.custom_help('help', 'suggest lottery numbers')
394
# Confirm that my_opt has my help and the original is unchanged
395
self.assertEqual('suggest lottery numbers', my_opt.help)
396
self.assertEqual(orig_help, the_opt.help)
399
class TestVerboseQuietLinkage(TestCase):
401
def check(self, parser, level, args):
402
option._verbosity_level = 0
403
opts, args = parser.parse_args(args)
404
self.assertEqual(level, option._verbosity_level)
406
def test_verbose_quiet_linkage(self):
407
parser = option.get_optparser(option.Option.STD_OPTIONS)
408
self.check(parser, 0, [])
409
self.check(parser, 1, ['-v'])
410
self.check(parser, 2, ['-v', '-v'])
411
self.check(parser, -1, ['-q'])
412
self.check(parser, -2, ['-qq'])
413
self.check(parser, -1, ['-v', '-v', '-q'])
414
self.check(parser, 2, ['-q', '-v', '-v'])
415
self.check(parser, 0, ['--no-verbose'])
416
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>]})