/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_options.py

  • Committer: v.ladeuil+lp at free
  • Date: 2007-02-04 17:41:12 UTC
  • mto: (2323.7.1 redirection)
  • mto: This revision was merged to the branch mainline in revision 2390.
  • Revision ID: v.ladeuil+lp@free.fr-20070204174112-iv6gxzinnjddlaxj
Add tests for redirection. Preserve transport decorations.

* bzrlib/tests/test_http.py:
(TestRedirections): new tests.

* bzrlib/tests/HttpServer.py:
(HttpServer): Make server host and port public once the socket
have been established.

* bzrlib/tests/HTTPTestUtil.py:
(RedirectRequestHandler, HTTPServerRedirecting): New http test
server for redirections. Only a whole host can be redirected, so
far.

* bzrlib/errors.py:
(RedirectRequested.__init__): Add a 'qual_proto' oso that
transport decorations can be transmitted to redirected transport.
(RedirectRequested._requalify_url,
RedirectRequested.get_source_url,
RedirectRequested.get_target_url): New methods providing fully
decorated urls.

* bzrlib/bzrdir.py:
(BzrDir.open_from_transport): The redirection should preserve
transport decorations.
(BzrDirMetaFormat1): To be able to specialize bzr branches from
foreign branches, we need to register BzrDirMetaFormat1 as the
default control format (instead of BzrDirMetaFormat which is
abstract and can still be used by foreign branches).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
 
16
 
 
17
from bzrlib import (
 
18
    builtins,
 
19
    bzrdir,
 
20
    errors,
 
21
    option,
 
22
    repository,
 
23
    symbol_versioning,
 
24
    )
 
25
from bzrlib.builtins import cmd_commit, cmd_log, cmd_status
 
26
from bzrlib.commands import Command, parse_args
 
27
from bzrlib.tests import TestCase
 
28
 
 
29
def parse(options, args):
 
30
    parser = option.get_optparser(dict((o.name, o) for o in options))
 
31
    return parser.parse_args(args)
 
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
 
 
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
 
 
51
    def test_option_help(self):
 
52
        """Options have help strings."""
 
53
        out, err = self.run_bzr_captured(['commit', '--help'])
 
54
        self.assertContainsRe(out, r'--file(.|\n)*file containing commit'
 
55
                                   ' message')
 
56
        self.assertContainsRe(out, r'-h.*--help')
 
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
 
 
69
    def test_unknown_short_opt(self):
 
70
        out, err = self.run_bzr_captured(['help', '-r'], retcode=3)
 
71
        self.assertContainsRe(err, r'no such option')
 
72
 
 
73
    def test_get_short_name(self):
 
74
        file_opt = option.Option.OPTIONS['file']
 
75
        self.assertEquals(file_opt.short_name(), 'F')
 
76
        force_opt = option.Option.OPTIONS['force']
 
77
        self.assertEquals(force_opt.short_name(), None)
 
78
 
 
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
 
 
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)
 
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')
 
103
            self.assertEqual([expected_warning], _warnings)
 
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'])
 
109
        finally:
 
110
            symbol_versioning.set_warning_method(old_warning_method)
 
111
 
 
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
 
 
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)
 
119
 
 
120
    def test_conversion(self):
 
121
        options = [option.Option('hello')]
 
122
        opts, args = self.parse(options, ['--no-hello', '--hello'])
 
123
        self.assertEqual(True, opts.hello)
 
124
        opts, args = self.parse(options, [])
 
125
        self.assertEqual(option.OptionParser.DEFAULT_VALUE, opts.hello)
 
126
        opts, args = self.parse(options, ['--hello', '--no-hello'])
 
127
        self.assertEqual(False, opts.hello)
 
128
        options = [option.Option('number', type=int)]
 
129
        opts, args = self.parse(options, ['--number', '6'])
 
130
        self.assertEqual(6, opts.number)
 
131
        self.assertRaises(errors.BzrCommandError, self.parse, options,
 
132
                          ['--number'])
 
133
        self.assertRaises(errors.BzrCommandError, self.parse, options,
 
134
                          ['--no-number'])
 
135
 
 
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')
 
141
        options = [option.RegistryOption('format', '', registry, str)]
 
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)
 
146
        self.assertRaises(errors.BadOptionValue, self.parse, options,
 
147
                          ['--format', 'three'])
 
148
        self.assertRaises(errors.BzrCommandError, self.parse, options,
 
149
                          ['--two'])
 
150
        options = [option.RegistryOption('format', '', registry, str,
 
151
                   value_switches=True)]
 
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)
 
156
        opts, args = self.parse(options, ['--two', '--one',
 
157
                                          '--format', 'two'])
 
158
        self.assertEqual({'format':'two'}, opts)
 
159
 
 
160
    def test_registry_converter(self):
 
161
        options = [option.RegistryOption('format', '',
 
162
                   bzrdir.format_registry, builtins.get_format_type)]
 
163
        opts, args = self.parse(options, ['--format', 'knit'])
 
164
        self.assertIsInstance(opts.format.repository_format,
 
165
                              repository.RepositoryFormatKnit1)
 
166
 
 
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,
 
173
                   str, value_switches=True)]
 
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')
 
178
 
 
179
    def test_iter_switches(self):
 
180
        opt = option.Option('hello', help='fg')
 
181
        self.assertEqual(list(opt.iter_switches()),
 
182
                         [('hello', None, None, 'fg')])
 
183
        opt = option.Option('hello', help='fg', type=int)
 
184
        self.assertEqual(list(opt.iter_switches()),
 
185
                         [('hello', None, 'ARG', 'fg')])
 
186
        opt = option.Option('hello', help='fg', type=int, argname='gar')
 
187
        self.assertEqual(list(opt.iter_switches()),
 
188
                         [('hello', None, 'GAR', 'fg')])
 
189
        registry = bzrdir.BzrDirFormatRegistry()
 
190
        registry.register_metadir('one', 'RepositoryFormat7', 'one help')
 
191
        registry.register_metadir('two', 'RepositoryFormatKnit1', 'two help')
 
192
        registry.set_default('one')
 
193
        opt = option.RegistryOption('format', 'format help', registry,
 
194
                                    value_switches=False)
 
195
        self.assertEqual(list(opt.iter_switches()),
 
196
                         [('format', None, 'ARG', 'format help')])
 
197
        opt = option.RegistryOption('format', 'format help', registry,
 
198
                                    value_switches=True)
 
199
        self.assertEqual(list(opt.iter_switches()),
 
200
                         [('format', None, 'ARG', 'format help'),
 
201
                          ('default', None, None, 'one help'),
 
202
                          ('one', None, None, 'one help'),
 
203
                          ('two', None, None, 'two help'),
 
204
                          ])
 
205
 
 
206
#     >>> parse_args('log -r 500'.split())
 
207
#     (['log'], {'revision': [<RevisionSpec_int 500>]})
 
208
#     >>> parse_args('log -r500..600'.split())
 
209
#     (['log'], {'revision': [<RevisionSpec_int 500>, <RevisionSpec_int 600>]})
 
210
#     >>> parse_args('log -vr500..600'.split())
 
211
#     (['log'], {'verbose': True, 'revision': [<RevisionSpec_int 500>, <RevisionSpec_int 600>]})
 
212
#     >>> parse_args('log -rrevno:500..600'.split()) #the r takes an argument
 
213
#     (['log'], {'revision': [<RevisionSpec_revno revno:500>, <RevisionSpec_int 600>]})