~bzr-pqm/bzr/bzr.dev

2227.1.3 by mbp at sourcefrog
Restore access to SHORT_OPTIONS for compatibility
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
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
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
16
2221.4.1 by Aaron Bentley
Get registry options working
17
from bzrlib import (
18
    builtins,
19
    bzrdir,
20
    errors,
21
    option,
22
    repository,
2221.4.8 by Aaron Bentley
Merge bzr.dev
23
    symbol_versioning,
2221.4.1 by Aaron Bentley
Get registry options working
24
    )
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
25
from bzrlib.builtins import cmd_commit, cmd_log, cmd_status
26
from bzrlib.commands import Command, parse_args
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
27
from bzrlib.tests import TestCase
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
28
from bzrlib.repofmt import knitrepo
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
29
2227.1.4 by mbp at sourcefrog
add test that legacy SHORT_OPTIONS really works, and set_short_name
30
def parse(options, args):
31
    parser = option.get_optparser(dict((o.name, o) for o in options))
32
    return parser.parse_args(args)
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
33
34
class OptionTests(TestCase):
35
    """Command-line option tests"""
36
37
    def test_parse_args(self):
38
        """Option parser"""
39
        eq = self.assertEquals
40
        eq(parse_args(cmd_commit(), ['--help']),
41
           ([], {'help': True}))
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)}))
46
1185.16.49 by mbp at sourcefrog
- more refactoring and tests of commandline
47
    def test_no_more_opts(self):
48
        """Terminated options"""
49
        self.assertEquals(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
50
                          (['-file-with-dashes'], {}))
51
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
52
    def test_option_help(self):
53
        """Options have help strings."""
54
        out, err = self.run_bzr_captured(['commit', '--help'])
1857.1.12 by Aaron Bentley
Fix a bunch of test cases that assumed --merge-type or log-format
55
        self.assertContainsRe(out, r'--file(.|\n)*file containing commit'
56
                                   ' message')
57
        self.assertContainsRe(out, r'-h.*--help')
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
58
59
    def test_option_help_global(self):
60
        """Global options have help strings."""
61
        out, err = self.run_bzr_captured(['help', 'status'])
62
        self.assertContainsRe(out, r'--show-ids.*show internal object')
63
64
    def test_option_arg_help(self):
65
        """Help message shows option arguments."""
66
        out, err = self.run_bzr_captured(['help', 'commit'])
67
        self.assertEquals(err, '')
68
        self.assertContainsRe(out, r'--file[ =]MSGFILE')
69
1185.35.24 by Aaron Bentley
Fixed handling of short options not accepted by the command
70
    def test_unknown_short_opt(self):
71
        out, err = self.run_bzr_captured(['help', '-r'], retcode=3)
1857.1.1 by Aaron Bentley
Use optparse for parsing options
72
        self.assertContainsRe(err, r'no such option')
1185.35.24 by Aaron Bentley
Fixed handling of short options not accepted by the command
73
2190.2.1 by Martin Pool
remove global registration of short options
74
    def test_get_short_name(self):
75
        file_opt = option.Option.OPTIONS['file']
2227.1.1 by mbp at sourcefrog
Back out previous incompatible change: Option.short_name is now again
76
        self.assertEquals(file_opt.short_name(), 'F')
2190.2.1 by Martin Pool
remove global registration of short options
77
        force_opt = option.Option.OPTIONS['force']
2227.1.1 by mbp at sourcefrog
Back out previous incompatible change: Option.short_name is now again
78
        self.assertEquals(force_opt.short_name(), None)
2190.2.1 by Martin Pool
remove global registration of short options
79
2227.1.4 by mbp at sourcefrog
add test that legacy SHORT_OPTIONS really works, and set_short_name
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
2227.1.3 by mbp at sourcefrog
Restore access to SHORT_OPTIONS for compatibility
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)
2227.1.4 by mbp at sourcefrog
add test that legacy SHORT_OPTIONS really works, and set_short_name
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')
2227.1.3 by mbp at sourcefrog
Restore access to SHORT_OPTIONS for compatibility
104
            self.assertEqual([expected_warning], _warnings)
2227.1.4 by mbp at sourcefrog
add test that legacy SHORT_OPTIONS really works, and set_short_name
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'])
2227.1.3 by mbp at sourcefrog
Restore access to SHORT_OPTIONS for compatibility
110
        finally:
111
            symbol_versioning.set_warning_method(old_warning_method)
112
1852.1.1 by John Arbash Meinel
Allow a plain '-' to be supplied as an argument. bug #50984
113
    def test_allow_dash(self):
114
        """Test that we can pass a plain '-' as an argument."""
115
        self.assertEqual((['-'], {}), parse_args(cmd_commit(), ['-']))
116
2221.4.1 by Aaron Bentley
Get registry options working
117
    def parse(self, options, args):
118
        parser = option.get_optparser(dict((o.name, o) for o in options))
119
        return parser.parse_args(args)
2221.4.9 by Aaron Bentley
Zap trailing whitespace
120
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
121
    def test_conversion(self):
122
        options = [option.Option('hello')]
2221.4.1 by Aaron Bentley
Get registry options working
123
        opts, args = self.parse(options, ['--no-hello', '--hello'])
1857.1.16 by Aaron Bentley
Add tests for iter_switches
124
        self.assertEqual(True, opts.hello)
2221.4.1 by Aaron Bentley
Get registry options working
125
        opts, args = self.parse(options, [])
1857.1.16 by Aaron Bentley
Add tests for iter_switches
126
        self.assertEqual(option.OptionParser.DEFAULT_VALUE, opts.hello)
2221.4.1 by Aaron Bentley
Get registry options working
127
        opts, args = self.parse(options, ['--hello', '--no-hello'])
1857.1.22 by Aaron Bentley
Negations set value to False, instead of Optparser.DEFAULT_VALUE
128
        self.assertEqual(False, opts.hello)
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
129
        options = [option.Option('number', type=int)]
2221.4.1 by Aaron Bentley
Get registry options working
130
        opts, args = self.parse(options, ['--number', '6'])
1857.1.16 by Aaron Bentley
Add tests for iter_switches
131
        self.assertEqual(6, opts.number)
2221.4.9 by Aaron Bentley
Zap trailing whitespace
132
        self.assertRaises(errors.BzrCommandError, self.parse, options,
2221.4.1 by Aaron Bentley
Get registry options working
133
                          ['--number'])
2221.4.9 by Aaron Bentley
Zap trailing whitespace
134
        self.assertRaises(errors.BzrCommandError, self.parse, options,
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
135
                          ['--no-number'])
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
136
2221.4.1 by Aaron Bentley
Get registry options working
137
    def test_registry_conversion(self):
138
        registry = bzrdir.BzrDirFormatRegistry()
139
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
140
        registry.register_metadir('two', 'RepositoryFormatKnit1', 'two help')
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
141
        registry.register_metadir('hidden', 'RepositoryFormatKnit1',
142
            'two help', hidden=True)
2221.4.1 by Aaron Bentley
Get registry options working
143
        registry.set_default('one')
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
144
        options = [option.RegistryOption('format', '', registry, str)]
2221.4.1 by Aaron Bentley
Get registry options working
145
        opts, args = self.parse(options, ['--format', 'one'])
146
        self.assertEqual({'format':'one'}, opts)
147
        opts, args = self.parse(options, ['--format', 'two'])
148
        self.assertEqual({'format':'two'}, opts)
2221.4.9 by Aaron Bentley
Zap trailing whitespace
149
        self.assertRaises(errors.BadOptionValue, self.parse, options,
2221.4.1 by Aaron Bentley
Get registry options working
150
                          ['--format', 'three'])
2221.4.9 by Aaron Bentley
Zap trailing whitespace
151
        self.assertRaises(errors.BzrCommandError, self.parse, options,
2221.4.1 by Aaron Bentley
Get registry options working
152
                          ['--two'])
2221.4.9 by Aaron Bentley
Zap trailing whitespace
153
        options = [option.RegistryOption('format', '', registry, str,
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
154
                   value_switches=True)]
2221.4.1 by Aaron Bentley
Get registry options working
155
        opts, args = self.parse(options, ['--two'])
156
        self.assertEqual({'format':'two'}, opts)
157
        opts, args = self.parse(options, ['--two', '--one'])
158
        self.assertEqual({'format':'one'}, opts)
2221.4.9 by Aaron Bentley
Zap trailing whitespace
159
        opts, args = self.parse(options, ['--two', '--one',
2221.4.1 by Aaron Bentley
Get registry options working
160
                                          '--format', 'two'])
161
        self.assertEqual({'format':'two'}, opts)
1551.12.18 by Aaron Bentley
Allow RegistryOption to omit the value-taking option
162
        options = [option.RegistryOption('format', '', registry, str,
163
                   enum_switch=False)]
164
        self.assertRaises(errors.BzrCommandError, self.parse, options,
165
                          ['--format', 'two'])
2221.4.1 by Aaron Bentley
Get registry options working
166
167
    def test_registry_converter(self):
2221.4.9 by Aaron Bentley
Zap trailing whitespace
168
        options = [option.RegistryOption('format', '',
2204.5.5 by Aaron Bentley
Remove RepositoryFormat.set_default_format, deprecate get_format_type
169
                   bzrdir.format_registry, bzrdir.format_registry.make_bzrdir)]
2221.4.1 by Aaron Bentley
Get registry options working
170
        opts, args = self.parse(options, ['--format', 'knit'])
171
        self.assertIsInstance(opts.format.repository_format,
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
172
                              knitrepo.RepositoryFormatKnit1)
2221.4.1 by Aaron Bentley
Get registry options working
173
1551.12.24 by Aaron Bentley
Add RegistryOption.from_swargs to simplify simple registry options
174
    def test_from_kwargs(self):
175
        my_option = option.RegistryOption.from_kwargs('my-option',
176
            help='test option', short='be short', be_long='go long')
177
        self.assertEqual(['my-option'],
178
            [x[0] for x in my_option.iter_switches()])
179
        my_option = option.RegistryOption.from_kwargs('my-option',
180
            help='test option', title="My option", short='be short',
181
            be_long='go long', value_switches=True)
182
        self.assertEqual(['my-option', 'be-long', 'short'],
183
            [x[0] for x in my_option.iter_switches()])
184
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
185
    def test_help(self):
186
        registry = bzrdir.BzrDirFormatRegistry()
187
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
2241.1.21 by Martin Pool
Change register_metadir to take fully-qualified repository class name.
188
        registry.register_metadir('two',
189
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
190
            'two help',
191
            )
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
192
        registry.register_metadir('hidden', 'RepositoryFormat7', 'hidden help',
193
            hidden=True)
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
194
        registry.set_default('one')
195
        options = [option.RegistryOption('format', 'format help', registry,
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
196
                   str, value_switches=True, title='Formats')]
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
197
        parser = option.get_optparser(dict((o.name, o) for o in options))
198
        value = parser.format_option_help()
199
        self.assertContainsRe(value, 'format.*format help')
200
        self.assertContainsRe(value, 'one.*one help')
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
201
        self.assertContainsRe(value, 'Formats:\n *--format')
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
202
        self.assertNotContainsRe(value, 'hidden help')
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
203
1857.1.16 by Aaron Bentley
Add tests for iter_switches
204
    def test_iter_switches(self):
205
        opt = option.Option('hello', help='fg')
206
        self.assertEqual(list(opt.iter_switches()),
207
                         [('hello', None, None, 'fg')])
208
        opt = option.Option('hello', help='fg', type=int)
209
        self.assertEqual(list(opt.iter_switches()),
210
                         [('hello', None, 'ARG', 'fg')])
211
        opt = option.Option('hello', help='fg', type=int, argname='gar')
212
        self.assertEqual(list(opt.iter_switches()),
213
                         [('hello', None, 'GAR', 'fg')])
2221.4.4 by Aaron Bentley
Fix iter_switches behavior when value_switches is true
214
        registry = bzrdir.BzrDirFormatRegistry()
215
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
2241.1.21 by Martin Pool
Change register_metadir to take fully-qualified repository class name.
216
        registry.register_metadir('two',
217
                'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
218
                'two help',
219
                )
2221.4.4 by Aaron Bentley
Fix iter_switches behavior when value_switches is true
220
        registry.set_default('one')
221
        opt = option.RegistryOption('format', 'format help', registry,
222
                                    value_switches=False)
223
        self.assertEqual(list(opt.iter_switches()),
224
                         [('format', None, 'ARG', 'format help')])
225
        opt = option.RegistryOption('format', 'format help', registry,
226
                                    value_switches=True)
227
        self.assertEqual(list(opt.iter_switches()),
228
                         [('format', None, 'ARG', 'format help'),
2221.4.9 by Aaron Bentley
Zap trailing whitespace
229
                          ('default', None, None, 'one help'),
230
                          ('one', None, None, 'one help'),
231
                          ('two', None, None, 'two help'),
2221.4.4 by Aaron Bentley
Fix iter_switches behavior when value_switches is true
232
                          ])
1857.1.16 by Aaron Bentley
Add tests for iter_switches
233
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
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>]})