/brz/remove-bazaar

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