/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4763.2.4 by John Arbash Meinel
merge bzr.2.1 in preparation for NEWS entry.
1
# Copyright (C) 2005-2010 Canonical Ltd
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
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
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
16
17
"""Tests for finding and reading the bzr config file[s]."""
18
# import system imports here
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
19
from cStringIO import StringIO
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
20
import os
21
import sys
22
23
#import bzrlib specific imports here
1878.1.3 by John Arbash Meinel
some test cleanups
24
from bzrlib import (
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
25
    branch,
26
    bzrdir,
1878.1.3 by John Arbash Meinel
some test cleanups
27
    config,
4603.1.10 by Aaron Bentley
Provide change editor via config.
28
    diff,
1878.1.3 by John Arbash Meinel
some test cleanups
29
    errors,
30
    osutils,
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
31
    mail_client,
2900.2.14 by Vincent Ladeuil
More tests.
32
    ui,
1878.1.3 by John Arbash Meinel
some test cleanups
33
    urlutils,
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
34
    tests,
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
35
    trace,
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
36
    transport,
1878.1.3 by John Arbash Meinel
some test cleanups
37
    )
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
38
from bzrlib.util.configobj import configobj
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
39
40
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
41
sample_long_alias="log -r-15..-1 --line"
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
42
sample_config_text = u"""
43
[DEFAULT]
44
email=Erik B\u00e5gfors <erik@bagfors.nu>
45
editor=vim
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
46
change_editor=vimdiff -of @new_path @old_path
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
47
gpg_signing_command=gnome-gpg
48
log_format=short
49
user_global_option=something
50
[ALIASES]
51
h=help
52
ll=""" + sample_long_alias + "\n"
53
54
55
sample_always_signatures = """
56
[DEFAULT]
57
check_signatures=ignore
58
create_signatures=always
59
"""
60
61
sample_ignore_signatures = """
62
[DEFAULT]
63
check_signatures=require
64
create_signatures=never
65
"""
66
67
sample_maybe_signatures = """
68
[DEFAULT]
69
check_signatures=ignore
70
create_signatures=when-required
71
"""
72
73
sample_branches_text = """
74
[http://www.example.com]
75
# Top level policy
76
email=Robert Collins <robertc@example.org>
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
77
normal_option = normal
78
appendpath_option = append
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
79
appendpath_option:policy = appendpath
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
80
norecurse_option = norecurse
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
81
norecurse_option:policy = norecurse
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
82
[http://www.example.com/ignoreparent]
83
# different project: ignore parent dir config
84
ignore_parents=true
85
[http://www.example.com/norecurse]
86
# configuration items that only apply to this dir
87
recurse=false
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
88
normal_option = norecurse
89
[http://www.example.com/dir]
90
appendpath_option = normal
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
91
[/b/]
92
check_signatures=require
93
# test trailing / matching with no children
94
[/a/]
95
check_signatures=check-available
96
gpg_signing_command=false
97
user_local_option=local
98
# test trailing / matching
99
[/a/*]
100
#subdirs will match but not the parent
101
[/a/c]
102
check_signatures=ignore
103
post_commit=bzrlib.tests.test_config.post_commit
104
#testing explicit beats globs
105
"""
1553.6.3 by Erik Bågfors
tests for AliasesConfig
106
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
107
1474 by Robert Collins
Merge from Aaron Bentley.
108
class InstrumentedConfigObj(object):
109
    """A config obj look-enough-alike to record calls made to it."""
110
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
111
    def __contains__(self, thing):
112
        self._calls.append(('__contains__', thing))
113
        return False
114
115
    def __getitem__(self, key):
116
        self._calls.append(('__getitem__', key))
117
        return self
118
1551.2.20 by Aaron Bentley
Treated config files as utf-8
119
    def __init__(self, input, encoding=None):
120
        self._calls = [('__init__', input, encoding)]
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
121
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
122
    def __setitem__(self, key, value):
123
        self._calls.append(('__setitem__', key, value))
124
2120.6.4 by James Henstridge
add support for specifying policy when storing options
125
    def __delitem__(self, key):
126
        self._calls.append(('__delitem__', key))
127
128
    def keys(self):
129
        self._calls.append(('keys',))
130
        return []
131
1551.2.49 by abentley
Made ConfigObj output binary-identical files on win32 and *nix
132
    def write(self, arg):
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
133
        self._calls.append(('write',))
134
2120.6.4 by James Henstridge
add support for specifying policy when storing options
135
    def as_bool(self, value):
136
        self._calls.append(('as_bool', value))
137
        return False
138
139
    def get_value(self, section, name):
140
        self._calls.append(('get_value', section, name))
141
        return None
142
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
143
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
144
class FakeBranch(object):
145
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
146
    def __init__(self, base=None, user_id=None):
147
        if base is None:
148
            self.base = "http://example.com/branches/demo"
149
        else:
150
            self.base = base
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
151
        self._transport = self.control_files = \
152
            FakeControlFilesAndTransport(user_id=user_id)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
153
4226.1.7 by Robert Collins
Alter test_config.FakeBranch in accordance with the Branch change to have a _get_config.
154
    def _get_config(self):
155
        return config.TransportConfig(self._transport, 'branch.conf')
156
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
157
    def lock_write(self):
158
        pass
159
160
    def unlock(self):
161
        pass
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
162
163
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
164
class FakeControlFilesAndTransport(object):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
165
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
166
    def __init__(self, user_id=None):
167
        self.files = {}
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
168
        if user_id:
169
            self.files['email'] = user_id
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
170
        self._transport = self
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
171
1185.65.29 by Robert Collins
Implement final review suggestions.
172
    def get_utf8(self, filename):
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
173
        # from LockableFiles
174
        raise AssertionError("get_utf8 should no longer be used")
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
175
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
176
    def get(self, filename):
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
177
        # from Transport
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
178
        try:
179
            return StringIO(self.files[filename])
180
        except KeyError:
181
            raise errors.NoSuchFile(filename)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
182
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
183
    def get_bytes(self, filename):
184
        # from Transport
185
        try:
186
            return self.files[filename]
187
        except KeyError:
188
            raise errors.NoSuchFile(filename)
189
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
190
    def put(self, filename, fileobj):
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
191
        self.files[filename] = fileobj.read()
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
192
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
193
    def put_file(self, filename, fileobj):
194
        return self.put(filename, fileobj)
195
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
196
197
class InstrumentedConfig(config.Config):
198
    """An instrumented config that supplies stubs for template methods."""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
199
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
200
    def __init__(self):
201
        super(InstrumentedConfig, self).__init__()
202
        self._calls = []
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
203
        self._signatures = config.CHECK_NEVER
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
204
205
    def _get_user_id(self):
206
        self._calls.append('_get_user_id')
207
        return "Robert Collins <robert.collins@example.org>"
208
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
209
    def _get_signature_checking(self):
210
        self._calls.append('_get_signature_checking')
211
        return self._signatures
212
4603.1.10 by Aaron Bentley
Provide change editor via config.
213
    def _get_change_editor(self):
214
        self._calls.append('_get_change_editor')
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
215
        return 'vimdiff -fo @new_path @old_path'
4603.1.10 by Aaron Bentley
Provide change editor via config.
216
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
217
1556.2.2 by Aaron Bentley
Fixed get_bool
218
bool_config = """[DEFAULT]
219
active = true
220
inactive = false
221
[UPPERCASE]
222
active = True
223
nonactive = False
224
"""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
225
226
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
227
class TestConfigObj(tests.TestCase):
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
228
1556.2.2 by Aaron Bentley
Fixed get_bool
229
    def test_get_bool(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
230
        co = config.ConfigObj(StringIO(bool_config))
1556.2.2 by Aaron Bentley
Fixed get_bool
231
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
232
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
233
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
234
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
235
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
236
    def test_hash_sign_in_value(self):
237
        """
238
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
239
        treated as comments when read in again. (#86838)
240
        """
241
        co = config.ConfigObj()
242
        co['test'] = 'foo#bar'
243
        lines = co.write()
244
        self.assertEqual(lines, ['test = "foo#bar"'])
245
        co2 = config.ConfigObj(lines)
246
        self.assertEqual(co2['test'], 'foo#bar')
247
1556.2.2 by Aaron Bentley
Fixed get_bool
248
2900.1.1 by Vincent Ladeuil
249
erroneous_config = """[section] # line 1
250
good=good # line 2
251
[section] # line 3
252
whocares=notme # line 4
253
"""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
254
255
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
256
class TestConfigObjErrors(tests.TestCase):
2900.1.1 by Vincent Ladeuil
257
258
    def test_duplicate_section_name_error_line(self):
259
        try:
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
260
            co = configobj.ConfigObj(StringIO(erroneous_config),
261
                                     raise_errors=True)
2900.1.1 by Vincent Ladeuil
262
        except config.configobj.DuplicateError, e:
263
            self.assertEqual(3, e.line_number)
264
        else:
265
            self.fail('Error in config file not detected')
266
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
267
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
268
class TestConfig(tests.TestCase):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
269
270
    def test_constructs(self):
271
        config.Config()
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
272
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
273
    def test_no_default_editor(self):
274
        self.assertRaises(NotImplementedError, config.Config().get_editor)
275
276
    def test_user_email(self):
277
        my_config = InstrumentedConfig()
278
        self.assertEqual('robert.collins@example.org', my_config.user_email())
279
        self.assertEqual(['_get_user_id'], my_config._calls)
280
281
    def test_username(self):
282
        my_config = InstrumentedConfig()
283
        self.assertEqual('Robert Collins <robert.collins@example.org>',
284
                         my_config.username())
285
        self.assertEqual(['_get_user_id'], my_config._calls)
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
286
287
    def test_signatures_default(self):
288
        my_config = config.Config()
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
289
        self.assertFalse(my_config.signature_needed())
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
290
        self.assertEqual(config.CHECK_IF_POSSIBLE,
291
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
292
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
293
                         my_config.signing_policy())
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
294
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
295
    def test_signatures_template_method(self):
296
        my_config = InstrumentedConfig()
297
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
298
        self.assertEqual(['_get_signature_checking'], my_config._calls)
299
300
    def test_signatures_template_method_none(self):
301
        my_config = InstrumentedConfig()
302
        my_config._signatures = None
303
        self.assertEqual(config.CHECK_IF_POSSIBLE,
304
                         my_config.signature_checking())
305
        self.assertEqual(['_get_signature_checking'], my_config._calls)
306
1442.1.56 by Robert Collins
gpg_signing_command configuration item
307
    def test_gpg_signing_command_default(self):
308
        my_config = config.Config()
309
        self.assertEqual('gpg', my_config.gpg_signing_command())
310
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
311
    def test_get_user_option_default(self):
312
        my_config = config.Config()
313
        self.assertEqual(None, my_config.get_user_option('no_option'))
314
1472 by Robert Collins
post commit hook, first pass implementation
315
    def test_post_commit_default(self):
316
        my_config = config.Config()
317
        self.assertEqual(None, my_config.post_commit())
318
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
319
    def test_log_format_default(self):
1553.2.8 by Erik Bågfors
tests for config log_formatter
320
        my_config = config.Config()
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
321
        self.assertEqual('long', my_config.log_format())
1553.2.8 by Erik Bågfors
tests for config log_formatter
322
4603.1.10 by Aaron Bentley
Provide change editor via config.
323
    def test_get_change_editor(self):
324
        my_config = InstrumentedConfig()
325
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
326
        self.assertEqual(['_get_change_editor'], my_config._calls)
327
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
328
        self.assertEqual(['vimdiff', '-fo', '@new_path', '@old_path'],
4603.1.10 by Aaron Bentley
Provide change editor via config.
329
                         change_editor.command_template)
330
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
331
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
332
class TestConfigPath(tests.TestCase):
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
333
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
334
    def setUp(self):
335
        super(TestConfigPath, self).setUp()
336
        os.environ['HOME'] = '/home/bogus'
4584.3.23 by Martin Pool
Correction to xdg_cache_dir and add a simple test
337
        os.environ['XDG_CACHE_DIR'] = ''
2309.2.6 by Alexander Belchenko
bzr now use Win32 API to determine Application Data location, and don't rely solely on $APPDATA
338
        if sys.platform == 'win32':
339
            os.environ['BZR_HOME'] = \
340
                r'C:\Documents and Settings\bogus\Application Data'
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
341
            self.bzr_home = \
342
                'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
343
        else:
344
            self.bzr_home = '/home/bogus/.bazaar'
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
345
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
346
    def test_config_dir(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
347
        self.assertEqual(config.config_dir(), self.bzr_home)
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
348
349
    def test_config_filename(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
350
        self.assertEqual(config.config_filename(),
351
                         self.bzr_home + '/bazaar.conf')
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
352
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
353
    def test_locations_config_filename(self):
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
354
        self.assertEqual(config.locations_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
355
                         self.bzr_home + '/locations.conf')
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
356
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
357
    def test_authentication_config_filename(self):
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
358
        self.assertEqual(config.authentication_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
359
                         self.bzr_home + '/authentication.conf')
360
4584.3.23 by Martin Pool
Correction to xdg_cache_dir and add a simple test
361
    def test_xdg_cache_dir(self):
362
        self.assertEqual(config.xdg_cache_dir(),
363
            '/home/bogus/.cache')
364
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
365
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
366
class TestIniConfig(tests.TestCase):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
367
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
368
    def make_config_parser(self, s):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
369
        conf = config.IniBasedConfig(_content=s)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
370
        return conf, conf._get_parser()
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
371
372
373
class TestIniConfigBuilding(TestIniConfig):
374
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
375
    def test_contructs(self):
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
376
        my_config = config.IniBasedConfig()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
377
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
378
    def test_from_fp(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
379
        my_config = config.IniBasedConfig(_content=sample_config_text)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
380
        self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
381
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
382
    def test_cached(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
383
        my_config = config.IniBasedConfig(_content=sample_config_text)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
384
        parser = my_config._get_parser()
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
385
        self.failUnless(my_config._get_parser() is parser)
386
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
387
    def test_get_filename_parameter_is_deprecated_(self):
388
        conf = self.callDeprecated([
389
            'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
390
            ' Use file_name instead.'],
391
            config.IniBasedConfig, lambda: 'ini.conf')
5345.3.1 by Vincent Ladeuil
Check that _get_filename() is called and produces the desired side effect.
392
        self.assertEqual('ini.conf', conf.file_name)
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
393
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
394
    def test_get_parser_file_parameter_is_deprecated_(self):
395
        config_file = StringIO(sample_config_text.encode('utf-8'))
5345.2.2 by Vincent Ladeuil
Simplify test config building.
396
        conf = config.IniBasedConfig(_content=sample_config_text)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
397
        conf = self.callDeprecated([
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
398
            'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
399
            ' Use IniBasedConfig(_content=xxx) instead.'],
400
            conf._get_parser, file=config_file)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
401
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
402
    def test_cant_save_without_a_file_name(self):
403
        conf = config.IniBasedConfig()
404
        self.assertRaises(AssertionError, conf._write_config_file)
405
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
406
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
407
class TestGetUserOptionAs(TestIniConfig):
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
408
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
409
    def test_get_user_option_as_bool(self):
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
410
        conf, parser = self.make_config_parser("""
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
411
a_true_bool = true
412
a_false_bool = 0
413
an_invalid_bool = maybe
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
414
a_list = hmm, who knows ? # This is interpreted as a list !
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
415
""")
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
416
        get_bool = conf.get_user_option_as_bool
417
        self.assertEqual(True, get_bool('a_true_bool'))
418
        self.assertEqual(False, get_bool('a_false_bool'))
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
419
        warnings = []
420
        def warning(*args):
421
            warnings.append(args[0] % args[1:])
422
        self.overrideAttr(trace, 'warning', warning)
423
        msg = 'Value "%s" is not a boolean for "%s"'
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
424
        self.assertIs(None, get_bool('an_invalid_bool'))
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
425
        self.assertEquals(msg % ('maybe', 'an_invalid_bool'), warnings[0])
426
        warnings = []
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
427
        self.assertIs(None, get_bool('not_defined_in_this_config'))
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
428
        self.assertEquals([], warnings)
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
429
430
    def test_get_user_option_as_list(self):
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
431
        conf, parser = self.make_config_parser("""
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
432
a_list = a,b,c
433
length_1 = 1,
434
one_item = x
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
435
""")
436
        get_list = conf.get_user_option_as_list
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
437
        self.assertEqual(['a', 'b', 'c'], get_list('a_list'))
438
        self.assertEqual(['1'], get_list('length_1'))
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
439
        self.assertEqual('x', conf.get_user_option('one_item'))
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
440
        # automatically cast to list
441
        self.assertEqual(['x'], get_list('one_item'))
442
443
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
444
class TestSupressWarning(TestIniConfig):
445
446
    def make_warnings_config(self, s):
447
        conf, parser = self.make_config_parser(s)
448
        return conf.suppress_warning
449
450
    def test_suppress_warning_unknown(self):
451
        suppress_warning = self.make_warnings_config('')
452
        self.assertEqual(False, suppress_warning('unknown_warning'))
453
454
    def test_suppress_warning_known(self):
455
        suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
456
        self.assertEqual(False, suppress_warning('c'))
457
        self.assertEqual(True, suppress_warning('a'))
458
        self.assertEqual(True, suppress_warning('b'))
459
460
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
461
class TestGetConfig(tests.TestCase):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
462
463
    def test_constructs(self):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
464
        my_config = config.GlobalConfig()
465
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
466
    def test_calls_read_filenames(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
467
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
468
        oldparserclass = config.ConfigObj
469
        config.ConfigObj = InstrumentedConfigObj
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
470
        my_config = config.GlobalConfig()
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
471
        try:
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
472
            parser = my_config._get_parser()
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
473
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
474
            config.ConfigObj = oldparserclass
475
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
1551.2.20 by Aaron Bentley
Treated config files as utf-8
476
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
477
                                          'utf-8')])
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
478
479
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
480
class TestBranchConfig(tests.TestCaseWithTransport):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
481
482
    def test_constructs(self):
483
        branch = FakeBranch()
484
        my_config = config.BranchConfig(branch)
485
        self.assertRaises(TypeError, config.BranchConfig)
486
487
    def test_get_location_config(self):
488
        branch = FakeBranch()
489
        my_config = config.BranchConfig(branch)
490
        location_config = my_config._get_location_config()
491
        self.assertEqual(branch.base, location_config.location)
492
        self.failUnless(location_config is my_config._get_location_config())
493
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
494
    def test_get_config(self):
495
        """The Branch.get_config method works properly"""
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
496
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
497
        my_config = b.get_config()
498
        self.assertIs(my_config.get_user_option('wacky'), None)
499
        my_config.set_user_option('wacky', 'unlikely')
500
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
501
502
        # Ensure we get the same thing if we start again
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
503
        b2 = branch.Branch.open('.')
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
504
        my_config2 = b2.get_config()
505
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
506
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
507
    def test_has_explicit_nickname(self):
508
        b = self.make_branch('.')
509
        self.assertFalse(b.get_config().has_explicit_nickname())
510
        b.nick = 'foo'
511
        self.assertTrue(b.get_config().has_explicit_nickname())
512
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
513
    def test_config_url(self):
514
        """The Branch.get_config will use section that uses a local url"""
515
        branch = self.make_branch('branch')
516
        self.assertEqual('branch', branch.nick)
517
518
        locations = config.locations_config_filename()
519
        config.ensure_config_dir_exists()
520
        local_url = urlutils.local_path_to_url('branch')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
521
        open(locations, 'wb').write('[%s]\nnickname = foobar'
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
522
                                    % (local_url,))
523
        self.assertEqual('foobar', branch.nick)
524
525
    def test_config_local_path(self):
526
        """The Branch.get_config will use a local system path"""
527
        branch = self.make_branch('branch')
528
        self.assertEqual('branch', branch.nick)
529
530
        locations = config.locations_config_filename()
531
        config.ensure_config_dir_exists()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
532
        open(locations, 'wb').write('[%s/branch]\nnickname = barry'
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
533
                                    % (osutils.getcwd().encode('utf8'),))
534
        self.assertEqual('barry', branch.nick)
535
1878.1.2 by John Arbash Meinel
Add a test that new locations.conf entries are created with a local path, rather than a URL
536
    def test_config_creates_local(self):
537
        """Creating a new entry in config uses a local path."""
2230.3.6 by Aaron Bentley
work in progress bind stuff
538
        branch = self.make_branch('branch', format='knit')
1878.1.2 by John Arbash Meinel
Add a test that new locations.conf entries are created with a local path, rather than a URL
539
        branch.set_push_location('http://foobar')
540
        locations = config.locations_config_filename()
541
        local_path = osutils.getcwd().encode('utf8')
542
        # Surprisingly ConfigObj doesn't create a trailing newline
543
        self.check_file_contents(locations,
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
544
                                 '[%s/branch]\n'
545
                                 'push_location = http://foobar\n'
3221.7.1 by Matt Nordhoff
Upgrade ConfigObj to version 4.5.1.
546
                                 'push_location:policy = norecurse\n'
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
547
                                 % (local_path,))
1878.1.2 by John Arbash Meinel
Add a test that new locations.conf entries are created with a local path, rather than a URL
548
2120.5.4 by Alexander Belchenko
Whitebox test for Config.get_nickname (req. by Aaron Bentley)
549
    def test_autonick_urlencoded(self):
550
        b = self.make_branch('!repo')
551
        self.assertEqual('!repo', b.get_config().get_nickname())
552
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
553
    def test_warn_if_masked(self):
554
        _warning = trace.warning
555
        warnings = []
556
        def warning(*args):
557
            warnings.append(args[0] % args[1:])
558
559
        def set_option(store, warn_masked=True):
560
            warnings[:] = []
561
            conf.set_user_option('example_option', repr(store), store=store,
562
                                 warn_masked=warn_masked)
563
        def assertWarning(warning):
564
            if warning is None:
565
                self.assertEqual(0, len(warnings))
566
            else:
567
                self.assertEqual(1, len(warnings))
568
                self.assertEqual(warning, warnings[0])
569
        trace.warning = warning
570
        try:
571
            branch = self.make_branch('.')
572
            conf = branch.get_config()
573
            set_option(config.STORE_GLOBAL)
574
            assertWarning(None)
575
            set_option(config.STORE_BRANCH)
576
            assertWarning(None)
577
            set_option(config.STORE_GLOBAL)
578
            assertWarning('Value "4" is masked by "3" from branch.conf')
579
            set_option(config.STORE_GLOBAL, warn_masked=False)
580
            assertWarning(None)
581
            set_option(config.STORE_LOCATION)
582
            assertWarning(None)
583
            set_option(config.STORE_BRANCH)
584
            assertWarning('Value "3" is masked by "0" from locations.conf')
585
            set_option(config.STORE_BRANCH, warn_masked=False)
586
            assertWarning(None)
587
        finally:
588
            trace.warning = _warning
589
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
590
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
591
class TestGlobalConfigItems(tests.TestCase):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
592
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
593
    def test_user_id(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
594
        my_config = config.GlobalConfig(_content=sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
595
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
596
                         my_config._get_user_id())
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
597
598
    def test_absent_user_id(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
599
        my_config = config.GlobalConfig()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
600
        self.assertEqual(None, my_config._get_user_id())
601
602
    def test_configured_editor(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
603
        my_config = config.GlobalConfig(_content=sample_config_text)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
604
        self.assertEqual("vim", my_config.get_editor())
605
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
606
    def test_signatures_always(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
607
        my_config = config.GlobalConfig(_content=sample_always_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
608
        self.assertEqual(config.CHECK_NEVER,
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
609
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
610
        self.assertEqual(config.SIGN_ALWAYS,
611
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
612
        self.assertEqual(True, my_config.signature_needed())
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
613
614
    def test_signatures_if_possible(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
615
        my_config = config.GlobalConfig(_content=sample_maybe_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
616
        self.assertEqual(config.CHECK_NEVER,
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
617
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
618
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
619
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
620
        self.assertEqual(False, my_config.signature_needed())
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
621
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
622
    def test_signatures_ignore(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
623
        my_config = config.GlobalConfig(_content=sample_ignore_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
624
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
625
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
626
        self.assertEqual(config.SIGN_NEVER,
627
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
628
        self.assertEqual(False, my_config.signature_needed())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
629
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
630
    def _get_sample_config(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
631
        my_config = config.GlobalConfig(_content=sample_config_text)
1534.7.154 by Aaron Bentley
Removed changes from bzr.ab 1529..1536
632
        return my_config
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
633
1442.1.56 by Robert Collins
gpg_signing_command configuration item
634
    def test_gpg_signing_command(self):
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
635
        my_config = self._get_sample_config()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
636
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
637
        self.assertEqual(False, my_config.signature_needed())
638
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
639
    def _get_empty_config(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
640
        my_config = config.GlobalConfig()
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
641
        return my_config
642
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
643
    def test_gpg_signing_command_unset(self):
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
644
        my_config = self._get_empty_config()
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
645
        self.assertEqual("gpg", my_config.gpg_signing_command())
646
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
647
    def test_get_user_option_default(self):
648
        my_config = self._get_empty_config()
649
        self.assertEqual(None, my_config.get_user_option('no_option'))
650
651
    def test_get_user_option_global(self):
652
        my_config = self._get_sample_config()
653
        self.assertEqual("something",
654
                         my_config.get_user_option('user_global_option'))
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
655
1472 by Robert Collins
post commit hook, first pass implementation
656
    def test_post_commit_default(self):
657
        my_config = self._get_sample_config()
658
        self.assertEqual(None, my_config.post_commit())
659
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
660
    def test_configured_logformat(self):
1553.2.8 by Erik Bågfors
tests for config log_formatter
661
        my_config = self._get_sample_config()
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
662
        self.assertEqual("short", my_config.log_format())
1553.2.8 by Erik Bågfors
tests for config log_formatter
663
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
664
    def test_get_alias(self):
665
        my_config = self._get_sample_config()
666
        self.assertEqual('help', my_config.get_alias('h'))
667
2900.3.6 by Tim Penhey
Added tests.
668
    def test_get_aliases(self):
669
        my_config = self._get_sample_config()
670
        aliases = my_config.get_aliases()
671
        self.assertEqual(2, len(aliases))
672
        sorted_keys = sorted(aliases)
673
        self.assertEqual('help', aliases[sorted_keys[0]])
674
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
675
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
676
    def test_get_no_alias(self):
677
        my_config = self._get_sample_config()
678
        self.assertEqual(None, my_config.get_alias('foo'))
679
680
    def test_get_long_alias(self):
681
        my_config = self._get_sample_config()
682
        self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
683
4603.1.10 by Aaron Bentley
Provide change editor via config.
684
    def test_get_change_editor(self):
685
        my_config = self._get_sample_config()
686
        change_editor = my_config.get_change_editor('old', 'new')
687
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
688
        self.assertEqual('vimdiff -of @new_path @old_path',
4603.1.10 by Aaron Bentley
Provide change editor via config.
689
                         ' '.join(change_editor.command_template))
690
691
    def test_get_no_change_editor(self):
692
        my_config = self._get_empty_config()
693
        change_editor = my_config.get_change_editor('old', 'new')
694
        self.assertIs(None, change_editor)
695
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
696
2900.3.6 by Tim Penhey
Added tests.
697
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
698
699
    def test_empty(self):
700
        my_config = config.GlobalConfig()
701
        self.assertEqual(0, len(my_config.get_aliases()))
702
703
    def test_set_alias(self):
704
        my_config = config.GlobalConfig()
705
        alias_value = 'commit --strict'
706
        my_config.set_alias('commit', alias_value)
707
        new_config = config.GlobalConfig()
708
        self.assertEqual(alias_value, new_config.get_alias('commit'))
709
710
    def test_remove_alias(self):
711
        my_config = config.GlobalConfig()
712
        my_config.set_alias('commit', 'commit --strict')
713
        # Now remove the alias again.
714
        my_config.unset_alias('commit')
715
        new_config = config.GlobalConfig()
716
        self.assertIs(None, new_config.get_alias('commit'))
717
718
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
719
class TestLocationConfig(tests.TestCaseInTempDir):
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
720
721
    def test_constructs(self):
722
        my_config = config.LocationConfig('http://example.com')
723
        self.assertRaises(TypeError, config.LocationConfig)
724
725
    def test_branch_calls_read_filenames(self):
1474 by Robert Collins
Merge from Aaron Bentley.
726
        # This is testing the correct file names are provided.
727
        # TODO: consolidate with the test for GlobalConfigs filename checks.
728
        #
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
729
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
730
        oldparserclass = config.ConfigObj
731
        config.ConfigObj = InstrumentedConfigObj
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
732
        try:
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
733
            my_config = config.LocationConfig('http://www.example.com')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
734
            parser = my_config._get_parser()
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
735
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
736
            config.ConfigObj = oldparserclass
737
        self.failUnless(isinstance(parser, InstrumentedConfigObj))
738
        self.assertEqual(parser._calls,
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
739
                         [('__init__', config.locations_config_filename(),
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
740
                           'utf-8')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
741
742
    def test_get_global_config(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
743
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
744
        global_config = my_config._get_global_config()
745
        self.failUnless(isinstance(global_config, config.GlobalConfig))
746
        self.failUnless(global_config is my_config._get_global_config())
747
1993.3.1 by James Henstridge
first go at making location config lookup recursive
748
    def test__get_matching_sections_no_match(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
749
        self.get_branch_config('/')
1993.3.1 by James Henstridge
first go at making location config lookup recursive
750
        self.assertEqual([], self.my_location_config._get_matching_sections())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
751
1993.3.1 by James Henstridge
first go at making location config lookup recursive
752
    def test__get_matching_sections_exact(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
753
        self.get_branch_config('http://www.example.com')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
754
        self.assertEqual([('http://www.example.com', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
755
                         self.my_location_config._get_matching_sections())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
756
1993.3.1 by James Henstridge
first go at making location config lookup recursive
757
    def test__get_matching_sections_suffix_does_not(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
758
        self.get_branch_config('http://www.example.com-com')
1993.3.1 by James Henstridge
first go at making location config lookup recursive
759
        self.assertEqual([], self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
760
1993.3.1 by James Henstridge
first go at making location config lookup recursive
761
    def test__get_matching_sections_subdir_recursive(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
762
        self.get_branch_config('http://www.example.com/com')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
763
        self.assertEqual([('http://www.example.com', 'com')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
764
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
765
1993.3.5 by James Henstridge
add back recurse=False option to config file
766
    def test__get_matching_sections_ignoreparent(self):
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
767
        self.get_branch_config('http://www.example.com/ignoreparent')
768
        self.assertEqual([('http://www.example.com/ignoreparent', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
769
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
770
1993.3.5 by James Henstridge
add back recurse=False option to config file
771
    def test__get_matching_sections_ignoreparent_subdir(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
772
        self.get_branch_config(
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
773
            'http://www.example.com/ignoreparent/childbranch')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
774
        self.assertEqual([('http://www.example.com/ignoreparent',
775
                           'childbranch')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
776
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
777
1993.3.1 by James Henstridge
first go at making location config lookup recursive
778
    def test__get_matching_sections_subdir_trailing_slash(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
779
        self.get_branch_config('/b')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
780
        self.assertEqual([('/b/', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
781
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
782
1993.3.1 by James Henstridge
first go at making location config lookup recursive
783
    def test__get_matching_sections_subdir_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
784
        self.get_branch_config('/a/foo')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
785
        self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
786
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
787
1993.3.1 by James Henstridge
first go at making location config lookup recursive
788
    def test__get_matching_sections_subdir_child_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
789
        self.get_branch_config('/a/foo/bar')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
790
        self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
791
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
792
1993.3.1 by James Henstridge
first go at making location config lookup recursive
793
    def test__get_matching_sections_trailing_slash_with_children(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
794
        self.get_branch_config('/a/')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
795
        self.assertEqual([('/a/', '')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
796
                         self.my_location_config._get_matching_sections())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
797
1993.3.1 by James Henstridge
first go at making location config lookup recursive
798
    def test__get_matching_sections_explicit_over_glob(self):
799
        # XXX: 2006-09-08 jamesh
800
        # This test only passes because ord('c') > ord('*').  If there
801
        # was a config section for '/a/?', it would get precedence
802
        # over '/a/c'.
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
803
        self.get_branch_config('/a/c')
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
804
        self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
1993.3.1 by James Henstridge
first go at making location config lookup recursive
805
                         self.my_location_config._get_matching_sections())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
806
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
807
    def test__get_option_policy_normal(self):
808
        self.get_branch_config('http://www.example.com')
809
        self.assertEqual(
810
            self.my_location_config._get_config_policy(
811
            'http://www.example.com', 'normal_option'),
812
            config.POLICY_NONE)
813
814
    def test__get_option_policy_norecurse(self):
815
        self.get_branch_config('http://www.example.com')
816
        self.assertEqual(
817
            self.my_location_config._get_option_policy(
818
            'http://www.example.com', 'norecurse_option'),
819
            config.POLICY_NORECURSE)
820
        # Test old recurse=False setting:
821
        self.assertEqual(
822
            self.my_location_config._get_option_policy(
823
            'http://www.example.com/norecurse', 'normal_option'),
824
            config.POLICY_NORECURSE)
825
826
    def test__get_option_policy_normal(self):
827
        self.get_branch_config('http://www.example.com')
828
        self.assertEqual(
829
            self.my_location_config._get_option_policy(
830
            'http://www.example.com', 'appendpath_option'),
831
            config.POLICY_APPENDPATH)
832
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
833
    def test_location_without_username(self):
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
834
        self.get_branch_config('http://www.example.com/ignoreparent')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
835
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
836
                         self.my_config.username())
837
838
    def test_location_not_listed(self):
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
839
        """Test that the global username is used when no location matches"""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
840
        self.get_branch_config('/home/robertc/sources')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
841
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
842
                         self.my_config.username())
843
1442.1.13 by Robert Collins
branches.conf is now able to override the users email
844
    def test_overriding_location(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
845
        self.get_branch_config('http://www.example.com/foo')
1442.1.13 by Robert Collins
branches.conf is now able to override the users email
846
        self.assertEqual('Robert Collins <robertc@example.org>',
847
                         self.my_config.username())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
848
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
849
    def test_signatures_not_set(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
850
        self.get_branch_config('http://www.example.com',
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
851
                                 global_config=sample_ignore_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
852
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
853
                         self.my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
854
        self.assertEqual(config.SIGN_NEVER,
855
                         self.my_config.signing_policy())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
856
857
    def test_signatures_never(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
858
        self.get_branch_config('/a/c')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
859
        self.assertEqual(config.CHECK_NEVER,
860
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
861
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
862
    def test_signatures_when_available(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
863
        self.get_branch_config('/a/', global_config=sample_ignore_signatures)
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
864
        self.assertEqual(config.CHECK_IF_POSSIBLE,
865
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
866
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
867
    def test_signatures_always(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
868
        self.get_branch_config('/b')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
869
        self.assertEqual(config.CHECK_ALWAYS,
870
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
871
1442.1.56 by Robert Collins
gpg_signing_command configuration item
872
    def test_gpg_signing_command(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
873
        self.get_branch_config('/b')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
874
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
875
876
    def test_gpg_signing_command_missing(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
877
        self.get_branch_config('/a')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
878
        self.assertEqual("false", self.my_config.gpg_signing_command())
879
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
880
    def test_get_user_option_global(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
881
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
882
        self.assertEqual('something',
883
                         self.my_config.get_user_option('user_global_option'))
884
885
    def test_get_user_option_local(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
886
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
887
        self.assertEqual('local',
888
                         self.my_config.get_user_option('user_local_option'))
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
889
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
890
    def test_get_user_option_appendpath(self):
891
        # returned as is for the base path:
892
        self.get_branch_config('http://www.example.com')
893
        self.assertEqual('append',
894
                         self.my_config.get_user_option('appendpath_option'))
895
        # Extra path components get appended:
896
        self.get_branch_config('http://www.example.com/a/b/c')
897
        self.assertEqual('append/a/b/c',
898
                         self.my_config.get_user_option('appendpath_option'))
899
        # Overriden for http://www.example.com/dir, where it is a
900
        # normal option:
901
        self.get_branch_config('http://www.example.com/dir/a/b/c')
902
        self.assertEqual('normal',
903
                         self.my_config.get_user_option('appendpath_option'))
904
905
    def test_get_user_option_norecurse(self):
906
        self.get_branch_config('http://www.example.com')
907
        self.assertEqual('norecurse',
908
                         self.my_config.get_user_option('norecurse_option'))
909
        self.get_branch_config('http://www.example.com/dir')
910
        self.assertEqual(None,
911
                         self.my_config.get_user_option('norecurse_option'))
912
        # http://www.example.com/norecurse is a recurse=False section
913
        # that redefines normal_option.  Subdirectories do not pick up
914
        # this redefinition.
915
        self.get_branch_config('http://www.example.com/norecurse')
916
        self.assertEqual('norecurse',
917
                         self.my_config.get_user_option('normal_option'))
918
        self.get_branch_config('http://www.example.com/norecurse/subdir')
919
        self.assertEqual('normal',
920
                         self.my_config.get_user_option('normal_option'))
921
2120.6.4 by James Henstridge
add support for specifying policy when storing options
922
    def test_set_user_option_norecurse(self):
923
        self.get_branch_config('http://www.example.com')
924
        self.my_config.set_user_option('foo', 'bar',
925
                                       store=config.STORE_LOCATION_NORECURSE)
926
        self.assertEqual(
927
            self.my_location_config._get_option_policy(
928
            'http://www.example.com', 'foo'),
929
            config.POLICY_NORECURSE)
930
931
    def test_set_user_option_appendpath(self):
932
        self.get_branch_config('http://www.example.com')
933
        self.my_config.set_user_option('foo', 'bar',
934
                                       store=config.STORE_LOCATION_APPENDPATH)
935
        self.assertEqual(
936
            self.my_location_config._get_option_policy(
937
            'http://www.example.com', 'foo'),
938
            config.POLICY_APPENDPATH)
939
940
    def test_set_user_option_change_policy(self):
941
        self.get_branch_config('http://www.example.com')
942
        self.my_config.set_user_option('norecurse_option', 'normal',
943
                                       store=config.STORE_LOCATION)
944
        self.assertEqual(
945
            self.my_location_config._get_option_policy(
946
            'http://www.example.com', 'norecurse_option'),
947
            config.POLICY_NONE)
948
949
    def test_set_user_option_recurse_false_section(self):
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
950
        # The following section has recurse=False set.  The test is to
951
        # make sure that a normal option can be added to the section,
952
        # converting recurse=False to the norecurse policy.
2120.6.4 by James Henstridge
add support for specifying policy when storing options
953
        self.get_branch_config('http://www.example.com/norecurse')
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
954
        self.callDeprecated(['The recurse option is deprecated as of 0.14.  '
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
955
                             'The section "http://www.example.com/norecurse" '
956
                             'has been converted to use policies.'],
957
                            self.my_config.set_user_option,
958
                            'foo', 'bar', store=config.STORE_LOCATION)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
959
        self.assertEqual(
960
            self.my_location_config._get_option_policy(
961
            'http://www.example.com/norecurse', 'foo'),
962
            config.POLICY_NONE)
963
        # The previously existing option is still norecurse:
964
        self.assertEqual(
965
            self.my_location_config._get_option_policy(
966
            'http://www.example.com/norecurse', 'normal_option'),
967
            config.POLICY_NORECURSE)
968
1472 by Robert Collins
post commit hook, first pass implementation
969
    def test_post_commit_default(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
970
        self.get_branch_config('/a/c')
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
971
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
972
                         self.my_config.post_commit())
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
973
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
974
    def get_branch_config(self, location, global_config=None):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
975
        my_branch = FakeBranch(location)
1502 by Robert Collins
Bugfix the config test suite to not create .bazaar in the dir where it is run.
976
        if global_config is None:
5345.2.2 by Vincent Ladeuil
Simplify test config building.
977
            global_config = sample_config_text
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
978
979
        config.ensure_config_dir_exists()
5345.2.2 by Vincent Ladeuil
Simplify test config building.
980
        my_global_config = config.GlobalConfig(_content=global_config)
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
981
        my_global_config._write_config_file()
5345.2.2 by Vincent Ladeuil
Simplify test config building.
982
        my_location_config = config.LocationConfig(
983
            my_branch.base, _content=sample_branches_text)
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
984
        my_location_config._write_config_file()
985
986
        my_config = config.BranchConfig(my_branch)
987
        self.my_config = my_config
988
        self.my_location_config = my_config._get_location_config()
1502 by Robert Collins
Bugfix the config test suite to not create .bazaar in the dir where it is run.
989
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
990
    def test_set_user_setting_sets_and_saves(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
991
        self.get_branch_config('/a/c')
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
992
        record = InstrumentedConfigObj("foo")
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
993
        self.my_location_config._parser = record
1185.62.6 by John Arbash Meinel
Updated test_set_user_setting_sets_and_saves to remove the print statement, and make sure it is doing the right thing
994
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
995
        self.callDeprecated(['The recurse option is deprecated as of '
996
                             '0.14.  The section "/a/c" has been '
997
                             'converted to use policies.'],
998
                            self.my_config.set_user_option,
999
                            'foo', 'bar', store=config.STORE_LOCATION)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1000
        self.assertEqual([('__contains__', '/a/c'),
1001
                          ('__contains__', '/a/c/'),
1002
                          ('__setitem__', '/a/c', {}),
1003
                          ('__getitem__', '/a/c'),
1004
                          ('__setitem__', 'foo', 'bar'),
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1005
                          ('__getitem__', '/a/c'),
1006
                          ('as_bool', 'recurse'),
1007
                          ('__getitem__', '/a/c'),
1008
                          ('__delitem__', 'recurse'),
1009
                          ('__getitem__', '/a/c'),
1010
                          ('keys',),
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1011
                          ('__getitem__', '/a/c'),
1012
                          ('__contains__', 'foo:policy'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1013
                          ('write',)],
1014
                         record._calls[1:])
1015
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1016
    def test_set_user_setting_sets_and_saves2(self):
1017
        self.get_branch_config('/a/c')
1018
        self.assertIs(self.my_config.get_user_option('foo'), None)
1019
        self.my_config.set_user_option('foo', 'bar')
1020
        self.assertEqual(
3616.2.6 by Mark Hammond
Fix test_set_user_setting_sets_and_saves2 on windows by stripping EOL
1021
            self.my_config.branch.control_files.files['branch.conf'].strip(),
1022
            'foo = bar')
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1023
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1024
        self.my_config.set_user_option('foo', 'baz',
1025
                                       store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1026
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1027
        self.my_config.set_user_option('foo', 'qux')
1028
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1029
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1030
    def test_get_bzr_remote_path(self):
1031
        my_config = config.LocationConfig('/a/c')
1032
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1033
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1034
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1035
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
1036
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1037
1185.62.7 by John Arbash Meinel
Whitespace cleanup.
1038
1770.2.8 by Aaron Bentley
Add precedence test
1039
precedence_global = 'option = global'
1040
precedence_branch = 'option = branch'
1041
precedence_location = """
1042
[http://]
1043
recurse = true
1044
option = recurse
1045
[http://example.com/specific]
1046
option = exact
1047
"""
1048
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1049
class TestBranchConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1050
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1051
    def get_branch_config(self, global_config=None, location=None,
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1052
                          location_config=None, branch_data_config=None):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1053
        my_branch = FakeBranch(location)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1054
        if global_config is not None:
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1055
            my_global_config = config.GlobalConfig(_content=global_config)
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1056
            config.ensure_config_dir_exists()
1057
            my_global_config._write_config_file()
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1058
        if location_config is not None:
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1059
            my_location_config = config.LocationConfig(my_branch.base,
1060
                                                       _content=location_config)
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1061
            config.ensure_config_dir_exists()
1062
            my_location_config._write_config_file()
1063
        my_config = config.BranchConfig(my_branch)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1064
        if branch_data_config is not None:
1065
            my_config.branch.control_files.files['branch.conf'] = \
1066
                branch_data_config
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1067
        return my_config
1068
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1069
    def test_user_id(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1070
        branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1071
        my_config = config.BranchConfig(branch)
1072
        self.assertEqual("Robert Collins <robertc@example.net>",
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1073
                         my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1074
        my_config.branch.control_files.files['email'] = "John"
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1075
        my_config.set_user_option('email',
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1076
                                  "Robert Collins <robertc@example.org>")
1077
        self.assertEqual("John", my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1078
        del my_config.branch.control_files.files['email']
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1079
        self.assertEqual("Robert Collins <robertc@example.org>",
1080
                         my_config.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1081
1082
    def test_not_set_in_branch(self):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1083
        my_config = self.get_branch_config(global_config=sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
1084
        self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1085
                         my_config._get_user_id())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1086
        my_config.branch.control_files.files['email'] = "John"
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1087
        self.assertEqual("John", my_config._get_user_id())
1088
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
1089
    def test_BZR_EMAIL_OVERRIDES(self):
1090
        os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1091
        branch = FakeBranch()
1092
        my_config = config.BranchConfig(branch)
1093
        self.assertEqual("Robert Collins <robertc@example.org>",
1094
                         my_config.username())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1095
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1096
    def test_signatures_forced(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1097
        my_config = self.get_branch_config(
1098
            global_config=sample_always_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1099
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1100
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1101
        self.assertTrue(my_config.signature_needed())
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1102
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1103
    def test_signatures_forced_branch(self):
1104
        my_config = self.get_branch_config(
1105
            global_config=sample_ignore_signatures,
1106
            branch_data_config=sample_always_signatures)
1107
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1108
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1109
        self.assertTrue(my_config.signature_needed())
1110
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1111
    def test_gpg_signing_command(self):
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1112
        my_config = self.get_branch_config(
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1113
            global_config=sample_config_text,
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1114
            # branch data cannot set gpg_signing_command
1115
            branch_data_config="gpg_signing_command=pgp")
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1116
        self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1117
1118
    def test_get_user_option_global(self):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1119
        my_config = self.get_branch_config(global_config=sample_config_text)
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1120
        self.assertEqual('something',
1121
                         my_config.get_user_option('user_global_option'))
1472 by Robert Collins
post commit hook, first pass implementation
1122
1123
    def test_post_commit_default(self):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1124
        my_config = self.get_branch_config(global_config=sample_config_text,
1125
                                      location='/a/c',
1126
                                      location_config=sample_branches_text)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1127
        self.assertEqual(my_config.branch.base, '/a/c')
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
1128
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1129
                         my_config.post_commit())
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1130
        my_config.set_user_option('post_commit', 'rmtree_root')
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1131
        # post-commit is ignored when present in branch data
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1132
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1133
                         my_config.post_commit())
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1134
        my_config.set_user_option('post_commit', 'rmtree_root',
1135
                                  store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1136
        self.assertEqual('rmtree_root', my_config.post_commit())
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1137
1770.2.8 by Aaron Bentley
Add precedence test
1138
    def test_config_precedence(self):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1139
        # FIXME: eager test, luckily no persitent config file makes it fail
1140
        # -- vila 20100716
1770.2.8 by Aaron Bentley
Add precedence test
1141
        my_config = self.get_branch_config(global_config=precedence_global)
1142
        self.assertEqual(my_config.get_user_option('option'), 'global')
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1143
        my_config = self.get_branch_config(global_config=precedence_global,
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1144
                                           branch_data_config=precedence_branch)
1770.2.8 by Aaron Bentley
Add precedence test
1145
        self.assertEqual(my_config.get_user_option('option'), 'branch')
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1146
        my_config = self.get_branch_config(
1147
            global_config=precedence_global,
1148
            branch_data_config=precedence_branch,
1149
            location_config=precedence_location)
1770.2.8 by Aaron Bentley
Add precedence test
1150
        self.assertEqual(my_config.get_user_option('option'), 'recurse')
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1151
        my_config = self.get_branch_config(
1152
            global_config=precedence_global,
1153
            branch_data_config=precedence_branch,
1154
            location_config=precedence_location,
1155
            location='http://example.com/specific')
1770.2.8 by Aaron Bentley
Add precedence test
1156
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1157
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
1158
    def test_get_mail_client(self):
1159
        config = self.get_branch_config()
1160
        client = config.get_mail_client()
2681.1.24 by Aaron Bentley
Handle default mail client by trying xdg-email, falling back to editor
1161
        self.assertIsInstance(client, mail_client.DefaultMail)
1162
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1163
        # Specific clients
2681.1.21 by Aaron Bentley
Refactor prompt generation to make it testable, test it with unicode
1164
        config.set_user_option('mail_client', 'evolution')
1165
        client = config.get_mail_client()
1166
        self.assertIsInstance(client, mail_client.Evolution)
1167
2681.5.1 by ghigo
Add KMail support to bzr send
1168
        config.set_user_option('mail_client', 'kmail')
1169
        client = config.get_mail_client()
1170
        self.assertIsInstance(client, mail_client.KMail)
1171
2790.2.1 by Keir Mierle
Add Mutt as a supported client email program. Also rearranges various listings
1172
        config.set_user_option('mail_client', 'mutt')
1173
        client = config.get_mail_client()
1174
        self.assertIsInstance(client, mail_client.Mutt)
1175
1176
        config.set_user_option('mail_client', 'thunderbird')
1177
        client = config.get_mail_client()
1178
        self.assertIsInstance(client, mail_client.Thunderbird)
1179
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1180
        # Generic options
1181
        config.set_user_option('mail_client', 'default')
1182
        client = config.get_mail_client()
1183
        self.assertIsInstance(client, mail_client.DefaultMail)
1184
1185
        config.set_user_option('mail_client', 'editor')
1186
        client = config.get_mail_client()
1187
        self.assertIsInstance(client, mail_client.Editor)
1188
1189
        config.set_user_option('mail_client', 'mapi')
1190
        client = config.get_mail_client()
1191
        self.assertIsInstance(client, mail_client.MAPIClient)
1192
2681.1.23 by Aaron Bentley
Add support for xdg-email
1193
        config.set_user_option('mail_client', 'xdg-email')
1194
        client = config.get_mail_client()
1195
        self.assertIsInstance(client, mail_client.XDGEmail)
1196
2681.1.10 by Aaron Bentley
Clean up handling of unknown mail clients
1197
        config.set_user_option('mail_client', 'firebird')
1198
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1199
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1200
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1201
class TestMailAddressExtraction(tests.TestCase):
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1202
1203
    def test_extract_email_address(self):
1204
        self.assertEqual('jane@test.com',
1205
                         config.extract_email_address('Jane <jane@test.com>'))
2055.2.2 by John Arbash Meinel
Switch extract_email_address() to use a more specific exception
1206
        self.assertRaises(errors.NoEmailInUsername,
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1207
                          config.extract_email_address, 'Jane Tester')
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1208
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1209
    def test_parse_username(self):
1210
        self.assertEqual(('', 'jdoe@example.com'),
1211
                         config.parse_username('jdoe@example.com'))
1212
        self.assertEqual(('', 'jdoe@example.com'),
1213
                         config.parse_username('<jdoe@example.com>'))
1214
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1215
                         config.parse_username('John Doe <jdoe@example.com>'))
1216
        self.assertEqual(('John Doe', ''),
1217
                         config.parse_username('John Doe'))
3063.3.3 by Lukáš Lalinský
Add one more test for config.parse_username().
1218
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1219
                         config.parse_username('John Doe jdoe@example.com'))
2562.1.2 by John Arbash Meinel
Clean up whitespace
1220
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1221
class TestTreeConfig(tests.TestCaseWithTransport):
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1222
1223
    def test_get_value(self):
1224
        """Test that retreiving a value from a section is possible"""
1225
        branch = self.make_branch('.')
1226
        tree_config = config.TreeConfig(branch)
1227
        tree_config.set_option('value', 'key', 'SECTION')
1228
        tree_config.set_option('value2', 'key2')
1229
        tree_config.set_option('value3-top', 'key3')
1230
        tree_config.set_option('value3-section', 'key3', 'SECTION')
1231
        value = tree_config.get_option('key', 'SECTION')
1232
        self.assertEqual(value, 'value')
1233
        value = tree_config.get_option('key2')
1234
        self.assertEqual(value, 'value2')
1235
        self.assertEqual(tree_config.get_option('non-existant'), None)
1236
        value = tree_config.get_option('non-existant', 'SECTION')
1237
        self.assertEqual(value, None)
1238
        value = tree_config.get_option('non-existant', default='default')
1239
        self.assertEqual(value, 'default')
1240
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1241
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
1242
        self.assertEqual(value, 'default')
1243
        value = tree_config.get_option('key3')
1244
        self.assertEqual(value, 'value3-top')
1245
        value = tree_config.get_option('key3', 'SECTION')
1246
        self.assertEqual(value, 'value3-section')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1247
1248
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1249
class TestTransportConfig(tests.TestCaseWithTransport):
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1250
1251
    def test_get_value(self):
1252
        """Test that retreiving a value from a section is possible"""
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1253
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1254
                                               'control.conf')
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1255
        bzrdir_config.set_option('value', 'key', 'SECTION')
1256
        bzrdir_config.set_option('value2', 'key2')
1257
        bzrdir_config.set_option('value3-top', 'key3')
1258
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1259
        value = bzrdir_config.get_option('key', 'SECTION')
1260
        self.assertEqual(value, 'value')
1261
        value = bzrdir_config.get_option('key2')
1262
        self.assertEqual(value, 'value2')
1263
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1264
        value = bzrdir_config.get_option('non-existant', 'SECTION')
1265
        self.assertEqual(value, None)
1266
        value = bzrdir_config.get_option('non-existant', default='default')
1267
        self.assertEqual(value, 'default')
1268
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1269
        value = bzrdir_config.get_option('key2', 'NOSECTION',
1270
                                         default='default')
1271
        self.assertEqual(value, 'default')
1272
        value = bzrdir_config.get_option('key3')
1273
        self.assertEqual(value, 'value3-top')
1274
        value = bzrdir_config.get_option('key3', 'SECTION')
1275
        self.assertEqual(value, 'value3-section')
1276
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1277
    def test_set_unset_default_stack_on(self):
1278
        my_dir = self.make_bzrdir('.')
4288.1.3 by Robert Collins
Fix BzrDirConfig tests.
1279
        bzrdir_config = config.BzrDirConfig(my_dir)
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1280
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1281
        bzrdir_config.set_default_stack_on('Foo')
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1282
        self.assertEqual('Foo', bzrdir_config._config.get_option(
1283
                         'default_stack_on'))
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1284
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
1285
        bzrdir_config.set_default_stack_on(None)
1286
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1287
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1288
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1289
class TestAuthenticationConfigFile(tests.TestCase):
2900.2.14 by Vincent Ladeuil
More tests.
1290
    """Test the authentication.conf file matching"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1291
1292
    def _got_user_passwd(self, expected_user, expected_password,
1293
                         config, *args, **kwargs):
1294
        credentials = config.get_credentials(*args, **kwargs)
1295
        if credentials is None:
1296
            user = None
1297
            password = None
1298
        else:
1299
            user = credentials['user']
1300
            password = credentials['password']
1301
        self.assertEquals(expected_user, user)
1302
        self.assertEquals(expected_password, password)
1303
2978.5.1 by John Arbash Meinel
Fix bug #162494, 'bzr register-branch' needs proper auth handling.
1304
    def test_empty_config(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1305
        conf = config.AuthenticationConfig(_file=StringIO())
1306
        self.assertEquals({}, conf._get_config())
1307
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1308
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1309
    def test_missing_auth_section_header(self):
1310
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
1311
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1312
1313
    def test_auth_section_header_not_closed(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1314
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
1315
        self.assertRaises(errors.ParseConfigError, conf._get_config)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1316
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1317
    def test_auth_value_not_boolean(self):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1318
        conf = config.AuthenticationConfig(_file=StringIO(
1319
                """[broken]
1320
scheme=ftp
1321
user=joe
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1322
verify_certificates=askme # Error: Not a boolean
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1323
"""))
1324
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1325
1326
    def test_auth_value_not_int(self):
2900.2.22 by Vincent Ladeuil
Polishing.
1327
        conf = config.AuthenticationConfig(_file=StringIO(
1328
                """[broken]
1329
scheme=ftp
1330
user=joe
1331
port=port # Error: Not an int
1332
"""))
1333
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1334
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1335
    def test_unknown_password_encoding(self):
1336
        conf = config.AuthenticationConfig(_file=StringIO(
1337
                """[broken]
1338
scheme=ftp
1339
user=joe
1340
password_encoding=unknown
1341
"""))
1342
        self.assertRaises(ValueError, conf.get_password,
1343
                          'ftp', 'foo.net', 'joe')
1344
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1345
    def test_credentials_for_scheme_host(self):
1346
        conf = config.AuthenticationConfig(_file=StringIO(
1347
                """# Identity on foo.net
1348
[ftp definition]
1349
scheme=ftp
1350
host=foo.net
1351
user=joe
1352
password=secret-pass
1353
"""))
1354
        # Basic matching
1355
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
1356
        # different scheme
1357
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1358
        # different host
1359
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
1360
1361
    def test_credentials_for_host_port(self):
1362
        conf = config.AuthenticationConfig(_file=StringIO(
1363
                """# Identity on foo.net
1364
[ftp definition]
1365
scheme=ftp
1366
port=10021
1367
host=foo.net
1368
user=joe
1369
password=secret-pass
1370
"""))
1371
        # No port
1372
        self._got_user_passwd('joe', 'secret-pass',
1373
                              conf, 'ftp', 'foo.net', port=10021)
1374
        # different port
1375
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
1376
1377
    def test_for_matching_host(self):
1378
        conf = config.AuthenticationConfig(_file=StringIO(
1379
                """# Identity on foo.net
1380
[sourceforge]
1381
scheme=bzr
1382
host=bzr.sf.net
1383
user=joe
1384
password=joepass
1385
[sourceforge domain]
1386
scheme=bzr
1387
host=.bzr.sf.net
1388
user=georges
1389
password=bendover
1390
"""))
1391
        # matching domain
1392
        self._got_user_passwd('georges', 'bendover',
1393
                              conf, 'bzr', 'foo.bzr.sf.net')
1394
        # phishing attempt
1395
        self._got_user_passwd(None, None,
1396
                              conf, 'bzr', 'bbzr.sf.net')
1397
1398
    def test_for_matching_host_None(self):
1399
        conf = config.AuthenticationConfig(_file=StringIO(
1400
                """# Identity on foo.net
1401
[catchup bzr]
1402
scheme=bzr
1403
user=joe
1404
password=joepass
1405
[DEFAULT]
1406
user=georges
1407
password=bendover
1408
"""))
1409
        # match no host
1410
        self._got_user_passwd('joe', 'joepass',
1411
                              conf, 'bzr', 'quux.net')
1412
        # no host but different scheme
1413
        self._got_user_passwd('georges', 'bendover',
1414
                              conf, 'ftp', 'quux.net')
1415
1416
    def test_credentials_for_path(self):
1417
        conf = config.AuthenticationConfig(_file=StringIO(
1418
                """
1419
[http dir1]
1420
scheme=http
1421
host=bar.org
1422
path=/dir1
1423
user=jim
1424
password=jimpass
1425
[http dir2]
1426
scheme=http
1427
host=bar.org
1428
path=/dir2
1429
user=georges
1430
password=bendover
1431
"""))
1432
        # no path no dice
1433
        self._got_user_passwd(None, None,
1434
                              conf, 'http', host='bar.org', path='/dir3')
1435
        # matching path
1436
        self._got_user_passwd('georges', 'bendover',
1437
                              conf, 'http', host='bar.org', path='/dir2')
1438
        # matching subdir
1439
        self._got_user_passwd('jim', 'jimpass',
1440
                              conf, 'http', host='bar.org',path='/dir1/subdir')
1441
1442
    def test_credentials_for_user(self):
1443
        conf = config.AuthenticationConfig(_file=StringIO(
1444
                """
1445
[with user]
1446
scheme=http
1447
host=bar.org
1448
user=jim
1449
password=jimpass
1450
"""))
1451
        # Get user
1452
        self._got_user_passwd('jim', 'jimpass',
1453
                              conf, 'http', 'bar.org')
1454
        # Get same user
1455
        self._got_user_passwd('jim', 'jimpass',
1456
                              conf, 'http', 'bar.org', user='jim')
1457
        # Don't get a different user if one is specified
1458
        self._got_user_passwd(None, None,
1459
                              conf, 'http', 'bar.org', user='georges')
1460
3418.4.1 by Vincent Ladeuil
Reproduce bug 199440.
1461
    def test_credentials_for_user_without_password(self):
1462
        conf = config.AuthenticationConfig(_file=StringIO(
1463
                """
1464
[without password]
1465
scheme=http
1466
host=bar.org
1467
user=jim
1468
"""))
1469
        # Get user but no password
1470
        self._got_user_passwd('jim', None,
1471
                              conf, 'http', 'bar.org')
1472
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1473
    def test_verify_certificates(self):
1474
        conf = config.AuthenticationConfig(_file=StringIO(
1475
                """
1476
[self-signed]
1477
scheme=https
1478
host=bar.org
1479
user=jim
1480
password=jimpass
1481
verify_certificates=False
1482
[normal]
1483
scheme=https
1484
host=foo.net
1485
user=georges
1486
password=bendover
1487
"""))
1488
        credentials = conf.get_credentials('https', 'bar.org')
1489
        self.assertEquals(False, credentials.get('verify_certificates'))
1490
        credentials = conf.get_credentials('https', 'foo.net')
1491
        self.assertEquals(True, credentials.get('verify_certificates'))
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1492
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1493
1494
class TestAuthenticationStorage(tests.TestCaseInTempDir):
1495
3777.1.8 by Aaron Bentley
Commit work-in-progress
1496
    def test_set_credentials(self):
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1497
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1498
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1499
        99, path='/foo', verify_certificates=False, realm='realm')
3777.1.8 by Aaron Bentley
Commit work-in-progress
1500
        credentials = conf.get_credentials(host='host', scheme='scheme',
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1501
                                           port=99, path='/foo',
1502
                                           realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1503
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
1504
                       'verify_certificates': False, 'scheme': 'scheme', 
1505
                       'host': 'host', 'port': 99, 'path': '/foo', 
1506
                       'realm': 'realm'}
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1507
        self.assertEqual(CREDENTIALS, credentials)
1508
        credentials_from_disk = config.AuthenticationConfig().get_credentials(
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1509
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1510
        self.assertEqual(CREDENTIALS, credentials_from_disk)
3777.1.8 by Aaron Bentley
Commit work-in-progress
1511
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1512
    def test_reset_credentials_different_name(self):
1513
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1514
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
1515
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1516
        self.assertIs(None, conf._get_config().get('name'))
1517
        credentials = conf.get_credentials(host='host', scheme='scheme')
1518
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
1519
                       'password', 'verify_certificates': True, 
1520
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
1521
                       'path': None, 'realm': None}
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1522
        self.assertEqual(CREDENTIALS, credentials)
1523
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1524
2900.2.14 by Vincent Ladeuil
More tests.
1525
class TestAuthenticationConfig(tests.TestCase):
1526
    """Test AuthenticationConfig behaviour"""
1527
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1528
    def _check_default_password_prompt(self, expected_prompt_format, scheme,
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1529
                                       host=None, port=None, realm=None,
1530
                                       path=None):
2900.2.14 by Vincent Ladeuil
More tests.
1531
        if host is None:
1532
            host = 'bar.org'
1533
        user, password = 'jim', 'precious'
1534
        expected_prompt = expected_prompt_format % {
1535
            'scheme': scheme, 'host': host, 'port': port,
1536
            'user': user, 'realm': realm}
1537
1538
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1539
        stderr = tests.StringIOWrapper()
2900.2.14 by Vincent Ladeuil
More tests.
1540
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1541
                                            stdout=stdout, stderr=stderr)
2900.2.14 by Vincent Ladeuil
More tests.
1542
        # We use an empty conf so that the user is always prompted
1543
        conf = config.AuthenticationConfig()
1544
        self.assertEquals(password,
1545
                          conf.get_password(scheme, host, user, port=port,
1546
                                            realm=realm, path=path))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1547
        self.assertEquals(expected_prompt, stderr.getvalue())
1548
        self.assertEquals('', stdout.getvalue())
2900.2.14 by Vincent Ladeuil
More tests.
1549
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1550
    def _check_default_username_prompt(self, expected_prompt_format, scheme,
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1551
                                       host=None, port=None, realm=None,
1552
                                       path=None):
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1553
        if host is None:
1554
            host = 'bar.org'
1555
        username = 'jim'
1556
        expected_prompt = expected_prompt_format % {
1557
            'scheme': scheme, 'host': host, 'port': port,
1558
            'realm': realm}
1559
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1560
        stderr = tests.StringIOWrapper()
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1561
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1562
                                            stdout=stdout, stderr=stderr)
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1563
        # We use an empty conf so that the user is always prompted
1564
        conf = config.AuthenticationConfig()
4222.3.5 by Jelmer Vernooij
Fix test.
1565
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
1566
                          realm=realm, path=path, ask=True))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1567
        self.assertEquals(expected_prompt, stderr.getvalue())
1568
        self.assertEquals('', stdout.getvalue())
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1569
1570
    def test_username_defaults_prompts(self):
1571
        # HTTP prompts can't be tested here, see test_http.py
1572
        self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
1573
        self._check_default_username_prompt(
1574
            'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
1575
        self._check_default_username_prompt(
1576
            'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
1577
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
1578
    def test_username_default_no_prompt(self):
1579
        conf = config.AuthenticationConfig()
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1580
        self.assertEquals(None,
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
1581
            conf.get_user('ftp', 'example.com'))
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1582
        self.assertEquals("explicitdefault",
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
1583
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
1584
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1585
    def test_password_default_prompts(self):
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
1586
        # HTTP prompts can't be tested here, see test_http.py
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1587
        self._check_default_password_prompt(
1588
            'FTP %(user)s@%(host)s password: ', 'ftp')
1589
        self._check_default_password_prompt(
1590
            'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
1591
        self._check_default_password_prompt(
1592
            'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
2900.2.14 by Vincent Ladeuil
More tests.
1593
        # SMTP port handling is a bit special (it's handled if embedded in the
1594
        # host too)
2900.2.22 by Vincent Ladeuil
Polishing.
1595
        # FIXME: should we: forbid that, extend it to other schemes, leave
1596
        # things as they are that's fine thank you ?
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1597
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1598
                                            'smtp')
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1599
        self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1600
                                            'smtp', host='bar.org:10025')
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1601
        self._check_default_password_prompt(
2900.2.14 by Vincent Ladeuil
More tests.
1602
            'SMTP %(user)s@%(host)s:%(port)d password: ',
1603
            'smtp', port=10025)
1604
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
1605
    def test_ssh_password_emits_warning(self):
1606
        conf = config.AuthenticationConfig(_file=StringIO(
1607
                """
1608
[ssh with password]
1609
scheme=ssh
1610
host=bar.org
1611
user=jim
1612
password=jimpass
1613
"""))
1614
        entered_password = 'typed-by-hand'
1615
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
1616
        stderr = tests.StringIOWrapper()
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
1617
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
1618
                                            stdout=stdout, stderr=stderr)
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
1619
1620
        # Since the password defined in the authentication config is ignored,
1621
        # the user is prompted
1622
        self.assertEquals(entered_password,
1623
                          conf.get_password('ssh', 'bar.org', user='jim'))
1624
        self.assertContainsRe(
4794.1.17 by Robert Collins
Fix from vila for type log_log.
1625
            self.get_log(),
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
1626
            'password ignored in section \[ssh with password\]')
1627
3420.1.3 by Vincent Ladeuil
John's review feedback.
1628
    def test_ssh_without_password_doesnt_emit_warning(self):
1629
        conf = config.AuthenticationConfig(_file=StringIO(
1630
                """
1631
[ssh with password]
1632
scheme=ssh
1633
host=bar.org
1634
user=jim
1635
"""))
1636
        entered_password = 'typed-by-hand'
1637
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
1638
        stderr = tests.StringIOWrapper()
3420.1.3 by Vincent Ladeuil
John's review feedback.
1639
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
1640
                                            stdout=stdout,
1641
                                            stderr=stderr)
3420.1.3 by Vincent Ladeuil
John's review feedback.
1642
1643
        # Since the password defined in the authentication config is ignored,
1644
        # the user is prompted
1645
        self.assertEquals(entered_password,
1646
                          conf.get_password('ssh', 'bar.org', user='jim'))
3420.1.4 by Vincent Ladeuil
Fix comment.
1647
        # No warning shoud be emitted since there is no password. We are only
1648
        # providing "user".
3420.1.3 by Vincent Ladeuil
John's review feedback.
1649
        self.assertNotContainsRe(
4794.1.15 by Robert Collins
Review feedback.
1650
            self.get_log(),
3420.1.3 by Vincent Ladeuil
John's review feedback.
1651
            'password ignored in section \[ssh with password\]')
1652
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
1653
    def test_uses_fallback_stores(self):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1654
        self.overrideAttr(config, 'credential_store_registry',
1655
                          config.CredentialStoreRegistry())
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
1656
        store = StubCredentialStore()
1657
        store.add_credentials("http", "example.com", "joe", "secret")
1658
        config.credential_store_registry.register("stub", store, fallback=True)
1659
        conf = config.AuthenticationConfig(_file=StringIO())
1660
        creds = conf.get_credentials("http", "example.com")
1661
        self.assertEquals("joe", creds["user"])
1662
        self.assertEquals("secret", creds["password"])
1663
2900.2.14 by Vincent Ladeuil
More tests.
1664
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1665
class StubCredentialStore(config.CredentialStore):
1666
1667
    def __init__(self):
1668
        self._username = {}
1669
        self._password = {}
1670
1671
    def add_credentials(self, scheme, host, user, password=None):
1672
        self._username[(scheme, host)] = user
1673
        self._password[(scheme, host)] = password
1674
1675
    def get_credentials(self, scheme, host, port=None, user=None,
1676
        path=None, realm=None):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1677
        key = (scheme, host)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1678
        if not key in self._username:
1679
            return None
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1680
        return { "scheme": scheme, "host": host, "port": port,
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1681
                "user": self._username[key], "password": self._password[key]}
1682
1683
1684
class CountingCredentialStore(config.CredentialStore):
1685
1686
    def __init__(self):
1687
        self._calls = 0
1688
1689
    def get_credentials(self, scheme, host, port=None, user=None,
1690
        path=None, realm=None):
1691
        self._calls += 1
1692
        return None
1693
1694
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1695
class TestCredentialStoreRegistry(tests.TestCase):
1696
1697
    def _get_cs_registry(self):
1698
        return config.credential_store_registry
1699
1700
    def test_default_credential_store(self):
1701
        r = self._get_cs_registry()
1702
        default = r.get_credential_store(None)
1703
        self.assertIsInstance(default, config.PlainTextCredentialStore)
1704
1705
    def test_unknown_credential_store(self):
1706
        r = self._get_cs_registry()
1707
        # It's hard to imagine someone creating a credential store named
1708
        # 'unknown' so we use that as an never registered key.
1709
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
1710
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1711
    def test_fallback_none_registered(self):
1712
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1713
        self.assertEquals(None,
1714
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1715
1716
    def test_register(self):
1717
        r = config.CredentialStoreRegistry()
1718
        r.register("stub", StubCredentialStore(), fallback=False)
1719
        r.register("another", StubCredentialStore(), fallback=True)
1720
        self.assertEquals(["another", "stub"], r.keys())
1721
1722
    def test_register_lazy(self):
1723
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1724
        r.register_lazy("stub", "bzrlib.tests.test_config",
1725
                        "StubCredentialStore", fallback=False)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1726
        self.assertEquals(["stub"], r.keys())
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1727
        self.assertIsInstance(r.get_credential_store("stub"),
1728
                              StubCredentialStore)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1729
1730
    def test_is_fallback(self):
1731
        r = config.CredentialStoreRegistry()
1732
        r.register("stub1", None, fallback=False)
1733
        r.register("stub2", None, fallback=True)
1734
        self.assertEquals(False, r.is_fallback("stub1"))
1735
        self.assertEquals(True, r.is_fallback("stub2"))
1736
1737
    def test_no_fallback(self):
1738
        r = config.CredentialStoreRegistry()
1739
        store = CountingCredentialStore()
1740
        r.register("count", store, fallback=False)
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1741
        self.assertEquals(None,
1742
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1743
        self.assertEquals(0, store._calls)
1744
1745
    def test_fallback_credentials(self):
1746
        r = config.CredentialStoreRegistry()
1747
        store = StubCredentialStore()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1748
        store.add_credentials("http", "example.com",
1749
                              "somebody", "geheim")
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1750
        r.register("stub", store, fallback=True)
1751
        creds = r.get_fallback_credentials("http", "example.com")
1752
        self.assertEquals("somebody", creds["user"])
1753
        self.assertEquals("geheim", creds["password"])
1754
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1755
    def test_fallback_first_wins(self):
1756
        r = config.CredentialStoreRegistry()
1757
        stub1 = StubCredentialStore()
1758
        stub1.add_credentials("http", "example.com",
1759
                              "somebody", "stub1")
1760
        r.register("stub1", stub1, fallback=True)
1761
        stub2 = StubCredentialStore()
1762
        stub2.add_credentials("http", "example.com",
1763
                              "somebody", "stub2")
1764
        r.register("stub2", stub1, fallback=True)
1765
        creds = r.get_fallback_credentials("http", "example.com")
1766
        self.assertEquals("somebody", creds["user"])
1767
        self.assertEquals("stub1", creds["password"])
1768
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1769
1770
class TestPlainTextCredentialStore(tests.TestCase):
1771
1772
    def test_decode_password(self):
1773
        r = config.credential_store_registry
1774
        plain_text = r.get_credential_store()
1775
        decoded = plain_text.decode_password(dict(password='secret'))
1776
        self.assertEquals('secret', decoded)
1777
1778
2900.2.14 by Vincent Ladeuil
More tests.
1779
# FIXME: Once we have a way to declare authentication to all test servers, we
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1780
# can implement generic tests.
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1781
# test_user_password_in_url
1782
# test_user_in_url_password_from_config
1783
# test_user_in_url_password_prompted
1784
# test_user_in_config
1785
# test_user_getpass.getuser
1786
# test_user_prompted ?
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1787
class TestAuthenticationRing(tests.TestCaseWithTransport):
1788
    pass