/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
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
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
28
2227.1.4 by mbp at sourcefrog
add test that legacy SHORT_OPTIONS really works, and set_short_name
29
def parse(options, args):
30
    parser = option.get_optparser(dict((o.name, o) for o in options))
31
    return parser.parse_args(args)
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
32
33
class OptionTests(TestCase):
34
    """Command-line option tests"""
35
36
    def test_parse_args(self):
37
        """Option parser"""
38
        eq = self.assertEquals
39
        eq(parse_args(cmd_commit(), ['--help']),
40
           ([], {'help': True}))
41
        eq(parse_args(cmd_commit(), ['--message=biter']),
42
           ([], {'message': 'biter'}))
43
        ## eq(parse_args(cmd_log(),  '-r 500'.split()),
44
        ##   ([], {'revision': RevisionSpec_int(500)}))
45
1185.16.49 by mbp at sourcefrog
- more refactoring and tests of commandline
46
    def test_no_more_opts(self):
47
        """Terminated options"""
48
        self.assertEquals(parse_args(cmd_commit(), ['--', '-file-with-dashes']),
49
                          (['-file-with-dashes'], {}))
50
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
51
    def test_option_help(self):
52
        """Options have help strings."""
53
        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
54
        self.assertContainsRe(out, r'--file(.|\n)*file containing commit'
55
                                   ' message')
56
        self.assertContainsRe(out, r'-h.*--help')
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
57
58
    def test_option_help_global(self):
59
        """Global options have help strings."""
60
        out, err = self.run_bzr_captured(['help', 'status'])
61
        self.assertContainsRe(out, r'--show-ids.*show internal object')
62
63
    def test_option_arg_help(self):
64
        """Help message shows option arguments."""
65
        out, err = self.run_bzr_captured(['help', 'commit'])
66
        self.assertEquals(err, '')
67
        self.assertContainsRe(out, r'--file[ =]MSGFILE')
68
1185.35.24 by Aaron Bentley
Fixed handling of short options not accepted by the command
69
    def test_unknown_short_opt(self):
70
        out, err = self.run_bzr_captured(['help', '-r'], retcode=3)
1857.1.1 by Aaron Bentley
Use optparse for parsing options
71
        self.assertContainsRe(err, r'no such option')
1185.35.24 by Aaron Bentley
Fixed handling of short options not accepted by the command
72
2190.2.1 by Martin Pool
remove global registration of short options
73
    def test_get_short_name(self):
74
        file_opt = option.Option.OPTIONS['file']
2227.1.1 by mbp at sourcefrog
Back out previous incompatible change: Option.short_name is now again
75
        self.assertEquals(file_opt.short_name(), 'F')
2190.2.1 by Martin Pool
remove global registration of short options
76
        force_opt = option.Option.OPTIONS['force']
2227.1.1 by mbp at sourcefrog
Back out previous incompatible change: Option.short_name is now again
77
        self.assertEquals(force_opt.short_name(), None)
2190.2.1 by Martin Pool
remove global registration of short options
78
2227.1.4 by mbp at sourcefrog
add test that legacy SHORT_OPTIONS really works, and set_short_name
79
    def test_set_short_name(self):
80
        o = option.Option('wiggle')
81
        o.set_short_name('w')
82
        self.assertEqual(o.short_name(), 'w')
83
2227.1.3 by mbp at sourcefrog
Restore access to SHORT_OPTIONS for compatibility
84
    def test_old_short_names(self):
85
        # test the deprecated method for getting and setting short option
86
        # names
87
        expected_warning = (
88
            "access to SHORT_OPTIONS was deprecated in version 0.14."
89
            " Set the short option name when constructing the Option.",
90
            DeprecationWarning, 2)
91
        _warnings = []
92
        def capture_warning(message, category, stacklevel=None):
93
            _warnings.append((message, category, stacklevel))
94
        old_warning_method = symbol_versioning.warn
95
        try:
96
            # an example of the kind of thing plugins might want to do through
97
            # the old interface - make a new option and then give it a short
98
            # name.
99
            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
100
            example_opt = option.Option('example', help='example option')
101
            option.Option.SHORT_OPTIONS['w'] = example_opt
102
            self.assertEqual(example_opt.short_name(), 'w')
2227.1.3 by mbp at sourcefrog
Restore access to SHORT_OPTIONS for compatibility
103
            self.assertEqual([expected_warning], _warnings)
2227.1.4 by mbp at sourcefrog
add test that legacy SHORT_OPTIONS really works, and set_short_name
104
            # now check that it can actually be parsed with the registered
105
            # value
106
            opts, args = parse([example_opt], ['-w', 'foo'])
107
            self.assertEqual(opts.example, True)
108
            self.assertEqual(args, ['foo'])
2227.1.3 by mbp at sourcefrog
Restore access to SHORT_OPTIONS for compatibility
109
        finally:
110
            symbol_versioning.set_warning_method(old_warning_method)
111
1852.1.1 by John Arbash Meinel
Allow a plain '-' to be supplied as an argument. bug #50984
112
    def test_allow_dash(self):
113
        """Test that we can pass a plain '-' as an argument."""
114
        self.assertEqual((['-'], {}), parse_args(cmd_commit(), ['-']))
115
2221.4.1 by Aaron Bentley
Get registry options working
116
    def parse(self, options, args):
117
        parser = option.get_optparser(dict((o.name, o) for o in options))
118
        return parser.parse_args(args)
2221.4.9 by Aaron Bentley
Zap trailing whitespace
119
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
120
    def test_conversion(self):
121
        options = [option.Option('hello')]
2221.4.1 by Aaron Bentley
Get registry options working
122
        opts, args = self.parse(options, ['--no-hello', '--hello'])
1857.1.16 by Aaron Bentley
Add tests for iter_switches
123
        self.assertEqual(True, opts.hello)
2221.4.1 by Aaron Bentley
Get registry options working
124
        opts, args = self.parse(options, [])
1857.1.16 by Aaron Bentley
Add tests for iter_switches
125
        self.assertEqual(option.OptionParser.DEFAULT_VALUE, opts.hello)
2221.4.1 by Aaron Bentley
Get registry options working
126
        opts, args = self.parse(options, ['--hello', '--no-hello'])
1857.1.22 by Aaron Bentley
Negations set value to False, instead of Optparser.DEFAULT_VALUE
127
        self.assertEqual(False, opts.hello)
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
128
        options = [option.Option('number', type=int)]
2221.4.1 by Aaron Bentley
Get registry options working
129
        opts, args = self.parse(options, ['--number', '6'])
1857.1.16 by Aaron Bentley
Add tests for iter_switches
130
        self.assertEqual(6, opts.number)
2221.4.9 by Aaron Bentley
Zap trailing whitespace
131
        self.assertRaises(errors.BzrCommandError, self.parse, options,
2221.4.1 by Aaron Bentley
Get registry options working
132
                          ['--number'])
2221.4.9 by Aaron Bentley
Zap trailing whitespace
133
        self.assertRaises(errors.BzrCommandError, self.parse, options,
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
134
                          ['--no-number'])
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
135
2221.4.1 by Aaron Bentley
Get registry options working
136
    def test_registry_conversion(self):
137
        registry = bzrdir.BzrDirFormatRegistry()
138
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
139
        registry.register_metadir('two', 'RepositoryFormatKnit1', 'two help')
140
        registry.set_default('one')
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
141
        options = [option.RegistryOption('format', '', registry, str)]
2221.4.1 by Aaron Bentley
Get registry options working
142
        opts, args = self.parse(options, ['--format', 'one'])
143
        self.assertEqual({'format':'one'}, opts)
144
        opts, args = self.parse(options, ['--format', 'two'])
145
        self.assertEqual({'format':'two'}, opts)
2221.4.9 by Aaron Bentley
Zap trailing whitespace
146
        self.assertRaises(errors.BadOptionValue, self.parse, options,
2221.4.1 by Aaron Bentley
Get registry options working
147
                          ['--format', 'three'])
2221.4.9 by Aaron Bentley
Zap trailing whitespace
148
        self.assertRaises(errors.BzrCommandError, self.parse, options,
2221.4.1 by Aaron Bentley
Get registry options working
149
                          ['--two'])
2221.4.9 by Aaron Bentley
Zap trailing whitespace
150
        options = [option.RegistryOption('format', '', registry, str,
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
151
                   value_switches=True)]
2221.4.1 by Aaron Bentley
Get registry options working
152
        opts, args = self.parse(options, ['--two'])
153
        self.assertEqual({'format':'two'}, opts)
154
        opts, args = self.parse(options, ['--two', '--one'])
155
        self.assertEqual({'format':'one'}, opts)
2221.4.9 by Aaron Bentley
Zap trailing whitespace
156
        opts, args = self.parse(options, ['--two', '--one',
2221.4.1 by Aaron Bentley
Get registry options working
157
                                          '--format', 'two'])
158
        self.assertEqual({'format':'two'}, opts)
159
160
    def test_registry_converter(self):
2221.4.9 by Aaron Bentley
Zap trailing whitespace
161
        options = [option.RegistryOption('format', '',
2204.5.5 by Aaron Bentley
Remove RepositoryFormat.set_default_format, deprecate get_format_type
162
                   bzrdir.format_registry, bzrdir.format_registry.make_bzrdir)]
2221.4.1 by Aaron Bentley
Get registry options working
163
        opts, args = self.parse(options, ['--format', 'knit'])
164
        self.assertIsInstance(opts.format.repository_format,
165
                              repository.RepositoryFormatKnit1)
166
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
167
    def test_help(self):
168
        registry = bzrdir.BzrDirFormatRegistry()
169
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
170
        registry.register_metadir('two', 'RepositoryFormatKnit1', 'two help')
171
        registry.set_default('one')
172
        options = [option.RegistryOption('format', 'format help', registry,
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
173
                   str, value_switches=True, title='Formats')]
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
174
        parser = option.get_optparser(dict((o.name, o) for o in options))
175
        value = parser.format_option_help()
176
        self.assertContainsRe(value, 'format.*format help')
177
        self.assertContainsRe(value, 'one.*one help')
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
178
        self.assertContainsRe(value, 'Formats:\n *--format')
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
179
1857.1.16 by Aaron Bentley
Add tests for iter_switches
180
    def test_iter_switches(self):
181
        opt = option.Option('hello', help='fg')
182
        self.assertEqual(list(opt.iter_switches()),
183
                         [('hello', None, None, 'fg')])
184
        opt = option.Option('hello', help='fg', type=int)
185
        self.assertEqual(list(opt.iter_switches()),
186
                         [('hello', None, 'ARG', 'fg')])
187
        opt = option.Option('hello', help='fg', type=int, argname='gar')
188
        self.assertEqual(list(opt.iter_switches()),
189
                         [('hello', None, 'GAR', 'fg')])
2221.4.4 by Aaron Bentley
Fix iter_switches behavior when value_switches is true
190
        registry = bzrdir.BzrDirFormatRegistry()
191
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
192
        registry.register_metadir('two', 'RepositoryFormatKnit1', 'two help')
193
        registry.set_default('one')
194
        opt = option.RegistryOption('format', 'format help', registry,
195
                                    value_switches=False)
196
        self.assertEqual(list(opt.iter_switches()),
197
                         [('format', None, 'ARG', 'format help')])
198
        opt = option.RegistryOption('format', 'format help', registry,
199
                                    value_switches=True)
200
        self.assertEqual(list(opt.iter_switches()),
201
                         [('format', None, 'ARG', 'format help'),
2221.4.9 by Aaron Bentley
Zap trailing whitespace
202
                          ('default', None, None, 'one help'),
203
                          ('one', None, None, 'one help'),
204
                          ('two', None, None, 'two help'),
2221.4.4 by Aaron Bentley
Fix iter_switches behavior when value_switches is true
205
                          ])
1857.1.16 by Aaron Bentley
Add tests for iter_switches
206
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
207
#     >>> parse_args('log -r 500'.split())
208
#     (['log'], {'revision': [<RevisionSpec_int 500>]})
209
#     >>> parse_args('log -r500..600'.split())
210
#     (['log'], {'revision': [<RevisionSpec_int 500>, <RevisionSpec_int 600>]})
211
#     >>> parse_args('log -vr500..600'.split())
212
#     (['log'], {'verbose': True, 'revision': [<RevisionSpec_int 500>, <RevisionSpec_int 600>]})
213
#     >>> parse_args('log -rrevno:500..600'.split()) #the r takes an argument
214
#     (['log'], {'revision': [<RevisionSpec_revno revno:500>, <RevisionSpec_int 600>]})