/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)
2221.4.9 by Aaron Bentley
Zap trailing whitespace
113
        self.assertRaises(errors.BzrCommandError, self.parse, options,
2221.4.1 by Aaron Bentley
Get registry options working
114
                          ['--number'])
2221.4.9 by Aaron Bentley
Zap trailing whitespace
115
        self.assertRaises(errors.BzrCommandError, self.parse, options,
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
116
                          ['--no-number'])
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
117
4251.1.1 by Aaron Bentley
Support hidden options.
118
    def test_is_hidden(self):
119
        self.assertTrue(option.Option('foo', hidden=True).is_hidden('foo'))
120
        self.assertFalse(option.Option('foo', hidden=False).is_hidden('foo'))
121
2221.4.1 by Aaron Bentley
Get registry options working
122
    def test_registry_conversion(self):
5363.2.9 by Jelmer Vernooij
Fix some tests.
123
        registry = controldir.ControlDirFormatRegistry()
6695.5.4 by Jelmer Vernooij
Fix options.
124
        bzr.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
7143.15.2 by Jelmer Vernooij
Run autopep8.
125
        bzr.register_metadir(
126
            registry, 'two', 'RepositoryFormatKnit1', 'two help')
6695.5.4 by Jelmer Vernooij
Fix options.
127
        bzr.register_metadir(registry, 'hidden', 'RepositoryFormatKnit1',
7143.15.2 by Jelmer Vernooij
Run autopep8.
128
                             'two help', hidden=True)
2221.4.1 by Aaron Bentley
Get registry options working
129
        registry.set_default('one')
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
130
        options = [option.RegistryOption('format', '', registry, str)]
2221.4.1 by Aaron Bentley
Get registry options working
131
        opts, args = self.parse(options, ['--format', 'one'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
132
        self.assertEqual({'format': 'one'}, opts)
2221.4.1 by Aaron Bentley
Get registry options working
133
        opts, args = self.parse(options, ['--format', 'two'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
134
        self.assertEqual({'format': 'two'}, opts)
6731.1.4 by Jelmer Vernooij
Move BadOptionValue to breezy.option.
135
        self.assertRaises(option.BadOptionValue, self.parse, options,
2221.4.1 by Aaron Bentley
Get registry options working
136
                          ['--format', 'three'])
2221.4.9 by Aaron Bentley
Zap trailing whitespace
137
        self.assertRaises(errors.BzrCommandError, self.parse, options,
2221.4.1 by Aaron Bentley
Get registry options working
138
                          ['--two'])
2221.4.9 by Aaron Bentley
Zap trailing whitespace
139
        options = [option.RegistryOption('format', '', registry, str,
7143.15.2 by Jelmer Vernooij
Run autopep8.
140
                                         value_switches=True)]
2221.4.1 by Aaron Bentley
Get registry options working
141
        opts, args = self.parse(options, ['--two'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
142
        self.assertEqual({'format': 'two'}, opts)
2221.4.1 by Aaron Bentley
Get registry options working
143
        opts, args = self.parse(options, ['--two', '--one'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
144
        self.assertEqual({'format': 'one'}, opts)
2221.4.9 by Aaron Bentley
Zap trailing whitespace
145
        opts, args = self.parse(options, ['--two', '--one',
2221.4.1 by Aaron Bentley
Get registry options working
146
                                          '--format', 'two'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
147
        self.assertEqual({'format': 'two'}, opts)
1551.12.18 by Aaron Bentley
Allow RegistryOption to omit the value-taking option
148
        options = [option.RegistryOption('format', '', registry, str,
7143.15.2 by Jelmer Vernooij
Run autopep8.
149
                                         enum_switch=False)]
1551.12.18 by Aaron Bentley
Allow RegistryOption to omit the value-taking option
150
        self.assertRaises(errors.BzrCommandError, self.parse, options,
151
                          ['--format', 'two'])
2221.4.1 by Aaron Bentley
Get registry options working
152
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.
153
    def test_override(self):
154
        options = [option.Option('hello', type=str),
155
                   option.Option('hi', type=str, param_name='hello')]
156
        opts, args = self.parse(options, ['--hello', 'a', '--hello', 'b'])
157
        self.assertEqual('b', opts.hello)
158
        opts, args = self.parse(options, ['--hello', 'b', '--hello', 'a'])
159
        self.assertEqual('a', opts.hello)
160
        opts, args = self.parse(options, ['--hello', 'a', '--hi', 'b'])
161
        self.assertEqual('b', opts.hello)
162
        opts, args = self.parse(options, ['--hi', 'b', '--hello', 'a'])
163
        self.assertEqual('a', opts.hello)
164
2221.4.1 by Aaron Bentley
Get registry options working
165
    def test_registry_converter(self):
2221.4.9 by Aaron Bentley
Zap trailing whitespace
166
        options = [option.RegistryOption('format', '',
7143.15.2 by Jelmer Vernooij
Run autopep8.
167
                                         controldir.format_registry, controldir.format_registry.make_controldir)]
2221.4.1 by Aaron Bentley
Get registry options working
168
        opts, args = self.parse(options, ['--format', 'knit'])
169
        self.assertIsInstance(opts.format.repository_format,
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
170
                              knitrepo.RepositoryFormatKnit1)
2221.4.1 by Aaron Bentley
Get registry options working
171
3224.5.34 by Andrew Bennetts
Polish lazy_registry feature a little.
172
    def test_lazy_registry(self):
173
        options = [option.RegistryOption('format', '',
7143.15.2 by Jelmer Vernooij
Run autopep8.
174
                                         lazy_registry=(
175
                                             'breezy.controldir', 'format_registry'),
176
                                         converter=str)]
3224.5.34 by Andrew Bennetts
Polish lazy_registry feature a little.
177
        opts, args = self.parse(options, ['--format', 'knit'])
178
        self.assertEqual({'format': 'knit'}, opts)
179
        self.assertRaises(
6731.1.4 by Jelmer Vernooij
Move BadOptionValue to breezy.option.
180
            option.BadOptionValue, self.parse, options, ['--format', 'BAD'])
3224.5.34 by Andrew Bennetts
Polish lazy_registry feature a little.
181
1551.12.24 by Aaron Bentley
Add RegistryOption.from_swargs to simplify simple registry options
182
    def test_from_kwargs(self):
183
        my_option = option.RegistryOption.from_kwargs('my-option',
7143.15.2 by Jelmer Vernooij
Run autopep8.
184
                                                      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
185
        self.assertEqual(['my-option'],
7143.15.2 by Jelmer Vernooij
Run autopep8.
186
                         [x[0] for x in my_option.iter_switches()])
1551.12.24 by Aaron Bentley
Add RegistryOption.from_swargs to simplify simple registry options
187
        my_option = option.RegistryOption.from_kwargs('my-option',
7143.15.2 by Jelmer Vernooij
Run autopep8.
188
                                                      help='test option', title="My option", short='be short',
189
                                                      be_long='go long', value_switches=True)
1551.12.24 by Aaron Bentley
Add RegistryOption.from_swargs to simplify simple registry options
190
        self.assertEqual(['my-option', 'be-long', 'short'],
7143.15.2 by Jelmer Vernooij
Run autopep8.
191
                         [x[0] for x in my_option.iter_switches()])
2681.1.5 by Aaron Bentley
Display correct help message in from_kwargs
192
        self.assertEqual('test option', my_option.help)
1551.12.24 by Aaron Bentley
Add RegistryOption.from_swargs to simplify simple registry options
193
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
194
    def test_help(self):
5363.2.9 by Jelmer Vernooij
Fix some tests.
195
        registry = controldir.ControlDirFormatRegistry()
6695.5.4 by Jelmer Vernooij
Fix options.
196
        bzr.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
197
        bzr.register_metadir(registry, 'two',
7143.15.2 by Jelmer Vernooij
Run autopep8.
198
                             'breezy.bzr.knitrepo.RepositoryFormatKnit1',
199
                             'two help',
200
                             )
6695.5.4 by Jelmer Vernooij
Fix options.
201
        bzr.register_metadir(registry, 'hidden', 'RepositoryFormat7', 'hidden help',
7143.15.2 by Jelmer Vernooij
Run autopep8.
202
                             hidden=True)
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
203
        registry.set_default('one')
204
        options = [option.RegistryOption('format', 'format help', registry,
7143.15.2 by Jelmer Vernooij
Run autopep8.
205
                                         str, value_switches=True, title='Formats')]
7045.4.23 by Jelmer Vernooij
Fix some help tests.
206
        parser = option.get_optparser(options)
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
207
        value = parser.format_option_help()
208
        self.assertContainsRe(value, 'format.*format help')
209
        self.assertContainsRe(value, 'one.*one help')
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
210
        self.assertContainsRe(value, 'Formats:\n *--format')
1551.13.2 by Aaron Bentley
Hide dirstate-with-subtree format
211
        self.assertNotContainsRe(value, 'hidden help')
2221.4.2 by Aaron Bentley
Implement RegistryOption on init
212
1857.1.16 by Aaron Bentley
Add tests for iter_switches
213
    def test_iter_switches(self):
214
        opt = option.Option('hello', help='fg')
215
        self.assertEqual(list(opt.iter_switches()),
216
                         [('hello', None, None, 'fg')])
217
        opt = option.Option('hello', help='fg', type=int)
218
        self.assertEqual(list(opt.iter_switches()),
219
                         [('hello', None, 'ARG', 'fg')])
220
        opt = option.Option('hello', help='fg', type=int, argname='gar')
221
        self.assertEqual(list(opt.iter_switches()),
222
                         [('hello', None, 'GAR', 'fg')])
5363.2.9 by Jelmer Vernooij
Fix some tests.
223
        registry = controldir.ControlDirFormatRegistry()
6695.5.4 by Jelmer Vernooij
Fix options.
224
        bzr.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
225
        bzr.register_metadir(registry, 'two',
7143.15.2 by Jelmer Vernooij
Run autopep8.
226
                             'breezy.bzr.knitrepo.RepositoryFormatKnit1',
227
                             'two help',
228
                             )
2221.4.4 by Aaron Bentley
Fix iter_switches behavior when value_switches is true
229
        registry.set_default('one')
230
        opt = option.RegistryOption('format', 'format help', registry,
231
                                    value_switches=False)
232
        self.assertEqual(list(opt.iter_switches()),
233
                         [('format', None, 'ARG', 'format help')])
234
        opt = option.RegistryOption('format', 'format help', registry,
235
                                    value_switches=True)
236
        self.assertEqual(list(opt.iter_switches()),
237
                         [('format', None, 'ARG', 'format help'),
2221.4.9 by Aaron Bentley
Zap trailing whitespace
238
                          ('default', None, None, 'one help'),
239
                          ('one', None, None, 'one help'),
240
                          ('two', None, None, 'two help'),
2221.4.4 by Aaron Bentley
Fix iter_switches behavior when value_switches is true
241
                          ])
1857.1.16 by Aaron Bentley
Add tests for iter_switches
242
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
243
    def test_option_callback_bool(self):
244
        "Test booleans get True and False passed correctly to a callback."""
245
        cb_calls = []
7143.15.2 by Jelmer Vernooij
Run autopep8.
246
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
247
        def cb(option, name, value, parser):
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
248
            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
249
        options = [option.Option('hello', custom_callback=cb)]
250
        opts, args = self.parse(options, ['--hello', '--no-hello'])
251
        self.assertEqual(2, len(cb_calls))
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
252
        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
253
        self.assertEqual('hello', name)
254
        self.assertTrue(value)
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
255
        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
256
        self.assertEqual('hello', name)
257
        self.assertFalse(value)
258
259
    def test_option_callback_str(self):
260
        """Test callbacks work for string options both long and short."""
261
        cb_calls = []
7143.15.2 by Jelmer Vernooij
Run autopep8.
262
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
263
        def cb(option, name, value, parser):
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
264
            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
265
        options = [option.Option('hello', type=str, custom_callback=cb,
7143.15.2 by Jelmer Vernooij
Run autopep8.
266
                                 short_name='h')]
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
267
        opts, args = self.parse(options, ['--hello', 'world', '-h', 'mars'])
268
        self.assertEqual(2, len(cb_calls))
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
269
        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
270
        self.assertEqual('hello', name)
271
        self.assertEqual('world', value)
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
272
        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
273
        self.assertEqual('hello', name)
274
        self.assertEqual('mars', value)
275
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
276
2376.4.11 by Jonathan Lange
Provide a way of resetting list options (specifying '-' as the argument)
277
class TestListOptions(TestCase):
278
    """Tests for ListOption, used to specify lists on the command-line."""
279
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
280
    def parse(self, options, args):
7045.4.23 by Jelmer Vernooij
Fix some help tests.
281
        parser = option.get_optparser(options)
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
282
        return parser.parse_args(args)
283
284
    def test_list_option(self):
285
        options = [option.ListOption('hello', type=str)]
286
        opts, args = self.parse(options, ['--hello=world', '--hello=sailor'])
287
        self.assertEqual(['world', 'sailor'], opts.hello)
288
3668.2.1 by Vincent Ladeuil
Fix bug #263249 by setting valid default _param_name.
289
    def test_list_option_with_dash(self):
290
        options = [option.ListOption('with-dash', type=str)]
291
        opts, args = self.parse(options, ['--with-dash=world',
292
                                          '--with-dash=sailor'])
293
        self.assertEqual(['world', 'sailor'], opts.with_dash)
294
2376.4.1 by jml at canonical
Blackbox-driven --fixes option to commit.
295
    def test_list_option_no_arguments(self):
296
        options = [option.ListOption('hello', type=str)]
297
        opts, args = self.parse(options, [])
298
        self.assertEqual([], opts.hello)
2376.4.11 by Jonathan Lange
Provide a way of resetting list options (specifying '-' as the argument)
299
2376.4.22 by Jonathan Lange
Variety of whitespace cleanups, tightening of tests and docstring changes in
300
    def test_list_option_with_int_type(self):
301
        options = [option.ListOption('hello', type=int)]
302
        opts, args = self.parse(options, ['--hello=2', '--hello=3'])
303
        self.assertEqual([2, 3], opts.hello)
304
305
    def test_list_option_with_int_type_can_be_reset(self):
306
        options = [option.ListOption('hello', type=int)]
307
        opts, args = self.parse(options, ['--hello=2', '--hello=3',
308
                                          '--hello=-', '--hello=5'])
309
        self.assertEqual([5], opts.hello)
310
2376.4.11 by Jonathan Lange
Provide a way of resetting list options (specifying '-' as the argument)
311
    def test_list_option_can_be_reset(self):
312
        """Passing an option of '-' to a list option should reset the list."""
313
        options = [option.ListOption('hello', type=str)]
314
        opts, args = self.parse(
315
            options, ['--hello=a', '--hello=b', '--hello=-', '--hello=c'])
316
        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
317
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
318
    def test_option_callback_list(self):
319
        """Test callbacks work for list options."""
320
        cb_calls = []
7143.15.2 by Jelmer Vernooij
Run autopep8.
321
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
322
        def cb(option, name, value, parser):
323
            # Note that the value is a reference so copy to keep it
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
324
            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
325
        options = [option.ListOption('hello', type=str, custom_callback=cb)]
326
        opts, args = self.parse(options, ['--hello=world', '--hello=mars',
7143.15.2 by Jelmer Vernooij
Run autopep8.
327
                                          '--hello=-'])
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
328
        self.assertEqual(3, len(cb_calls))
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
329
        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
330
        self.assertEqual('hello', name)
331
        self.assertEqual(['world'], value)
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
332
        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
333
        self.assertEqual('hello', name)
334
        self.assertEqual(['world', 'mars'], value)
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
335
        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
336
        self.assertEqual('hello', name)
337
        self.assertEqual([], value)
338
3751.1.1 by Martin von Gagern
Handle param_name for ListOption.
339
    def test_list_option_param_name(self):
340
        """Test list options can have their param_name set."""
341
        options = [option.ListOption('hello', type=str, param_name='greeting')]
342
        opts, args = self.parse(
343
            options, ['--hello=world', '--hello=sailor'])
344
        self.assertEqual(['world', 'sailor'], opts.greeting)
345
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
346
347
class TestOptionDefinitions(TestCase):
348
    """Tests for options in the Bazaar codebase."""
349
2598.1.14 by Martin Pool
Revert tightening of options api - breaks too many plugins
350
    def get_builtin_command_options(self):
351
        g = []
6259.2.1 by Martin Packman
Make TestOptionDefinitions actually do something again by reinstalling hooks in test context
352
        commands.install_bzr_command_hooks()
353
        for cmd_name in sorted(commands.builtin_command_names()):
4119.3.8 by Robert Collins
Get missing command support sorted out.
354
            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
355
            for opt_name, opt in sorted(cmd.options().items()):
356
                g.append((cmd_name, opt))
6614.1.1 by Vincent Ladeuil
Fix assert_ being deprecated by using assertTrue.
357
        self.assertTrue(g)
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
358
        return g
359
360
    def test_option_grammar(self):
361
        msgs = []
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
362
        # 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
363
        # period with an optional bracketed suffix. All the text should be on
364
        # one line, because the display code will wrap it.
365
        option_re = re.compile(r'^[A-Z][^\n]+\.(?: \([^\n]+\))?$')
3755.1.1 by Vincent Ladeuil
Fix --verbose leaking into blackbox tests.
366
        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
367
            for name, _, _, helptxt in opt.iter_switches():
368
                if name != opt.name:
369
                    name = "/".join([opt.name, name])
370
                if not helptxt:
371
                    msgs.append('%-16s %-16s %s' %
7143.15.2 by Jelmer Vernooij
Run autopep8.
372
                                ((scope or 'GLOBAL'), name, 'NO HELP'))
6259.2.6 by Martin Packman
Test help strings of registry option value switches as well
373
                elif not option_re.match(helptxt):
6259.2.7 by Martin Packman
Let format registry help break the rules for now
374
                    if name.startswith("format/"):
375
                        # Don't complain about the odd format registry help
376
                        continue
6259.2.6 by Martin Packman
Test help strings of registry option value switches as well
377
                    msgs.append('%-16s %-16s %s' %
7143.15.2 by Jelmer Vernooij
Run autopep8.
378
                                ((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
379
        if msgs:
380
            self.fail("The following options don't match the style guide:\n"
7143.15.2 by Jelmer Vernooij
Run autopep8.
381
                      + '\n'.join(msgs))
1551.18.12 by Aaron Bentley
Man page doesn't list hidden options (#131667)
382
6259.2.3 by Martin Packman
Split tests methods unrelated to command options to a seperate class
383
384
class TestOptionMisc(TestCase):
385
1551.18.12 by Aaron Bentley
Man page doesn't list hidden options (#131667)
386
    def test_is_hidden(self):
5363.2.9 by Jelmer Vernooij
Fix some tests.
387
        registry = controldir.ControlDirFormatRegistry()
6695.5.4 by Jelmer Vernooij
Fix options.
388
        bzr.register_metadir(registry, 'hidden', 'HiddenFormat',
7143.15.2 by Jelmer Vernooij
Run autopep8.
389
                             'hidden help text', hidden=True)
6695.5.4 by Jelmer Vernooij
Fix options.
390
        bzr.register_metadir(registry, 'visible', 'VisibleFormat',
7143.15.2 by Jelmer Vernooij
Run autopep8.
391
                             'visible help text', hidden=False)
1551.18.12 by Aaron Bentley
Man page doesn't list hidden options (#131667)
392
        format = option.RegistryOption('format', '', registry, str)
393
        self.assertTrue(format.is_hidden('hidden'))
394
        self.assertFalse(format.is_hidden('visible'))
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
395
5574.9.3 by Jelmer Vernooij
Add -F as alias for 'bzr diff -F format'
396
    def test_short_name(self):
397
        registry = controldir.ControlDirFormatRegistry()
398
        opt = option.RegistryOption('format', help='', registry=registry)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
399
        self.assertEqual(None, opt.short_name())
5574.9.3 by Jelmer Vernooij
Add -F as alias for 'bzr diff -F format'
400
        opt = option.RegistryOption('format', short_name='F', help='',
7143.15.2 by Jelmer Vernooij
Run autopep8.
401
                                    registry=registry)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
402
        self.assertEqual('F', opt.short_name())
5574.9.3 by Jelmer Vernooij
Add -F as alias for 'bzr diff -F format'
403
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
404
    def test_option_custom_help(self):
405
        the_opt = option.Option.OPTIONS['help']
406
        orig_help = the_opt.help[:]
407
        my_opt = option.custom_help('help', 'suggest lottery numbers')
408
        # Confirm that my_opt has my help and the original is unchanged
409
        self.assertEqual('suggest lottery numbers', my_opt.help)
410
        self.assertEqual(orig_help, the_opt.help)
411
5945.1.1 by Martin von Gagern
Allow -s as shorthand for --log-format=short.
412
    def test_short_value_switches(self):
413
        reg = registry.Registry()
414
        reg.register('short', 'ShortChoice')
415
        reg.register('long', 'LongChoice')
416
        ropt = option.RegistryOption('choice', '', reg, value_switches=True,
7143.15.2 by Jelmer Vernooij
Run autopep8.
417
                                     short_value_switches={'short': 's'})
5945.1.1 by Martin von Gagern
Allow -s as shorthand for --log-format=short.
418
        opts, args = parse([ropt], ['--short'])
419
        self.assertEqual('ShortChoice', opts.choice)
420
        opts, args = parse([ropt], ['-s'])
421
        self.assertEqual('ShortChoice', opts.choice)
422
2768.1.11 by Ian Clatworthy
Add new option tests for custom help, callbacks and verbose/quiet linkage
423
424
class TestVerboseQuietLinkage(TestCase):
425
426
    def check(self, parser, level, args):
427
        option._verbosity_level = 0
428
        opts, args = parser.parse_args(args)
429
        self.assertEqual(level, option._verbosity_level)
430
431
    def test_verbose_quiet_linkage(self):
7045.4.23 by Jelmer Vernooij
Fix some help tests.
432
        parser = option.get_optparser(
7143.15.2 by Jelmer Vernooij
Run autopep8.
433
            [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
434
        self.check(parser, 0, [])
435
        self.check(parser, 1, ['-v'])
436
        self.check(parser, 2, ['-v', '-v'])
437
        self.check(parser, -1, ['-q'])
438
        self.check(parser, -2, ['-qq'])
439
        self.check(parser, -1, ['-v', '-v', '-q'])
440
        self.check(parser, 2, ['-q', '-v', '-v'])
441
        self.check(parser, 0, ['--no-verbose'])
442
        self.check(parser, 0, ['-v', '-q', '--no-quiet'])