~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_options.py

  • Committer: Robert Collins
  • Date: 2007-07-04 08:08:13 UTC
  • mfrom: (2572 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2587.
  • Revision ID: robertc@robertcollins.net-20070704080813-wzebx0r88fvwj5rq
Merge bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
2
16
 
 
17
from bzrlib import (
 
18
    builtins,
 
19
    bzrdir,
 
20
    errors,
 
21
    option,
 
22
    repository,
 
23
    symbol_versioning,
 
24
    )
3
25
from bzrlib.builtins import cmd_commit, cmd_log, cmd_status
4
26
from bzrlib.commands import Command, parse_args
5
 
from bzrlib import errors
6
 
from bzrlib import option
7
27
from bzrlib.tests import TestCase
8
 
 
9
 
# TODO: might be nice to just parse them into a structured form and test
10
 
# against that, rather than running the whole command.
 
28
from bzrlib.repofmt import knitrepo
 
29
 
 
30
 
 
31
def parse(options, args):
 
32
    parser = option.get_optparser(dict((o.name, o) for o in options))
 
33
    return parser.parse_args(args)
 
34
 
11
35
 
12
36
class OptionTests(TestCase):
13
37
    """Command-line option tests"""
16
40
        """Option parser"""
17
41
        eq = self.assertEquals
18
42
        eq(parse_args(cmd_commit(), ['--help']),
19
 
           ([], {'help': True}))
 
43
           ([], {'fixes': [], 'help': True}))
20
44
        eq(parse_args(cmd_commit(), ['--message=biter']),
21
 
           ([], {'message': 'biter'}))
22
 
        ## eq(parse_args(cmd_log(),  '-r 500'.split()),
23
 
        ##   ([], {'revision': RevisionSpec_int(500)}))
 
45
           ([], {'fixes': [], 'message': 'biter'}))
24
46
 
25
47
    def test_no_more_opts(self):
26
48
        """Terminated options"""
27
49
        self.assertEquals(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
28
 
                          (['-file-with-dashes'], {}))
 
50
                          (['-file-with-dashes'], {'fixes': []}))
29
51
 
30
52
    def test_option_help(self):
31
53
        """Options have help strings."""
32
 
        out, err = self.run_bzr_captured(['commit', '--help'])
 
54
        out, err = self.run_bzr(['commit', '--help'])
33
55
        self.assertContainsRe(out, r'--file(.|\n)*file containing commit'
34
56
                                   ' message')
35
57
        self.assertContainsRe(out, r'-h.*--help')
36
58
 
37
59
    def test_option_help_global(self):
38
60
        """Global options have help strings."""
39
 
        out, err = self.run_bzr_captured(['help', 'status'])
 
61
        out, err = self.run_bzr(['help', 'status'])
40
62
        self.assertContainsRe(out, r'--show-ids.*show internal object')
41
63
 
42
64
    def test_option_arg_help(self):
43
65
        """Help message shows option arguments."""
44
 
        out, err = self.run_bzr_captured(['help', 'commit'])
 
66
        out, err = self.run_bzr(['help', 'commit'])
45
67
        self.assertEquals(err, '')
46
68
        self.assertContainsRe(out, r'--file[ =]MSGFILE')
47
69
 
48
70
    def test_unknown_short_opt(self):
49
 
        out, err = self.run_bzr_captured(['help', '-r'], retcode=3)
 
71
        out, err = self.run_bzr(['help', '-r'], retcode=3)
50
72
        self.assertContainsRe(err, r'no such option')
51
73
 
 
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)
 
79
 
 
80
    def test_set_short_name(self):
 
81
        o = option.Option('wiggle')
 
82
        o.set_short_name('w')
 
83
        self.assertEqual(o.short_name(), 'w')
 
84
 
 
85
    def test_old_short_names(self):
 
86
        # test the deprecated method for getting and setting short option
 
87
        # names
 
88
        expected_warning = (
 
89
            "access to SHORT_OPTIONS was deprecated in version 0.14."
 
90
            " Set the short option name when constructing the Option.",
 
91
            DeprecationWarning, 2)
 
92
        _warnings = []
 
93
        def capture_warning(message, category, stacklevel=None):
 
94
            _warnings.append((message, category, stacklevel))
 
95
        old_warning_method = symbol_versioning.warn
 
96
        try:
 
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
 
99
            # name.
 
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
 
106
            # value
 
107
            opts, args = parse([example_opt], ['-w', 'foo'])
 
108
            self.assertEqual(opts.example, True)
 
109
            self.assertEqual(args, ['foo'])
 
110
        finally:
 
111
            symbol_versioning.set_warning_method(old_warning_method)
 
112
 
52
113
    def test_allow_dash(self):
53
114
        """Test that we can pass a plain '-' as an argument."""
54
 
        self.assertEqual((['-'], {}), parse_args(cmd_commit(), ['-']))
 
115
        self.assertEqual(
 
116
            (['-'], {'fixes': []}), parse_args(cmd_commit(), ['-']))
 
117
 
 
118
    def parse(self, options, args):
 
119
        parser = option.get_optparser(dict((o.name, o) for o in options))
 
120
        return parser.parse_args(args)
55
121
 
56
122
    def test_conversion(self):
57
 
        def parse(options, args):
58
 
            parser = option.get_optparser(dict((o.name, o) for o in options))
59
 
            return parser.parse_args(args)
60
123
        options = [option.Option('hello')]
61
 
        opts, args = parse(options, ['--no-hello', '--hello'])
 
124
        opts, args = self.parse(options, ['--no-hello', '--hello'])
62
125
        self.assertEqual(True, opts.hello)
63
 
        opts, args = parse(options, [])
 
126
        opts, args = self.parse(options, [])
64
127
        self.assertEqual(option.OptionParser.DEFAULT_VALUE, opts.hello)
65
 
        opts, args = parse(options, ['--hello', '--no-hello'])
 
128
        opts, args = self.parse(options, ['--hello', '--no-hello'])
66
129
        self.assertEqual(False, opts.hello)
67
130
        options = [option.Option('number', type=int)]
68
 
        opts, args = parse(options, ['--number', '6'])
 
131
        opts, args = self.parse(options, ['--number', '6'])
69
132
        self.assertEqual(6, opts.number)
70
 
        self.assertRaises(errors.BzrCommandError, parse, options, ['--number'])
71
 
        self.assertRaises(errors.BzrCommandError, parse, options, 
 
133
        self.assertRaises(errors.BzrCommandError, self.parse, options,
 
134
                          ['--number'])
 
135
        self.assertRaises(errors.BzrCommandError, self.parse, options,
72
136
                          ['--no-number'])
73
137
 
 
138
    def test_registry_conversion(self):
 
139
        registry = bzrdir.BzrDirFormatRegistry()
 
140
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
141
        registry.register_metadir('two', 'RepositoryFormatKnit1', 'two help')
 
142
        registry.register_metadir('hidden', 'RepositoryFormatKnit1',
 
143
            'two help', hidden=True)
 
144
        registry.set_default('one')
 
145
        options = [option.RegistryOption('format', '', registry, str)]
 
146
        opts, args = self.parse(options, ['--format', 'one'])
 
147
        self.assertEqual({'format':'one'}, opts)
 
148
        opts, args = self.parse(options, ['--format', 'two'])
 
149
        self.assertEqual({'format':'two'}, opts)
 
150
        self.assertRaises(errors.BadOptionValue, self.parse, options,
 
151
                          ['--format', 'three'])
 
152
        self.assertRaises(errors.BzrCommandError, self.parse, options,
 
153
                          ['--two'])
 
154
        options = [option.RegistryOption('format', '', registry, str,
 
155
                   value_switches=True)]
 
156
        opts, args = self.parse(options, ['--two'])
 
157
        self.assertEqual({'format':'two'}, opts)
 
158
        opts, args = self.parse(options, ['--two', '--one'])
 
159
        self.assertEqual({'format':'one'}, opts)
 
160
        opts, args = self.parse(options, ['--two', '--one',
 
161
                                          '--format', 'two'])
 
162
        self.assertEqual({'format':'two'}, opts)
 
163
        options = [option.RegistryOption('format', '', registry, str,
 
164
                   enum_switch=False)]
 
165
        self.assertRaises(errors.BzrCommandError, self.parse, options,
 
166
                          ['--format', 'two'])
 
167
 
 
168
    def test_registry_converter(self):
 
169
        options = [option.RegistryOption('format', '',
 
170
                   bzrdir.format_registry, bzrdir.format_registry.make_bzrdir)]
 
171
        opts, args = self.parse(options, ['--format', 'knit'])
 
172
        self.assertIsInstance(opts.format.repository_format,
 
173
                              knitrepo.RepositoryFormatKnit1)
 
174
 
 
175
    def test_from_kwargs(self):
 
176
        my_option = option.RegistryOption.from_kwargs('my-option',
 
177
            help='test option', short='be short', be_long='go long')
 
178
        self.assertEqual(['my-option'],
 
179
            [x[0] for x in my_option.iter_switches()])
 
180
        my_option = option.RegistryOption.from_kwargs('my-option',
 
181
            help='test option', title="My option", short='be short',
 
182
            be_long='go long', value_switches=True)
 
183
        self.assertEqual(['my-option', 'be-long', 'short'],
 
184
            [x[0] for x in my_option.iter_switches()])
 
185
 
 
186
    def test_help(self):
 
187
        registry = bzrdir.BzrDirFormatRegistry()
 
188
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
189
        registry.register_metadir('two',
 
190
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
191
            'two help',
 
192
            )
 
193
        registry.register_metadir('hidden', 'RepositoryFormat7', 'hidden help',
 
194
            hidden=True)
 
195
        registry.set_default('one')
 
196
        options = [option.RegistryOption('format', 'format help', registry,
 
197
                   str, value_switches=True, title='Formats')]
 
198
        parser = option.get_optparser(dict((o.name, o) for o in options))
 
199
        value = parser.format_option_help()
 
200
        self.assertContainsRe(value, 'format.*format help')
 
201
        self.assertContainsRe(value, 'one.*one help')
 
202
        self.assertContainsRe(value, 'Formats:\n *--format')
 
203
        self.assertNotContainsRe(value, 'hidden help')
 
204
 
74
205
    def test_iter_switches(self):
75
206
        opt = option.Option('hello', help='fg')
76
207
        self.assertEqual(list(opt.iter_switches()),
81
212
        opt = option.Option('hello', help='fg', type=int, argname='gar')
82
213
        self.assertEqual(list(opt.iter_switches()),
83
214
                         [('hello', None, 'GAR', 'fg')])
84
 
 
85
 
#     >>> parse_args('log -r 500'.split())
86
 
#     (['log'], {'revision': [<RevisionSpec_int 500>]})
87
 
#     >>> parse_args('log -r500..600'.split())
88
 
#     (['log'], {'revision': [<RevisionSpec_int 500>, <RevisionSpec_int 600>]})
89
 
#     >>> parse_args('log -vr500..600'.split())
90
 
#     (['log'], {'verbose': True, 'revision': [<RevisionSpec_int 500>, <RevisionSpec_int 600>]})
91
 
#     >>> parse_args('log -rrevno:500..600'.split()) #the r takes an argument
92
 
#     (['log'], {'revision': [<RevisionSpec_revno revno:500>, <RevisionSpec_int 600>]})
 
215
        registry = bzrdir.BzrDirFormatRegistry()
 
216
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
217
        registry.register_metadir('two',
 
218
                'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
219
                'two help',
 
220
                )
 
221
        registry.set_default('one')
 
222
        opt = option.RegistryOption('format', 'format help', registry,
 
223
                                    value_switches=False)
 
224
        self.assertEqual(list(opt.iter_switches()),
 
225
                         [('format', None, 'ARG', 'format help')])
 
226
        opt = option.RegistryOption('format', 'format help', registry,
 
227
                                    value_switches=True)
 
228
        self.assertEqual(list(opt.iter_switches()),
 
229
                         [('format', None, 'ARG', 'format help'),
 
230
                          ('default', None, None, 'one help'),
 
231
                          ('one', None, None, 'one help'),
 
232
                          ('two', None, None, 'two help'),
 
233
                          ])
 
234
 
 
235
 
 
236
class TestListOptions(TestCase):
 
237
    """Tests for ListOption, used to specify lists on the command-line."""
 
238
 
 
239
    def parse(self, options, args):
 
240
        parser = option.get_optparser(dict((o.name, o) for o in options))
 
241
        return parser.parse_args(args)
 
242
 
 
243
    def test_list_option(self):
 
244
        options = [option.ListOption('hello', type=str)]
 
245
        opts, args = self.parse(options, ['--hello=world', '--hello=sailor'])
 
246
        self.assertEqual(['world', 'sailor'], opts.hello)
 
247
 
 
248
    def test_list_option_no_arguments(self):
 
249
        options = [option.ListOption('hello', type=str)]
 
250
        opts, args = self.parse(options, [])
 
251
        self.assertEqual([], opts.hello)
 
252
 
 
253
    def test_list_option_with_int_type(self):
 
254
        options = [option.ListOption('hello', type=int)]
 
255
        opts, args = self.parse(options, ['--hello=2', '--hello=3'])
 
256
        self.assertEqual([2, 3], opts.hello)
 
257
 
 
258
    def test_list_option_with_int_type_can_be_reset(self):
 
259
        options = [option.ListOption('hello', type=int)]
 
260
        opts, args = self.parse(options, ['--hello=2', '--hello=3',
 
261
                                          '--hello=-', '--hello=5'])
 
262
        self.assertEqual([5], opts.hello)
 
263
 
 
264
    def test_list_option_can_be_reset(self):
 
265
        """Passing an option of '-' to a list option should reset the list."""
 
266
        options = [option.ListOption('hello', type=str)]
 
267
        opts, args = self.parse(
 
268
            options, ['--hello=a', '--hello=b', '--hello=-', '--hello=c'])
 
269
        self.assertEqual(['c'], opts.hello)