/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
6614.1.1 by Vincent Ladeuil
Fix assert_ being deprecated by using assertTrue.
1
# Copyright (C) 2005-2012, 2016 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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
16
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
17
import re
18
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
19
from .. import (
6695.5.5 by Jelmer Vernooij
Fix import.
20
    bzr,
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
21
    commands,
5363.2.9 by Jelmer Vernooij
Fix some tests.
22
    controldir,
2221.4.1 by Aaron Bentley
Get registry options working
23
    errors,
24
    option,
5945.1.1 by Martin von Gagern
Allow -s as shorthand for --log-format=short.
25
    registry,
2221.4.1 by Aaron Bentley
Get registry options working
26
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
27
from ..builtins import cmd_commit
28
from ..commands import parse_args
29
from . import TestCase
6670.4.5 by Jelmer Vernooij
Move breezy.repofmt contents to breezy.bzr.
30
from ..bzr import knitrepo
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
31
2376.4.22 by Jonathan Lange
Variety of whitespace cleanups, tightening of tests and docstring changes in
32
2227.1.4 by mbp at sourcefrog
add test that legacy SHORT_OPTIONS really works, and set_short_name
33
def parse(options, args):
7045.4.23 by Jelmer Vernooij
Fix some help tests.
34
    parser = option.get_optparser(options)
2227.1.4 by mbp at sourcefrog
add test that legacy SHORT_OPTIONS really works, and set_short_name
35
    return parser.parse_args(args)
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
36
2376.4.22 by Jonathan Lange
Variety of whitespace cleanups, tightening of tests and docstring changes in
37
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
38
class OptionTests(TestCase):
39
    """Command-line option tests"""
40
41
    def test_parse_args(self):
42
        """Option parser"""
3602.1.5 by Robert Collins
Fixups for test_options due to the changes to cmd_commit - insta-review by spiv.
43
        # XXX: Using cmd_commit makes these tests overly sensitive to changes
44
        # to cmd_commit, when they are meant to be about option parsing in
45
        # general.
6161.1.1 by Vincent Ladeuil
Allow config options to be overridden from the command line
46
        self.assertEqual(
7143.15.6 by Jelmer Vernooij
Merge trunk.
47
            ([], {'author': [], 'exclude': [], 'fixes': [], 'help': True,
48
                  'bugs': []}),
7143.16.12 by Jelmer Vernooij
Fix E131.
49
            parse_args(cmd_commit(), ['--help']))
6161.1.1 by Vincent Ladeuil
Allow config options to be overridden from the command line
50
        self.assertEqual(
7143.15.6 by Jelmer Vernooij
Merge trunk.
51
            ([], {'author': [], 'exclude': [], 'fixes': [], 'message': 'biter',
52
                  'bugs': []}),
7143.16.12 by Jelmer Vernooij
Fix E131.
53
            parse_args(cmd_commit(), ['--message=biter']))
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
54
1185.16.49 by mbp at sourcefrog
- more refactoring and tests of commandline
55
    def test_no_more_opts(self):
56
        """Terminated options"""
6161.1.1 by Vincent Ladeuil
Allow config options to be overridden from the command line
57
        self.assertEqual(
7143.15.6 by Jelmer Vernooij
Merge trunk.
58
            (['-file-with-dashes'], {
59
                'author': [], 'exclude': [], 'fixes': [], 'bugs': []}),
6161.1.1 by Vincent Ladeuil
Allow config options to be overridden from the command line
60
            parse_args(cmd_commit(), ['--', '-file-with-dashes']))
1185.16.49 by mbp at sourcefrog
- more refactoring and tests of commandline
61
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
62
    def test_option_help(self):
63
        """Options have help strings."""
2552.2.2 by Vincent Ladeuil
Enforce run_bzr(string) where possible.
64
        out, err = self.run_bzr('commit --help')
2598.1.4 by Martin Pool
Fix up tests for option help cleanups
65
        self.assertContainsRe(out,
7143.15.2 by Jelmer Vernooij
Run autopep8.
66
                              r'--file(.|\n)*Take commit message from this file\.')
1857.1.12 by Aaron Bentley
Fix a bunch of test cases that assumed --merge-type or log-format
67
        self.assertContainsRe(out, r'-h.*--help')
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
68
69
    def test_option_help_global(self):
70
        """Global options have help strings."""
2552.2.2 by Vincent Ladeuil
Enforce run_bzr(string) where possible.
71
        out, err = self.run_bzr('help status')
2598.1.4 by Martin Pool
Fix up tests for option help cleanups
72
        self.assertContainsRe(out, r'--show-ids.*Show internal object.')
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
73
6171.2.1 by Vincent Ladeuil
Global options respect their hidden attribute
74
    def test_option_help_global_hidden(self):
75
        """Hidden global options have no help strings."""
76
        out, err = self.run_bzr('help log')
7027.4.2 by Jelmer Vernooij
Use StringIOWithEncoding in run_bzr.
77
        self.assertNotContainsRe(out, r'--message')
6171.2.1 by Vincent Ladeuil
Global options respect their hidden attribute
78
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
79
    def test_option_arg_help(self):
80
        """Help message shows option arguments."""
2552.2.2 by Vincent Ladeuil
Enforce run_bzr(string) where possible.
81
        out, err = self.run_bzr('help commit')
3602.1.5 by Robert Collins
Fixups for test_options due to the changes to cmd_commit - insta-review by spiv.
82
        self.assertEqual(err, '')
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
83
        self.assertContainsRe(out, r'--file[ =]MSGFILE')
84
1185.35.24 by Aaron Bentley
Fixed handling of short options not accepted by the command
85
    def test_unknown_short_opt(self):
2552.2.2 by Vincent Ladeuil
Enforce run_bzr(string) where possible.
86
        out, err = self.run_bzr('help -r', retcode=3)
7058.4.12 by Jelmer Vernooij
Fix option test.
87
        self.assertContainsRe(err, r'no such option')
1185.35.24 by Aaron Bentley
Fixed handling of short options not accepted by the command
88
2227.1.4 by mbp at sourcefrog
add test that legacy SHORT_OPTIONS really works, and set_short_name
89
    def test_set_short_name(self):
90
        o = option.Option('wiggle')
91
        o.set_short_name('w')
92
        self.assertEqual(o.short_name(), 'w')
93
1852.1.1 by John Arbash Meinel
Allow a plain '-' to be supplied as an argument. bug #50984
94
    def test_allow_dash(self):
95
        """Test that we can pass a plain '-' as an argument."""
3602.1.5 by Robert Collins
Fixups for test_options due to the changes to cmd_commit - insta-review by spiv.
96
        self.assertEqual((['-']), parse_args(cmd_commit(), ['-'])[0])
1852.1.1 by John Arbash Meinel
Allow a plain '-' to be supplied as an argument. bug #50984
97
2221.4.1 by Aaron Bentley
Get registry options working
98
    def parse(self, options, args):
7045.4.23 by Jelmer Vernooij
Fix some help tests.
99
        parser = option.get_optparser(options)
2221.4.1 by Aaron Bentley
Get registry options working
100
        return parser.parse_args(args)
2221.4.9 by Aaron Bentley
Zap trailing whitespace
101
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
102
    def test_conversion(self):
103
        options = [option.Option('hello')]
2221.4.1 by Aaron Bentley
Get registry options working
104
        opts, args = self.parse(options, ['--no-hello', '--hello'])
1857.1.16 by Aaron Bentley
Add tests for iter_switches
105
        self.assertEqual(True, opts.hello)
2221.4.1 by Aaron Bentley
Get registry options working
106
        opts, args = self.parse(options, [])
2768.1.6 by Ian Clatworthy
Fix existing option and help tests
107
        self.assertFalse(hasattr(opts, 'hello'))
2221.4.1 by Aaron Bentley
Get registry options working
108
        opts, args = self.parse(options, ['--hello', '--no-hello'])
1857.1.22 by Aaron Bentley
Negations set value to False, instead of Optparser.DEFAULT_VALUE
109
        self.assertEqual(False, opts.hello)
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
110
        options = [option.Option('number', type=int)]
2221.4.1 by Aaron Bentley
Get registry options working
111
        opts, args = self.parse(options, ['--number', '6'])
1857.1.16 by Aaron Bentley
Add tests for iter_switches
112
        self.assertEqual(6, opts.number)
7490.61.1 by Jelmer Vernooij
Rename BzrCommandError to CommandError.
113
        self.assertRaises(errors.CommandError, self.parse, options,
2221.4.1 by Aaron Bentley
Get registry options working
114
                          ['--number'])
7490.61.1 by Jelmer Vernooij
Rename BzrCommandError to CommandError.
115
        self.assertRaises(errors.CommandError, self.parse, options,
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
116
                          ['--no-number'])
7490.61.1 by Jelmer Vernooij
Rename BzrCommandError to CommandError.
117
        self.assertRaises(errors.CommandError, self.parse, options,
7336.1.1 by Jelmer Vernooij
Print sensible error message when an invalid argument is specified for an option.
118
                          ['--number', 'a'])
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
119
4251.1.1 by Aaron Bentley
Support hidden options.
120
    def test_is_hidden(self):
121
        self.assertTrue(option.Option('foo', hidden=True).is_hidden('foo'))
122
        self.assertFalse(option.Option('foo', hidden=False).is_hidden('foo'))
123
2221.4.1 by Aaron Bentley
Get registry options working
124
    def test_registry_conversion(self):
5363.2.9 by Jelmer Vernooij
Fix some tests.
125
        registry = controldir.ControlDirFormatRegistry()
6695.5.4 by Jelmer Vernooij
Fix options.
126
        bzr.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
7143.15.2 by Jelmer Vernooij
Run autopep8.
127
        bzr.register_metadir(
128
            registry, 'two', 'RepositoryFormatKnit1', 'two help')
6695.5.4 by Jelmer Vernooij
Fix options.
129
        bzr.register_metadir(registry, 'hidden', 'RepositoryFormatKnit1',
7143.15.2 by Jelmer Vernooij
Run autopep8.
130
                             'two help', hidden=True)
2221.4.1 by Aaron Bentley
Get registry options working
131
        registry.set_default('one')
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
132
        options = [option.RegistryOption('format', '', registry, str)]
2221.4.1 by Aaron Bentley
Get registry options working
133
        opts, args = self.parse(options, ['--format', 'one'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
134
        self.assertEqual({'format': 'one'}, opts)
2221.4.1 by Aaron Bentley
Get registry options working
135
        opts, args = self.parse(options, ['--format', 'two'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
136
        self.assertEqual({'format': 'two'}, opts)
6731.1.4 by Jelmer Vernooij
Move BadOptionValue to breezy.option.
137
        self.assertRaises(option.BadOptionValue, self.parse, options,
2221.4.1 by Aaron Bentley
Get registry options working
138
                          ['--format', 'three'])
7490.61.1 by Jelmer Vernooij
Rename BzrCommandError to CommandError.
139
        self.assertRaises(errors.CommandError, self.parse, options,
2221.4.1 by Aaron Bentley
Get registry options working
140
                          ['--two'])
2221.4.9 by Aaron Bentley
Zap trailing whitespace
141
        options = [option.RegistryOption('format', '', registry, str,
7143.15.2 by Jelmer Vernooij
Run autopep8.
142
                                         value_switches=True)]
2221.4.1 by Aaron Bentley
Get registry options working
143
        opts, args = self.parse(options, ['--two'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
144
        self.assertEqual({'format': 'two'}, opts)
2221.4.1 by Aaron Bentley
Get registry options working
145
        opts, args = self.parse(options, ['--two', '--one'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
146
        self.assertEqual({'format': 'one'}, opts)
2221.4.9 by Aaron Bentley
Zap trailing whitespace
147
        opts, args = self.parse(options, ['--two', '--one',
2221.4.1 by Aaron Bentley
Get registry options working
148
                                          '--format', 'two'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
149
        self.assertEqual({'format': 'two'}, opts)
1551.12.18 by Aaron Bentley
Allow RegistryOption to omit the value-taking option
150
        options = [option.RegistryOption('format', '', registry, str,
7143.15.2 by Jelmer Vernooij
Run autopep8.
151
                                         enum_switch=False)]
7490.61.1 by Jelmer Vernooij
Rename BzrCommandError to CommandError.
152
        self.assertRaises(errors.CommandError, self.parse, options,
1551.12.18 by Aaron Bentley
Allow RegistryOption to omit the value-taking option
153
                          ['--format', 'two'])
2221.4.1 by Aaron Bentley
Get registry options working
154
2745.4.2 by Lukáš Lalinsky
Allow options to be stored in attributes that differ from their 'name' and use this to let '--change' and '--revision' to override each other.
155
    def test_override(self):
156
        options = [option.Option('hello', type=str),
157
                   option.Option('hi', type=str, param_name='hello')]
158
        opts, args = self.parse(options, ['--hello', 'a', '--hello', 'b'])
159
        self.assertEqual('b', opts.hello)
160
        opts, args = self.parse(options, ['--hello', 'b', '--hello', 'a'])
161
        self.assertEqual('a', opts.hello)
162
        opts, args = self.parse(options, ['--hello', 'a', '--hi', 'b'])
163
        self.assertEqual('b', opts.hello)
164
        opts, args = self.parse(options, ['--hi', 'b', '--hello', 'a'])
165
        self.assertEqual('a', opts.hello)
166
2221.4.1 by Aaron Bentley
Get registry options working
167
    def test_registry_converter(self):
2221.4.9 by Aaron Bentley
Zap trailing whitespace
168
        options = [option.RegistryOption('format', '',
7143.15.2 by Jelmer Vernooij
Run autopep8.
169
                                         controldir.format_registry, controldir.format_registry.make_controldir)]
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
3224.5.34 by Andrew Bennetts
Polish lazy_registry feature a little.
174
    def test_lazy_registry(self):
175
        options = [option.RegistryOption('format', '',
7143.15.2 by Jelmer Vernooij
Run autopep8.
176
                                         lazy_registry=(
177
                                             'breezy.controldir', 'format_registry'),
178
                                         converter=str)]
3224.5.34 by Andrew Bennetts
Polish lazy_registry feature a little.
179
        opts, args = self.parse(options, ['--format', 'knit'])
180
        self.assertEqual({'format': 'knit'}, opts)
181
        self.assertRaises(
6731.1.4 by Jelmer Vernooij
Move BadOptionValue to breezy.option.
182
            option.BadOptionValue, self.parse, options, ['--format', 'BAD'])
3224.5.34 by Andrew Bennetts
Polish lazy_registry feature a little.
183
1551.12.24 by Aaron Bentley
Add RegistryOption.from_swargs to simplify simple registry options
184
    def test_from_kwargs(self):
185
        my_option = option.RegistryOption.from_kwargs('my-option',
7143.15.2 by Jelmer Vernooij
Run autopep8.
186
                                                      help='test option', short='be short', be_long='go long')
1551.12.24 by Aaron Bentley
Add RegistryOption.from_swargs to simplify simple registry options
187
        self.assertEqual(['my-option'],
7143.15.2 by Jelmer Vernooij
Run autopep8.
188
                         [x[0] for x in my_option.iter_switches()])
1551.12.24 by Aaron Bentley
Add RegistryOption.from_swargs to simplify simple registry options
189
        my_option = option.RegistryOption.from_kwargs('my-option',
7143.15.2 by Jelmer Vernooij
Run autopep8.
190
                                                      help='test option', title="My option", short='be short',
191
                                                      be_long='go long', value_switches=True)
1551.12.24 by Aaron Bentley
Add RegistryOption.from_swargs to simplify simple registry options
192
        self.assertEqual(['my-option', 'be-long', 'short'],
7143.15.2 by Jelmer Vernooij
Run autopep8.
193
                         [x[0] for x in my_option.iter_switches()])
2681.1.5 by Aaron Bentley
Display correct help message in from_kwargs
194
        self.assertEqual('test option', my_option.help)
1551.12.24 by Aaron Bentley
Add RegistryOption.from_swargs to simplify simple registry options
195
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
196
    def test_help(self):
5363.2.9 by Jelmer Vernooij
Fix some tests.
197
        registry = controldir.ControlDirFormatRegistry()
6695.5.4 by Jelmer Vernooij
Fix options.
198
        bzr.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
199
        bzr.register_metadir(registry, 'two',
7143.15.2 by Jelmer Vernooij
Run autopep8.
200
                             'breezy.bzr.knitrepo.RepositoryFormatKnit1',
201
                             'two help',
202
                             )
6695.5.4 by Jelmer Vernooij
Fix options.
203
        bzr.register_metadir(registry, 'hidden', 'RepositoryFormat7', 'hidden help',
7143.15.2 by Jelmer Vernooij
Run autopep8.
204
                             hidden=True)
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
205
        registry.set_default('one')
206
        options = [option.RegistryOption('format', 'format help', registry,
7143.15.2 by Jelmer Vernooij
Run autopep8.
207
                                         str, value_switches=True, title='Formats')]
7045.4.23 by Jelmer Vernooij
Fix some help tests.
208
        parser = option.get_optparser(options)
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
209
        value = parser.format_option_help()
210
        self.assertContainsRe(value, 'format.*format help')
211
        self.assertContainsRe(value, 'one.*one help')
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
212
        self.assertContainsRe(value, 'Formats:\n *--format')
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
213
        self.assertNotContainsRe(value, 'hidden help')
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
214
1857.1.16 by Aaron Bentley
Add tests for iter_switches
215
    def test_iter_switches(self):
216
        opt = option.Option('hello', help='fg')
217
        self.assertEqual(list(opt.iter_switches()),
218
                         [('hello', None, None, 'fg')])
219
        opt = option.Option('hello', help='fg', type=int)
220
        self.assertEqual(list(opt.iter_switches()),
221
                         [('hello', None, 'ARG', 'fg')])
222
        opt = option.Option('hello', help='fg', type=int, argname='gar')
223
        self.assertEqual(list(opt.iter_switches()),
224
                         [('hello', None, 'GAR', 'fg')])
5363.2.9 by Jelmer Vernooij
Fix some tests.
225
        registry = controldir.ControlDirFormatRegistry()
6695.5.4 by Jelmer Vernooij
Fix options.
226
        bzr.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
227
        bzr.register_metadir(registry, 'two',
7143.15.2 by Jelmer Vernooij
Run autopep8.
228
                             'breezy.bzr.knitrepo.RepositoryFormatKnit1',
229
                             'two help',
230
                             )
2221.4.4 by Aaron Bentley
Fix iter_switches behavior when value_switches is true
231
        registry.set_default('one')
232
        opt = option.RegistryOption('format', 'format help', registry,
233
                                    value_switches=False)
234
        self.assertEqual(list(opt.iter_switches()),
235
                         [('format', None, 'ARG', 'format help')])
236
        opt = option.RegistryOption('format', 'format help', registry,
237
                                    value_switches=True)
238
        self.assertEqual(list(opt.iter_switches()),
239
                         [('format', None, 'ARG', 'format help'),
2221.4.9 by Aaron Bentley
Zap trailing whitespace
240
                          ('default', None, None, 'one help'),
241
                          ('one', None, None, 'one help'),
242
                          ('two', None, None, 'two help'),
2221.4.4 by Aaron Bentley
Fix iter_switches behavior when value_switches is true
243
                          ])
1857.1.16 by Aaron Bentley
Add tests for iter_switches
244
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
245
    def test_option_callback_bool(self):
246
        "Test booleans get True and False passed correctly to a callback."""
247
        cb_calls = []
7143.15.2 by Jelmer Vernooij
Run autopep8.
248
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
249
        def cb(option, name, value, parser):
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
250
            cb_calls.append((option, name, value, parser))
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
251
        options = [option.Option('hello', custom_callback=cb)]
252
        opts, args = self.parse(options, ['--hello', '--no-hello'])
253
        self.assertEqual(2, len(cb_calls))
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
254
        opt, name, value, parser = cb_calls[0]
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
255
        self.assertEqual('hello', name)
256
        self.assertTrue(value)
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
257
        opt, name, value, parser = cb_calls[1]
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
258
        self.assertEqual('hello', name)
259
        self.assertFalse(value)
260
261
    def test_option_callback_str(self):
262
        """Test callbacks work for string options both long and short."""
263
        cb_calls = []
7143.15.2 by Jelmer Vernooij
Run autopep8.
264
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
265
        def cb(option, name, value, parser):
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
266
            cb_calls.append((option, name, value, parser))
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
267
        options = [option.Option('hello', type=str, custom_callback=cb,
7143.15.2 by Jelmer Vernooij
Run autopep8.
268
                                 short_name='h')]
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
269
        opts, args = self.parse(options, ['--hello', 'world', '-h', 'mars'])
270
        self.assertEqual(2, len(cb_calls))
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
271
        opt, name, value, parser = cb_calls[0]
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
272
        self.assertEqual('hello', name)
273
        self.assertEqual('world', value)
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
274
        opt, name, value, parser = cb_calls[1]
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
275
        self.assertEqual('hello', name)
276
        self.assertEqual('mars', value)
277
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
278
2376.4.11 by Jonathan Lange
Provide a way of resetting list options (specifying '-' as the argument)
279
class TestListOptions(TestCase):
280
    """Tests for ListOption, used to specify lists on the command-line."""
281
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
282
    def parse(self, options, args):
7045.4.23 by Jelmer Vernooij
Fix some help tests.
283
        parser = option.get_optparser(options)
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
284
        return parser.parse_args(args)
285
286
    def test_list_option(self):
287
        options = [option.ListOption('hello', type=str)]
288
        opts, args = self.parse(options, ['--hello=world', '--hello=sailor'])
289
        self.assertEqual(['world', 'sailor'], opts.hello)
290
3668.2.1 by Vincent Ladeuil
Fix bug #263249 by setting valid default _param_name.
291
    def test_list_option_with_dash(self):
292
        options = [option.ListOption('with-dash', type=str)]
293
        opts, args = self.parse(options, ['--with-dash=world',
294
                                          '--with-dash=sailor'])
295
        self.assertEqual(['world', 'sailor'], opts.with_dash)
296
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
297
    def test_list_option_no_arguments(self):
298
        options = [option.ListOption('hello', type=str)]
299
        opts, args = self.parse(options, [])
300
        self.assertEqual([], opts.hello)
2376.4.11 by Jonathan Lange
Provide a way of resetting list options (specifying '-' as the argument)
301
2376.4.22 by Jonathan Lange
Variety of whitespace cleanups, tightening of tests and docstring changes in
302
    def test_list_option_with_int_type(self):
303
        options = [option.ListOption('hello', type=int)]
304
        opts, args = self.parse(options, ['--hello=2', '--hello=3'])
305
        self.assertEqual([2, 3], opts.hello)
306
307
    def test_list_option_with_int_type_can_be_reset(self):
308
        options = [option.ListOption('hello', type=int)]
309
        opts, args = self.parse(options, ['--hello=2', '--hello=3',
310
                                          '--hello=-', '--hello=5'])
311
        self.assertEqual([5], opts.hello)
312
2376.4.11 by Jonathan Lange
Provide a way of resetting list options (specifying '-' as the argument)
313
    def test_list_option_can_be_reset(self):
314
        """Passing an option of '-' to a list option should reset the list."""
315
        options = [option.ListOption('hello', type=str)]
316
        opts, args = self.parse(
317
            options, ['--hello=a', '--hello=b', '--hello=-', '--hello=c'])
318
        self.assertEqual(['c'], opts.hello)
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
319
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
320
    def test_option_callback_list(self):
321
        """Test callbacks work for list options."""
322
        cb_calls = []
7143.15.2 by Jelmer Vernooij
Run autopep8.
323
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
324
        def cb(option, name, value, parser):
325
            # Note that the value is a reference so copy to keep it
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
326
            cb_calls.append((option, name, value[:], parser))
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
327
        options = [option.ListOption('hello', type=str, custom_callback=cb)]
328
        opts, args = self.parse(options, ['--hello=world', '--hello=mars',
7143.15.2 by Jelmer Vernooij
Run autopep8.
329
                                          '--hello=-'])
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
330
        self.assertEqual(3, len(cb_calls))
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
331
        opt, name, value, parser = cb_calls[0]
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
332
        self.assertEqual('hello', name)
333
        self.assertEqual(['world'], value)
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
334
        opt, name, value, parser = cb_calls[1]
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
335
        self.assertEqual('hello', name)
336
        self.assertEqual(['world', 'mars'], value)
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
337
        opt, name, value, parser = cb_calls[2]
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
338
        self.assertEqual('hello', name)
339
        self.assertEqual([], value)
340
3751.1.1 by Martin von Gagern
Handle param_name for ListOption.
341
    def test_list_option_param_name(self):
342
        """Test list options can have their param_name set."""
343
        options = [option.ListOption('hello', type=str, param_name='greeting')]
344
        opts, args = self.parse(
345
            options, ['--hello=world', '--hello=sailor'])
346
        self.assertEqual(['world', 'sailor'], opts.greeting)
347
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
348
349
class TestOptionDefinitions(TestCase):
350
    """Tests for options in the Bazaar codebase."""
351
2598.1.14 by Martin Pool
Revert tightening of options api - breaks too many plugins
352
    def get_builtin_command_options(self):
353
        g = []
6259.2.1 by Martin Packman
Make TestOptionDefinitions actually do something again by reinstalling hooks in test context
354
        commands.install_bzr_command_hooks()
355
        for cmd_name in sorted(commands.builtin_command_names()):
4119.3.8 by Robert Collins
Get missing command support sorted out.
356
            cmd = commands.get_cmd_object(cmd_name)
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
357
            for opt_name, opt in sorted(cmd.options().items()):
358
                g.append((cmd_name, opt))
6614.1.1 by Vincent Ladeuil
Fix assert_ being deprecated by using assertTrue.
359
        self.assertTrue(g)
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
360
        return g
361
362
    def test_option_grammar(self):
363
        msgs = []
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
364
        # Option help should be written in sentence form, and have a final
6259.2.10 by Martin Packman
Allow a bracketed suffix in option help test
365
        # period with an optional bracketed suffix. All the text should be on
366
        # one line, because the display code will wrap it.
367
        option_re = re.compile(r'^[A-Z][^\n]+\.(?: \([^\n]+\))?$')
3755.1.1 by Vincent Ladeuil
Fix --verbose leaking into blackbox tests.
368
        for scope, opt in self.get_builtin_command_options():
6259.2.6 by Martin Packman
Test help strings of registry option value switches as well
369
            for name, _, _, helptxt in opt.iter_switches():
370
                if name != opt.name:
371
                    name = "/".join([opt.name, name])
372
                if not helptxt:
373
                    msgs.append('%-16s %-16s %s' %
7143.15.2 by Jelmer Vernooij
Run autopep8.
374
                                ((scope or 'GLOBAL'), name, 'NO HELP'))
6259.2.6 by Martin Packman
Test help strings of registry option value switches as well
375
                elif not option_re.match(helptxt):
376
                    msgs.append('%-16s %-16s %s' %
7143.15.2 by Jelmer Vernooij
Run autopep8.
377
                                ((scope or 'GLOBAL'), name, helptxt))
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
378
        if msgs:
379
            self.fail("The following options don't match the style guide:\n"
7143.15.2 by Jelmer Vernooij
Run autopep8.
380
                      + '\n'.join(msgs))
1551.18.12 by Aaron Bentley
Man page doesn't list hidden options (#131667)
381
6259.2.3 by Martin Packman
Split tests methods unrelated to command options to a seperate class
382
383
class TestOptionMisc(TestCase):
384
1551.18.12 by Aaron Bentley
Man page doesn't list hidden options (#131667)
385
    def test_is_hidden(self):
5363.2.9 by Jelmer Vernooij
Fix some tests.
386
        registry = controldir.ControlDirFormatRegistry()
6695.5.4 by Jelmer Vernooij
Fix options.
387
        bzr.register_metadir(registry, 'hidden', 'HiddenFormat',
7143.15.2 by Jelmer Vernooij
Run autopep8.
388
                             'hidden help text', hidden=True)
6695.5.4 by Jelmer Vernooij
Fix options.
389
        bzr.register_metadir(registry, 'visible', 'VisibleFormat',
7143.15.2 by Jelmer Vernooij
Run autopep8.
390
                             'visible help text', hidden=False)
1551.18.12 by Aaron Bentley
Man page doesn't list hidden options (#131667)
391
        format = option.RegistryOption('format', '', registry, str)
392
        self.assertTrue(format.is_hidden('hidden'))
393
        self.assertFalse(format.is_hidden('visible'))
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
394
5574.9.3 by Jelmer Vernooij
Add -F as alias for 'bzr diff -F format'
395
    def test_short_name(self):
396
        registry = controldir.ControlDirFormatRegistry()
397
        opt = option.RegistryOption('format', help='', registry=registry)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
398
        self.assertEqual(None, opt.short_name())
5574.9.3 by Jelmer Vernooij
Add -F as alias for 'bzr diff -F format'
399
        opt = option.RegistryOption('format', short_name='F', help='',
7143.15.2 by Jelmer Vernooij
Run autopep8.
400
                                    registry=registry)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
401
        self.assertEqual('F', opt.short_name())
5574.9.3 by Jelmer Vernooij
Add -F as alias for 'bzr diff -F format'
402
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
403
    def test_option_custom_help(self):
404
        the_opt = option.Option.OPTIONS['help']
405
        orig_help = the_opt.help[:]
406
        my_opt = option.custom_help('help', 'suggest lottery numbers')
407
        # Confirm that my_opt has my help and the original is unchanged
408
        self.assertEqual('suggest lottery numbers', my_opt.help)
409
        self.assertEqual(orig_help, the_opt.help)
410
5945.1.1 by Martin von Gagern
Allow -s as shorthand for --log-format=short.
411
    def test_short_value_switches(self):
412
        reg = registry.Registry()
413
        reg.register('short', 'ShortChoice')
414
        reg.register('long', 'LongChoice')
415
        ropt = option.RegistryOption('choice', '', reg, value_switches=True,
7143.15.2 by Jelmer Vernooij
Run autopep8.
416
                                     short_value_switches={'short': 's'})
5945.1.1 by Martin von Gagern
Allow -s as shorthand for --log-format=short.
417
        opts, args = parse([ropt], ['--short'])
418
        self.assertEqual('ShortChoice', opts.choice)
419
        opts, args = parse([ropt], ['-s'])
420
        self.assertEqual('ShortChoice', opts.choice)
421
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
422
423
class TestVerboseQuietLinkage(TestCase):
424
425
    def check(self, parser, level, args):
426
        option._verbosity_level = 0
427
        opts, args = parser.parse_args(args)
428
        self.assertEqual(level, option._verbosity_level)
429
430
    def test_verbose_quiet_linkage(self):
7045.4.23 by Jelmer Vernooij
Fix some help tests.
431
        parser = option.get_optparser(
7143.15.2 by Jelmer Vernooij
Run autopep8.
432
            [v for k, v in sorted(option.Option.STD_OPTIONS.items())])
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
433
        self.check(parser, 0, [])
434
        self.check(parser, 1, ['-v'])
435
        self.check(parser, 2, ['-v', '-v'])
436
        self.check(parser, -1, ['-q'])
437
        self.check(parser, -2, ['-qq'])
438
        self.check(parser, -1, ['-v', '-v', '-q'])
439
        self.check(parser, 2, ['-q', '-v', '-v'])
440
        self.check(parser, 0, ['--no-verbose'])
441
        self.check(parser, 0, ['-v', '-q', '--no-quiet'])