~bzr-pqm/bzr/bzr.dev

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