/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
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1019
    def test__get_options_with_policy(self):
1020
        self.get_branch_config('/dir/subdir',
1021
                               location_config="""\
1022
[/dir]
1023
other_url = /other-dir
1024
other_url:policy = appendpath
1025
[/dir/subdir]
1026
other_url = /other-subdir
1027
""")
1028
        self.assertEqual(
1029
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
1030
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
1031
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
1032
            list(self.my_location_config._get_options()))
1033
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1034
    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
1035
        self.get_branch_config('http://www.example.com/ignoreparent')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1036
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1037
                         self.my_config.username())
1038
1039
    def test_location_not_listed(self):
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1040
        """Test that the global username is used when no location matches"""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1041
        self.get_branch_config('/home/robertc/sources')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1042
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1043
                         self.my_config.username())
1044
1442.1.13 by Robert Collins
branches.conf is now able to override the users email
1045
    def test_overriding_location(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1046
        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
1047
        self.assertEqual('Robert Collins <robertc@example.org>',
1048
                         self.my_config.username())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1049
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1050
    def test_signatures_not_set(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1051
        self.get_branch_config('http://www.example.com',
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1052
                                 global_config=sample_ignore_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1053
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1054
                         self.my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1055
        self.assertEqual(config.SIGN_NEVER,
1056
                         self.my_config.signing_policy())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1057
1058
    def test_signatures_never(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1059
        self.get_branch_config('/a/c')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1060
        self.assertEqual(config.CHECK_NEVER,
1061
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1062
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1063
    def test_signatures_when_available(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1064
        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
1065
        self.assertEqual(config.CHECK_IF_POSSIBLE,
1066
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1067
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1068
    def test_signatures_always(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1069
        self.get_branch_config('/b')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1070
        self.assertEqual(config.CHECK_ALWAYS,
1071
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1072
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1073
    def test_gpg_signing_command(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1074
        self.get_branch_config('/b')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1075
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
1076
1077
    def test_gpg_signing_command_missing(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1078
        self.get_branch_config('/a')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1079
        self.assertEqual("false", self.my_config.gpg_signing_command())
1080
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1081
    def test_get_user_option_global(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1082
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1083
        self.assertEqual('something',
1084
                         self.my_config.get_user_option('user_global_option'))
1085
1086
    def test_get_user_option_local(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1087
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1088
        self.assertEqual('local',
1089
                         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
1090
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
1091
    def test_get_user_option_appendpath(self):
1092
        # returned as is for the base path:
1093
        self.get_branch_config('http://www.example.com')
1094
        self.assertEqual('append',
1095
                         self.my_config.get_user_option('appendpath_option'))
1096
        # Extra path components get appended:
1097
        self.get_branch_config('http://www.example.com/a/b/c')
1098
        self.assertEqual('append/a/b/c',
1099
                         self.my_config.get_user_option('appendpath_option'))
1100
        # Overriden for http://www.example.com/dir, where it is a
1101
        # normal option:
1102
        self.get_branch_config('http://www.example.com/dir/a/b/c')
1103
        self.assertEqual('normal',
1104
                         self.my_config.get_user_option('appendpath_option'))
1105
1106
    def test_get_user_option_norecurse(self):
1107
        self.get_branch_config('http://www.example.com')
1108
        self.assertEqual('norecurse',
1109
                         self.my_config.get_user_option('norecurse_option'))
1110
        self.get_branch_config('http://www.example.com/dir')
1111
        self.assertEqual(None,
1112
                         self.my_config.get_user_option('norecurse_option'))
1113
        # http://www.example.com/norecurse is a recurse=False section
1114
        # that redefines normal_option.  Subdirectories do not pick up
1115
        # this redefinition.
1116
        self.get_branch_config('http://www.example.com/norecurse')
1117
        self.assertEqual('norecurse',
1118
                         self.my_config.get_user_option('normal_option'))
1119
        self.get_branch_config('http://www.example.com/norecurse/subdir')
1120
        self.assertEqual('normal',
1121
                         self.my_config.get_user_option('normal_option'))
1122
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1123
    def test_set_user_option_norecurse(self):
1124
        self.get_branch_config('http://www.example.com')
1125
        self.my_config.set_user_option('foo', 'bar',
1126
                                       store=config.STORE_LOCATION_NORECURSE)
1127
        self.assertEqual(
1128
            self.my_location_config._get_option_policy(
1129
            'http://www.example.com', 'foo'),
1130
            config.POLICY_NORECURSE)
1131
1132
    def test_set_user_option_appendpath(self):
1133
        self.get_branch_config('http://www.example.com')
1134
        self.my_config.set_user_option('foo', 'bar',
1135
                                       store=config.STORE_LOCATION_APPENDPATH)
1136
        self.assertEqual(
1137
            self.my_location_config._get_option_policy(
1138
            'http://www.example.com', 'foo'),
1139
            config.POLICY_APPENDPATH)
1140
1141
    def test_set_user_option_change_policy(self):
1142
        self.get_branch_config('http://www.example.com')
1143
        self.my_config.set_user_option('norecurse_option', 'normal',
1144
                                       store=config.STORE_LOCATION)
1145
        self.assertEqual(
1146
            self.my_location_config._get_option_policy(
1147
            'http://www.example.com', 'norecurse_option'),
1148
            config.POLICY_NONE)
1149
1150
    def test_set_user_option_recurse_false_section(self):
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1151
        # The following section has recurse=False set.  The test is to
1152
        # make sure that a normal option can be added to the section,
1153
        # converting recurse=False to the norecurse policy.
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1154
        self.get_branch_config('http://www.example.com/norecurse')
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
1155
        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
1156
                             'The section "http://www.example.com/norecurse" '
1157
                             'has been converted to use policies.'],
1158
                            self.my_config.set_user_option,
1159
                            'foo', 'bar', store=config.STORE_LOCATION)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1160
        self.assertEqual(
1161
            self.my_location_config._get_option_policy(
1162
            'http://www.example.com/norecurse', 'foo'),
1163
            config.POLICY_NONE)
1164
        # The previously existing option is still norecurse:
1165
        self.assertEqual(
1166
            self.my_location_config._get_option_policy(
1167
            'http://www.example.com/norecurse', 'normal_option'),
1168
            config.POLICY_NORECURSE)
1169
1472 by Robert Collins
post commit hook, first pass implementation
1170
    def test_post_commit_default(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1171
        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
1172
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1173
                         self.my_config.post_commit())
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1174
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1175
    def get_branch_config(self, location, global_config=None,
1176
                          location_config=None):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1177
        my_branch = FakeBranch(location)
1502 by Robert Collins
Bugfix the config test suite to not create .bazaar in the dir where it is run.
1178
        if global_config is None:
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1179
            global_config = sample_config_text
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1180
        if location_config is None:
1181
            location_config = sample_branches_text
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1182
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1183
        my_global_config = config.GlobalConfig.from_string(global_config,
1184
                                                           save=True)
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1185
        my_location_config = config.LocationConfig.from_string(
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1186
            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.
1187
        my_config = config.BranchConfig(my_branch)
1188
        self.my_config = my_config
1189
        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.
1190
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1191
    def test_set_user_setting_sets_and_saves(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1192
        self.get_branch_config('/a/c')
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1193
        record = InstrumentedConfigObj("foo")
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1194
        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
1195
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1196
        self.callDeprecated(['The recurse option is deprecated as of '
1197
                             '0.14.  The section "/a/c" has been '
1198
                             'converted to use policies.'],
1199
                            self.my_config.set_user_option,
1200
                            'foo', 'bar', store=config.STORE_LOCATION)
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
1201
        self.assertEqual([('reload',),
1202
                          ('__contains__', '/a/c'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1203
                          ('__contains__', '/a/c/'),
1204
                          ('__setitem__', '/a/c', {}),
1205
                          ('__getitem__', '/a/c'),
1206
                          ('__setitem__', 'foo', 'bar'),
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1207
                          ('__getitem__', '/a/c'),
1208
                          ('as_bool', 'recurse'),
1209
                          ('__getitem__', '/a/c'),
1210
                          ('__delitem__', 'recurse'),
1211
                          ('__getitem__', '/a/c'),
1212
                          ('keys',),
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1213
                          ('__getitem__', '/a/c'),
1214
                          ('__contains__', 'foo:policy'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1215
                          ('write',)],
1216
                         record._calls[1:])
1217
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1218
    def test_set_user_setting_sets_and_saves2(self):
1219
        self.get_branch_config('/a/c')
1220
        self.assertIs(self.my_config.get_user_option('foo'), None)
1221
        self.my_config.set_user_option('foo', 'bar')
1222
        self.assertEqual(
3616.2.6 by Mark Hammond
Fix test_set_user_setting_sets_and_saves2 on windows by stripping EOL
1223
            self.my_config.branch.control_files.files['branch.conf'].strip(),
1224
            'foo = bar')
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1225
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1226
        self.my_config.set_user_option('foo', 'baz',
1227
                                       store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1228
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1229
        self.my_config.set_user_option('foo', 'qux')
1230
        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.
1231
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1232
    def test_get_bzr_remote_path(self):
1233
        my_config = config.LocationConfig('/a/c')
1234
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1235
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1236
        self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
1237
        os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
1238
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1239
1185.62.7 by John Arbash Meinel
Whitespace cleanup.
1240
1770.2.8 by Aaron Bentley
Add precedence test
1241
precedence_global = 'option = global'
1242
precedence_branch = 'option = branch'
1243
precedence_location = """
1244
[http://]
1245
recurse = true
1246
option = recurse
1247
[http://example.com/specific]
1248
option = exact
1249
"""
1250
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1251
class TestBranchConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1252
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1253
    def get_branch_config(self, global_config=None, location=None,
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1254
                          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.
1255
        my_branch = FakeBranch(location)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1256
        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
1257
            my_global_config = config.GlobalConfig.from_string(global_config,
1258
                                                               save=True)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1259
        if location_config is not None:
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1260
            my_location_config = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1261
                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.
1262
        my_config = config.BranchConfig(my_branch)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1263
        if branch_data_config is not None:
1264
            my_config.branch.control_files.files['branch.conf'] = \
1265
                branch_data_config
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1266
        return my_config
1267
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1268
    def test_user_id(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1269
        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
1270
        my_config = config.BranchConfig(branch)
1271
        self.assertEqual("Robert Collins <robertc@example.net>",
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1272
                         my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1273
        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.
1274
        my_config.set_user_option('email',
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1275
                                  "Robert Collins <robertc@example.org>")
1276
        self.assertEqual("John", my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1277
        del my_config.branch.control_files.files['email']
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1278
        self.assertEqual("Robert Collins <robertc@example.org>",
1279
                         my_config.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1280
1281
    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.
1282
        my_config = self.get_branch_config(global_config=sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
1283
        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
1284
                         my_config._get_user_id())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1285
        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
1286
        self.assertEqual("John", my_config._get_user_id())
1287
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
1288
    def test_BZR_EMAIL_OVERRIDES(self):
1289
        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
1290
        branch = FakeBranch()
1291
        my_config = config.BranchConfig(branch)
1292
        self.assertEqual("Robert Collins <robertc@example.org>",
1293
                         my_config.username())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1294
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1295
    def test_signatures_forced(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1296
        my_config = self.get_branch_config(
1297
            global_config=sample_always_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1298
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1299
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1300
        self.assertTrue(my_config.signature_needed())
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1301
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1302
    def test_signatures_forced_branch(self):
1303
        my_config = self.get_branch_config(
1304
            global_config=sample_ignore_signatures,
1305
            branch_data_config=sample_always_signatures)
1306
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1307
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1308
        self.assertTrue(my_config.signature_needed())
1309
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1310
    def test_gpg_signing_command(self):
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1311
        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.
1312
            global_config=sample_config_text,
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1313
            # branch data cannot set gpg_signing_command
1314
            branch_data_config="gpg_signing_command=pgp")
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1315
        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.
1316
1317
    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.
1318
        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.
1319
        self.assertEqual('something',
1320
                         my_config.get_user_option('user_global_option'))
1472 by Robert Collins
post commit hook, first pass implementation
1321
1322
    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.
1323
        my_config = self.get_branch_config(global_config=sample_config_text,
1324
                                      location='/a/c',
1325
                                      location_config=sample_branches_text)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1326
        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
1327
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1328
                         my_config.post_commit())
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1329
        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.
1330
        # post-commit is ignored when present in branch data
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1331
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1332
                         my_config.post_commit())
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1333
        my_config.set_user_option('post_commit', 'rmtree_root',
1334
                                  store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1335
        self.assertEqual('rmtree_root', my_config.post_commit())
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1336
1770.2.8 by Aaron Bentley
Add precedence test
1337
    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.
1338
        # FIXME: eager test, luckily no persitent config file makes it fail
1339
        # -- vila 20100716
1770.2.8 by Aaron Bentley
Add precedence test
1340
        my_config = self.get_branch_config(global_config=precedence_global)
1341
        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.
1342
        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.
1343
                                           branch_data_config=precedence_branch)
1770.2.8 by Aaron Bentley
Add precedence test
1344
        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.
1345
        my_config = self.get_branch_config(
1346
            global_config=precedence_global,
1347
            branch_data_config=precedence_branch,
1348
            location_config=precedence_location)
1770.2.8 by Aaron Bentley
Add precedence test
1349
        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.
1350
        my_config = self.get_branch_config(
1351
            global_config=precedence_global,
1352
            branch_data_config=precedence_branch,
1353
            location_config=precedence_location,
1354
            location='http://example.com/specific')
1770.2.8 by Aaron Bentley
Add precedence test
1355
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1356
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
1357
    def test_get_mail_client(self):
1358
        config = self.get_branch_config()
1359
        client = config.get_mail_client()
2681.1.24 by Aaron Bentley
Handle default mail client by trying xdg-email, falling back to editor
1360
        self.assertIsInstance(client, mail_client.DefaultMail)
1361
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1362
        # Specific clients
2681.1.21 by Aaron Bentley
Refactor prompt generation to make it testable, test it with unicode
1363
        config.set_user_option('mail_client', 'evolution')
1364
        client = config.get_mail_client()
1365
        self.assertIsInstance(client, mail_client.Evolution)
1366
2681.5.1 by ghigo
Add KMail support to bzr send
1367
        config.set_user_option('mail_client', 'kmail')
1368
        client = config.get_mail_client()
1369
        self.assertIsInstance(client, mail_client.KMail)
1370
2790.2.1 by Keir Mierle
Add Mutt as a supported client email program. Also rearranges various listings
1371
        config.set_user_option('mail_client', 'mutt')
1372
        client = config.get_mail_client()
1373
        self.assertIsInstance(client, mail_client.Mutt)
1374
1375
        config.set_user_option('mail_client', 'thunderbird')
1376
        client = config.get_mail_client()
1377
        self.assertIsInstance(client, mail_client.Thunderbird)
1378
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1379
        # Generic options
1380
        config.set_user_option('mail_client', 'default')
1381
        client = config.get_mail_client()
1382
        self.assertIsInstance(client, mail_client.DefaultMail)
1383
1384
        config.set_user_option('mail_client', 'editor')
1385
        client = config.get_mail_client()
1386
        self.assertIsInstance(client, mail_client.Editor)
1387
1388
        config.set_user_option('mail_client', 'mapi')
1389
        client = config.get_mail_client()
1390
        self.assertIsInstance(client, mail_client.MAPIClient)
1391
2681.1.23 by Aaron Bentley
Add support for xdg-email
1392
        config.set_user_option('mail_client', 'xdg-email')
1393
        client = config.get_mail_client()
1394
        self.assertIsInstance(client, mail_client.XDGEmail)
1395
2681.1.10 by Aaron Bentley
Clean up handling of unknown mail clients
1396
        config.set_user_option('mail_client', 'firebird')
1397
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1398
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1399
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1400
class TestMailAddressExtraction(tests.TestCase):
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1401
1402
    def test_extract_email_address(self):
1403
        self.assertEqual('jane@test.com',
1404
                         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
1405
        self.assertRaises(errors.NoEmailInUsername,
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1406
                          config.extract_email_address, 'Jane Tester')
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1407
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1408
    def test_parse_username(self):
1409
        self.assertEqual(('', 'jdoe@example.com'),
1410
                         config.parse_username('jdoe@example.com'))
1411
        self.assertEqual(('', 'jdoe@example.com'),
1412
                         config.parse_username('<jdoe@example.com>'))
1413
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1414
                         config.parse_username('John Doe <jdoe@example.com>'))
1415
        self.assertEqual(('John Doe', ''),
1416
                         config.parse_username('John Doe'))
3063.3.3 by Lukáš Lalinský
Add one more test for config.parse_username().
1417
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1418
                         config.parse_username('John Doe jdoe@example.com'))
2562.1.2 by John Arbash Meinel
Clean up whitespace
1419
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1420
class TestTreeConfig(tests.TestCaseWithTransport):
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1421
1422
    def test_get_value(self):
1423
        """Test that retreiving a value from a section is possible"""
1424
        branch = self.make_branch('.')
1425
        tree_config = config.TreeConfig(branch)
1426
        tree_config.set_option('value', 'key', 'SECTION')
1427
        tree_config.set_option('value2', 'key2')
1428
        tree_config.set_option('value3-top', 'key3')
1429
        tree_config.set_option('value3-section', 'key3', 'SECTION')
1430
        value = tree_config.get_option('key', 'SECTION')
1431
        self.assertEqual(value, 'value')
1432
        value = tree_config.get_option('key2')
1433
        self.assertEqual(value, 'value2')
1434
        self.assertEqual(tree_config.get_option('non-existant'), None)
1435
        value = tree_config.get_option('non-existant', 'SECTION')
1436
        self.assertEqual(value, None)
1437
        value = tree_config.get_option('non-existant', default='default')
1438
        self.assertEqual(value, 'default')
1439
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1440
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
1441
        self.assertEqual(value, 'default')
1442
        value = tree_config.get_option('key3')
1443
        self.assertEqual(value, 'value3-top')
1444
        value = tree_config.get_option('key3', 'SECTION')
1445
        self.assertEqual(value, 'value3-section')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1446
1447
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1448
class TestTransportConfig(tests.TestCaseWithTransport):
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1449
1450
    def test_get_value(self):
1451
        """Test that retreiving a value from a section is possible"""
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1452
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1453
                                               'control.conf')
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1454
        bzrdir_config.set_option('value', 'key', 'SECTION')
1455
        bzrdir_config.set_option('value2', 'key2')
1456
        bzrdir_config.set_option('value3-top', 'key3')
1457
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1458
        value = bzrdir_config.get_option('key', 'SECTION')
1459
        self.assertEqual(value, 'value')
1460
        value = bzrdir_config.get_option('key2')
1461
        self.assertEqual(value, 'value2')
1462
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1463
        value = bzrdir_config.get_option('non-existant', 'SECTION')
1464
        self.assertEqual(value, None)
1465
        value = bzrdir_config.get_option('non-existant', default='default')
1466
        self.assertEqual(value, 'default')
1467
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1468
        value = bzrdir_config.get_option('key2', 'NOSECTION',
1469
                                         default='default')
1470
        self.assertEqual(value, 'default')
1471
        value = bzrdir_config.get_option('key3')
1472
        self.assertEqual(value, 'value3-top')
1473
        value = bzrdir_config.get_option('key3', 'SECTION')
1474
        self.assertEqual(value, 'value3-section')
1475
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1476
    def test_set_unset_default_stack_on(self):
1477
        my_dir = self.make_bzrdir('.')
4288.1.3 by Robert Collins
Fix BzrDirConfig tests.
1478
        bzrdir_config = config.BzrDirConfig(my_dir)
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1479
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1480
        bzrdir_config.set_default_stack_on('Foo')
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1481
        self.assertEqual('Foo', bzrdir_config._config.get_option(
1482
                         'default_stack_on'))
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1483
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
1484
        bzrdir_config.set_default_stack_on(None)
1485
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1486
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1487
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1488
def create_configs(test):
1489
    """Create configuration files for a given test.
1490
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
1491
    This requires creating a tree (and populate the ``test.tree`` attribute)
1492
    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.
1493
1494
    - branch_config: A BranchConfig for the associated branch.
1495
1496
    - locations_config : A LocationConfig for the associated branch
1497
1498
    - bazaar_config: A GlobalConfig.
1499
1500
    The tree and branch are created in a 'tree' subdirectory so the tests can
1501
    still use the test directory to stay outside of the branch.
1502
    """
1503
    tree = test.make_branch_and_tree('tree')
1504
    test.tree = tree
1505
    test.branch_config = config.BranchConfig(tree.branch)
1506
    test.locations_config = config.LocationConfig(tree.basedir)
1507
    test.bazaar_config = config.GlobalConfig()
1508
1509
1510
def create_configs_with_file_option(test):
1511
    """Create configuration files with a ``file`` option set in each.
1512
1513
    This builds on ``create_configs`` and add one ``file`` option in each
1514
    configuration with a value which allows identifying the configuration file.
1515
    """
1516
    create_configs(test)
1517
    test.bazaar_config.set_user_option('file', 'bazaar')
1518
    test.locations_config.set_user_option('file', 'locations')
1519
    test.branch_config.set_user_option('file', 'branch')
1520
1521
1522
class TestConfigGetOptions(tests.TestCaseWithTransport):
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1523
1524
    def setUp(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1525
        super(TestConfigGetOptions, self).setUp()
1526
        create_configs(self)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1527
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1528
    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.
1529
        actual = list(conf._get_options())
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1530
        self.assertEqual(expected, actual)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1531
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1532
    # One variable in none of the above
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1533
    def test_no_variable(self):
1534
        # 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.
1535
        self.assertOptions([], self.branch_config)
1536
1537
    def test_option_in_bazaar(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1538
        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.
1539
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1540
                           self.bazaar_config)
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1541
1542
    def test_option_in_locations(self):
1543
        self.locations_config.set_user_option('file', 'locations')
1544
        self.assertOptions(
1545
            [('file', 'locations', self.tree.basedir, 'locations')],
1546
            self.locations_config)
1547
1548
    def test_option_in_branch(self):
1549
        self.branch_config.set_user_option('file', 'branch')
1550
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
1551
                           self.branch_config)
1552
1553
    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.
1554
        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.
1555
        self.branch_config.set_user_option('file', 'branch')
1556
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
1557
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1558
                           self.branch_config)
1559
1560
    def test_option_in_branch_and_locations(self):
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1561
        # Hmm, locations override branch :-/
1562
        self.locations_config.set_user_option('file', 'locations')
1563
        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.
1564
        self.assertOptions(
1565
            [('file', 'locations', self.tree.basedir, 'locations'),
1566
             ('file', 'branch', 'DEFAULT', 'branch'),],
1567
            self.branch_config)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1568
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1569
    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.
1570
        self.bazaar_config.set_user_option('file', 'bazaar')
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1571
        self.locations_config.set_user_option('file', 'locations')
1572
        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.
1573
        self.assertOptions(
1574
            [('file', 'locations', self.tree.basedir, 'locations'),
1575
             ('file', 'branch', 'DEFAULT', 'branch'),
1576
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1577
            self.branch_config)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1578
1579
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1580
class TestConfigRemoveOption(tests.TestCaseWithTransport):
1581
1582
    def setUp(self):
1583
        super(TestConfigRemoveOption, self).setUp()
1584
        create_configs_with_file_option(self)
1585
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1586
    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.
1587
        actual = list(conf._get_options())
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1588
        self.assertEqual(expected, actual)
1589
1590
    def test_remove_in_locations(self):
1591
        self.locations_config.remove_user_option('file', self.tree.basedir)
1592
        self.assertOptions(
1593
            [('file', 'branch', 'DEFAULT', 'branch'),
1594
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1595
            self.branch_config)
1596
1597
    def test_remove_in_branch(self):
1598
        self.branch_config.remove_user_option('file')
1599
        self.assertOptions(
1600
            [('file', 'locations', self.tree.basedir, 'locations'),
1601
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
1602
            self.branch_config)
1603
1604
    def test_remove_in_bazaar(self):
1605
        self.bazaar_config.remove_user_option('file')
1606
        self.assertOptions(
1607
            [('file', 'locations', self.tree.basedir, 'locations'),
1608
             ('file', 'branch', 'DEFAULT', 'branch'),],
1609
            self.branch_config)
1610
5447.4.7 by Vincent Ladeuil
Check error message if the test is checking for errors or we have unexpected success for wrong errors.
1611
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1612
class TestConfigGetSections(tests.TestCaseWithTransport):
1613
1614
    def setUp(self):
1615
        super(TestConfigGetSections, self).setUp()
1616
        create_configs(self)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1617
1618
    def assertSectionNames(self, expected, conf, name=None):
1619
        """Check which sections are returned for a given config.
1620
1621
        If fallback configurations exist their sections can be included.
1622
1623
        :param expected: A list of section names.
1624
1625
        :param conf: The configuration that will be queried.
1626
1627
        :param name: An optional section name that will be passed to
1628
            get_sections().
1629
        """
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.
1630
        sections = list(conf._get_sections(name))
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1631
        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.
1632
        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.
1633
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1634
    def test_bazaar_default_section(self):
1635
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1636
1637
    def test_locations_default_section(self):
1638
        # No sections are defined in an empty file
1639
        self.assertSectionNames([], self.locations_config)
1640
1641
    def test_locations_named_section(self):
1642
        self.locations_config.set_user_option('file', 'locations')
1643
        self.assertSectionNames([self.tree.basedir], self.locations_config)
1644
1645
    def test_locations_matching_sections(self):
1646
        loc_config = self.locations_config
1647
        loc_config.set_user_option('file', 'locations')
1648
        # We need to cheat a bit here to create an option in sections above and
1649
        # below the 'location' one.
1650
        parser = loc_config._get_parser()
1651
        # locations.cong deals with '/' ignoring native os.sep
1652
        location_names = self.tree.basedir.split('/')
1653
        parent = '/'.join(location_names[:-1])
1654
        child = '/'.join(location_names + ['child'])
1655
        parser[parent] = {}
1656
        parser[parent]['file'] = 'parent'
1657
        parser[child] = {}
1658
        parser[child]['file'] = 'child'
1659
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
1660
1661
    def test_branch_data_default_section(self):
1662
        self.assertSectionNames([None],
1663
                                self.branch_config._get_branch_data_config())
1664
1665
    def test_branch_default_sections(self):
1666
        # No sections are defined in an empty locations file
1667
        self.assertSectionNames([None, 'DEFAULT'],
1668
                                self.branch_config)
1669
        # Unless we define an option
1670
        self.branch_config._get_location_config().set_user_option(
1671
            'file', 'locations')
1672
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
1673
                                self.branch_config)
1674
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1675
    def test_bazaar_named_section(self):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1676
        # We need to cheat as the API doesn't give direct access to sections
1677
        # other than DEFAULT.
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
1678
        self.bazaar_config.set_alias('bazaar', 'bzr')
1679
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1680
1681
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1682
class TestAuthenticationConfigFile(tests.TestCase):
2900.2.14 by Vincent Ladeuil
More tests.
1683
    """Test the authentication.conf file matching"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1684
1685
    def _got_user_passwd(self, expected_user, expected_password,
1686
                         config, *args, **kwargs):
1687
        credentials = config.get_credentials(*args, **kwargs)
1688
        if credentials is None:
1689
            user = None
1690
            password = None
1691
        else:
1692
            user = credentials['user']
1693
            password = credentials['password']
1694
        self.assertEquals(expected_user, user)
1695
        self.assertEquals(expected_password, password)
1696
2978.5.1 by John Arbash Meinel
Fix bug #162494, 'bzr register-branch' needs proper auth handling.
1697
    def test_empty_config(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1698
        conf = config.AuthenticationConfig(_file=StringIO())
1699
        self.assertEquals({}, conf._get_config())
1700
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1701
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1702
    def test_missing_auth_section_header(self):
1703
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
1704
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
1705
1706
    def test_auth_section_header_not_closed(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1707
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
1708
        self.assertRaises(errors.ParseConfigError, conf._get_config)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1709
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1710
    def test_auth_value_not_boolean(self):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1711
        conf = config.AuthenticationConfig(_file=StringIO(
1712
                """[broken]
1713
scheme=ftp
1714
user=joe
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1715
verify_certificates=askme # Error: Not a boolean
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1716
"""))
1717
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1718
1719
    def test_auth_value_not_int(self):
2900.2.22 by Vincent Ladeuil
Polishing.
1720
        conf = config.AuthenticationConfig(_file=StringIO(
1721
                """[broken]
1722
scheme=ftp
1723
user=joe
1724
port=port # Error: Not an int
1725
"""))
1726
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1727
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1728
    def test_unknown_password_encoding(self):
1729
        conf = config.AuthenticationConfig(_file=StringIO(
1730
                """[broken]
1731
scheme=ftp
1732
user=joe
1733
password_encoding=unknown
1734
"""))
1735
        self.assertRaises(ValueError, conf.get_password,
1736
                          'ftp', 'foo.net', 'joe')
1737
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1738
    def test_credentials_for_scheme_host(self):
1739
        conf = config.AuthenticationConfig(_file=StringIO(
1740
                """# Identity on foo.net
1741
[ftp definition]
1742
scheme=ftp
1743
host=foo.net
1744
user=joe
1745
password=secret-pass
1746
"""))
1747
        # Basic matching
1748
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
1749
        # different scheme
1750
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
1751
        # different host
1752
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
1753
1754
    def test_credentials_for_host_port(self):
1755
        conf = config.AuthenticationConfig(_file=StringIO(
1756
                """# Identity on foo.net
1757
[ftp definition]
1758
scheme=ftp
1759
port=10021
1760
host=foo.net
1761
user=joe
1762
password=secret-pass
1763
"""))
1764
        # No port
1765
        self._got_user_passwd('joe', 'secret-pass',
1766
                              conf, 'ftp', 'foo.net', port=10021)
1767
        # different port
1768
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
1769
1770
    def test_for_matching_host(self):
1771
        conf = config.AuthenticationConfig(_file=StringIO(
1772
                """# Identity on foo.net
1773
[sourceforge]
1774
scheme=bzr
1775
host=bzr.sf.net
1776
user=joe
1777
password=joepass
1778
[sourceforge domain]
1779
scheme=bzr
1780
host=.bzr.sf.net
1781
user=georges
1782
password=bendover
1783
"""))
1784
        # matching domain
1785
        self._got_user_passwd('georges', 'bendover',
1786
                              conf, 'bzr', 'foo.bzr.sf.net')
1787
        # phishing attempt
1788
        self._got_user_passwd(None, None,
1789
                              conf, 'bzr', 'bbzr.sf.net')
1790
1791
    def test_for_matching_host_None(self):
1792
        conf = config.AuthenticationConfig(_file=StringIO(
1793
                """# Identity on foo.net
1794
[catchup bzr]
1795
scheme=bzr
1796
user=joe
1797
password=joepass
1798
[DEFAULT]
1799
user=georges
1800
password=bendover
1801
"""))
1802
        # match no host
1803
        self._got_user_passwd('joe', 'joepass',
1804
                              conf, 'bzr', 'quux.net')
1805
        # no host but different scheme
1806
        self._got_user_passwd('georges', 'bendover',
1807
                              conf, 'ftp', 'quux.net')
1808
1809
    def test_credentials_for_path(self):
1810
        conf = config.AuthenticationConfig(_file=StringIO(
1811
                """
1812
[http dir1]
1813
scheme=http
1814
host=bar.org
1815
path=/dir1
1816
user=jim
1817
password=jimpass
1818
[http dir2]
1819
scheme=http
1820
host=bar.org
1821
path=/dir2
1822
user=georges
1823
password=bendover
1824
"""))
1825
        # no path no dice
1826
        self._got_user_passwd(None, None,
1827
                              conf, 'http', host='bar.org', path='/dir3')
1828
        # matching path
1829
        self._got_user_passwd('georges', 'bendover',
1830
                              conf, 'http', host='bar.org', path='/dir2')
1831
        # matching subdir
1832
        self._got_user_passwd('jim', 'jimpass',
1833
                              conf, 'http', host='bar.org',path='/dir1/subdir')
1834
1835
    def test_credentials_for_user(self):
1836
        conf = config.AuthenticationConfig(_file=StringIO(
1837
                """
1838
[with user]
1839
scheme=http
1840
host=bar.org
1841
user=jim
1842
password=jimpass
1843
"""))
1844
        # Get user
1845
        self._got_user_passwd('jim', 'jimpass',
1846
                              conf, 'http', 'bar.org')
1847
        # Get same user
1848
        self._got_user_passwd('jim', 'jimpass',
1849
                              conf, 'http', 'bar.org', user='jim')
1850
        # Don't get a different user if one is specified
1851
        self._got_user_passwd(None, None,
1852
                              conf, 'http', 'bar.org', user='georges')
1853
3418.4.1 by Vincent Ladeuil
Reproduce bug 199440.
1854
    def test_credentials_for_user_without_password(self):
1855
        conf = config.AuthenticationConfig(_file=StringIO(
1856
                """
1857
[without password]
1858
scheme=http
1859
host=bar.org
1860
user=jim
1861
"""))
1862
        # Get user but no password
1863
        self._got_user_passwd('jim', None,
1864
                              conf, 'http', 'bar.org')
1865
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1866
    def test_verify_certificates(self):
1867
        conf = config.AuthenticationConfig(_file=StringIO(
1868
                """
1869
[self-signed]
1870
scheme=https
1871
host=bar.org
1872
user=jim
1873
password=jimpass
1874
verify_certificates=False
1875
[normal]
1876
scheme=https
1877
host=foo.net
1878
user=georges
1879
password=bendover
1880
"""))
1881
        credentials = conf.get_credentials('https', 'bar.org')
1882
        self.assertEquals(False, credentials.get('verify_certificates'))
1883
        credentials = conf.get_credentials('https', 'foo.net')
1884
        self.assertEquals(True, credentials.get('verify_certificates'))
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1885
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1886
1887
class TestAuthenticationStorage(tests.TestCaseInTempDir):
1888
3777.1.8 by Aaron Bentley
Commit work-in-progress
1889
    def test_set_credentials(self):
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1890
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1891
        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
1892
        99, path='/foo', verify_certificates=False, realm='realm')
3777.1.8 by Aaron Bentley
Commit work-in-progress
1893
        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
1894
                                           port=99, path='/foo',
1895
                                           realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1896
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
1897
                       'verify_certificates': False, 'scheme': 'scheme', 
1898
                       'host': 'host', 'port': 99, 'path': '/foo', 
1899
                       'realm': 'realm'}
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1900
        self.assertEqual(CREDENTIALS, credentials)
1901
        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
1902
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1903
        self.assertEqual(CREDENTIALS, credentials_from_disk)
3777.1.8 by Aaron Bentley
Commit work-in-progress
1904
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1905
    def test_reset_credentials_different_name(self):
1906
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1907
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
1908
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1909
        self.assertIs(None, conf._get_config().get('name'))
1910
        credentials = conf.get_credentials(host='host', scheme='scheme')
1911
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
1912
                       'password', 'verify_certificates': True, 
1913
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
1914
                       'path': None, 'realm': None}
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1915
        self.assertEqual(CREDENTIALS, credentials)
1916
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1917
2900.2.14 by Vincent Ladeuil
More tests.
1918
class TestAuthenticationConfig(tests.TestCase):
1919
    """Test AuthenticationConfig behaviour"""
1920
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1921
    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.
1922
                                       host=None, port=None, realm=None,
1923
                                       path=None):
2900.2.14 by Vincent Ladeuil
More tests.
1924
        if host is None:
1925
            host = 'bar.org'
1926
        user, password = 'jim', 'precious'
1927
        expected_prompt = expected_prompt_format % {
1928
            'scheme': scheme, 'host': host, 'port': port,
1929
            'user': user, 'realm': realm}
1930
1931
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1932
        stderr = tests.StringIOWrapper()
2900.2.14 by Vincent Ladeuil
More tests.
1933
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1934
                                            stdout=stdout, stderr=stderr)
2900.2.14 by Vincent Ladeuil
More tests.
1935
        # We use an empty conf so that the user is always prompted
1936
        conf = config.AuthenticationConfig()
1937
        self.assertEquals(password,
1938
                          conf.get_password(scheme, host, user, port=port,
1939
                                            realm=realm, path=path))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1940
        self.assertEquals(expected_prompt, stderr.getvalue())
1941
        self.assertEquals('', stdout.getvalue())
2900.2.14 by Vincent Ladeuil
More tests.
1942
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1943
    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.
1944
                                       host=None, port=None, realm=None,
1945
                                       path=None):
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1946
        if host is None:
1947
            host = 'bar.org'
1948
        username = 'jim'
1949
        expected_prompt = expected_prompt_format % {
1950
            'scheme': scheme, 'host': host, 'port': port,
1951
            'realm': realm}
1952
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1953
        stderr = tests.StringIOWrapper()
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1954
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1955
                                            stdout=stdout, stderr=stderr)
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1956
        # We use an empty conf so that the user is always prompted
1957
        conf = config.AuthenticationConfig()
4222.3.5 by Jelmer Vernooij
Fix test.
1958
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
1959
                          realm=realm, path=path, ask=True))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1960
        self.assertEquals(expected_prompt, stderr.getvalue())
1961
        self.assertEquals('', stdout.getvalue())
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1962
1963
    def test_username_defaults_prompts(self):
1964
        # HTTP prompts can't be tested here, see test_http.py
1965
        self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
1966
        self._check_default_username_prompt(
1967
            'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
1968
        self._check_default_username_prompt(
1969
            'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
1970
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
1971
    def test_username_default_no_prompt(self):
1972
        conf = config.AuthenticationConfig()
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1973
        self.assertEquals(None,
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
1974
            conf.get_user('ftp', 'example.com'))
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1975
        self.assertEquals("explicitdefault",
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
1976
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
1977
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1978
    def test_password_default_prompts(self):
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
1979
        # HTTP prompts can't be tested here, see test_http.py
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1980
        self._check_default_password_prompt(
1981
            'FTP %(user)s@%(host)s password: ', 'ftp')
1982
        self._check_default_password_prompt(
1983
            'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
1984
        self._check_default_password_prompt(
1985
            'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
2900.2.14 by Vincent Ladeuil
More tests.
1986
        # SMTP port handling is a bit special (it's handled if embedded in the
1987
        # host too)
2900.2.22 by Vincent Ladeuil
Polishing.
1988
        # FIXME: should we: forbid that, extend it to other schemes, leave
1989
        # things as they are that's fine thank you ?
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1990
        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
1991
                                            'smtp')
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1992
        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
1993
                                            'smtp', host='bar.org:10025')
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
1994
        self._check_default_password_prompt(
2900.2.14 by Vincent Ladeuil
More tests.
1995
            'SMTP %(user)s@%(host)s:%(port)d password: ',
1996
            'smtp', port=10025)
1997
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
1998
    def test_ssh_password_emits_warning(self):
1999
        conf = config.AuthenticationConfig(_file=StringIO(
2000
                """
2001
[ssh with password]
2002
scheme=ssh
2003
host=bar.org
2004
user=jim
2005
password=jimpass
2006
"""))
2007
        entered_password = 'typed-by-hand'
2008
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2009
        stderr = tests.StringIOWrapper()
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2010
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2011
                                            stdout=stdout, stderr=stderr)
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2012
2013
        # Since the password defined in the authentication config is ignored,
2014
        # the user is prompted
2015
        self.assertEquals(entered_password,
2016
                          conf.get_password('ssh', 'bar.org', user='jim'))
2017
        self.assertContainsRe(
4794.1.17 by Robert Collins
Fix from vila for type log_log.
2018
            self.get_log(),
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2019
            'password ignored in section \[ssh with password\]')
2020
3420.1.3 by Vincent Ladeuil
John's review feedback.
2021
    def test_ssh_without_password_doesnt_emit_warning(self):
2022
        conf = config.AuthenticationConfig(_file=StringIO(
2023
                """
2024
[ssh with password]
2025
scheme=ssh
2026
host=bar.org
2027
user=jim
2028
"""))
2029
        entered_password = 'typed-by-hand'
2030
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2031
        stderr = tests.StringIOWrapper()
3420.1.3 by Vincent Ladeuil
John's review feedback.
2032
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
2033
                                            stdout=stdout,
2034
                                            stderr=stderr)
3420.1.3 by Vincent Ladeuil
John's review feedback.
2035
2036
        # Since the password defined in the authentication config is ignored,
2037
        # the user is prompted
2038
        self.assertEquals(entered_password,
2039
                          conf.get_password('ssh', 'bar.org', user='jim'))
3420.1.4 by Vincent Ladeuil
Fix comment.
2040
        # No warning shoud be emitted since there is no password. We are only
2041
        # providing "user".
3420.1.3 by Vincent Ladeuil
John's review feedback.
2042
        self.assertNotContainsRe(
4794.1.15 by Robert Collins
Review feedback.
2043
            self.get_log(),
3420.1.3 by Vincent Ladeuil
John's review feedback.
2044
            'password ignored in section \[ssh with password\]')
2045
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
2046
    def test_uses_fallback_stores(self):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
2047
        self.overrideAttr(config, 'credential_store_registry',
2048
                          config.CredentialStoreRegistry())
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
2049
        store = StubCredentialStore()
2050
        store.add_credentials("http", "example.com", "joe", "secret")
2051
        config.credential_store_registry.register("stub", store, fallback=True)
2052
        conf = config.AuthenticationConfig(_file=StringIO())
2053
        creds = conf.get_credentials("http", "example.com")
2054
        self.assertEquals("joe", creds["user"])
2055
        self.assertEquals("secret", creds["password"])
2056
2900.2.14 by Vincent Ladeuil
More tests.
2057
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2058
class StubCredentialStore(config.CredentialStore):
2059
2060
    def __init__(self):
2061
        self._username = {}
2062
        self._password = {}
2063
2064
    def add_credentials(self, scheme, host, user, password=None):
2065
        self._username[(scheme, host)] = user
2066
        self._password[(scheme, host)] = password
2067
2068
    def get_credentials(self, scheme, host, port=None, user=None,
2069
        path=None, realm=None):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2070
        key = (scheme, host)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2071
        if not key in self._username:
2072
            return None
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2073
        return { "scheme": scheme, "host": host, "port": port,
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2074
                "user": self._username[key], "password": self._password[key]}
2075
2076
2077
class CountingCredentialStore(config.CredentialStore):
2078
2079
    def __init__(self):
2080
        self._calls = 0
2081
2082
    def get_credentials(self, scheme, host, port=None, user=None,
2083
        path=None, realm=None):
2084
        self._calls += 1
2085
        return None
2086
2087
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2088
class TestCredentialStoreRegistry(tests.TestCase):
2089
2090
    def _get_cs_registry(self):
2091
        return config.credential_store_registry
2092
2093
    def test_default_credential_store(self):
2094
        r = self._get_cs_registry()
2095
        default = r.get_credential_store(None)
2096
        self.assertIsInstance(default, config.PlainTextCredentialStore)
2097
2098
    def test_unknown_credential_store(self):
2099
        r = self._get_cs_registry()
2100
        # It's hard to imagine someone creating a credential store named
2101
        # 'unknown' so we use that as an never registered key.
2102
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
2103
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2104
    def test_fallback_none_registered(self):
2105
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2106
        self.assertEquals(None,
2107
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2108
2109
    def test_register(self):
2110
        r = config.CredentialStoreRegistry()
2111
        r.register("stub", StubCredentialStore(), fallback=False)
2112
        r.register("another", StubCredentialStore(), fallback=True)
2113
        self.assertEquals(["another", "stub"], r.keys())
2114
2115
    def test_register_lazy(self):
2116
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2117
        r.register_lazy("stub", "bzrlib.tests.test_config",
2118
                        "StubCredentialStore", fallback=False)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2119
        self.assertEquals(["stub"], r.keys())
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2120
        self.assertIsInstance(r.get_credential_store("stub"),
2121
                              StubCredentialStore)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2122
2123
    def test_is_fallback(self):
2124
        r = config.CredentialStoreRegistry()
2125
        r.register("stub1", None, fallback=False)
2126
        r.register("stub2", None, fallback=True)
2127
        self.assertEquals(False, r.is_fallback("stub1"))
2128
        self.assertEquals(True, r.is_fallback("stub2"))
2129
2130
    def test_no_fallback(self):
2131
        r = config.CredentialStoreRegistry()
2132
        store = CountingCredentialStore()
2133
        r.register("count", store, fallback=False)
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2134
        self.assertEquals(None,
2135
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2136
        self.assertEquals(0, store._calls)
2137
2138
    def test_fallback_credentials(self):
2139
        r = config.CredentialStoreRegistry()
2140
        store = StubCredentialStore()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2141
        store.add_credentials("http", "example.com",
2142
                              "somebody", "geheim")
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2143
        r.register("stub", store, fallback=True)
2144
        creds = r.get_fallback_credentials("http", "example.com")
2145
        self.assertEquals("somebody", creds["user"])
2146
        self.assertEquals("geheim", creds["password"])
2147
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2148
    def test_fallback_first_wins(self):
2149
        r = config.CredentialStoreRegistry()
2150
        stub1 = StubCredentialStore()
2151
        stub1.add_credentials("http", "example.com",
2152
                              "somebody", "stub1")
2153
        r.register("stub1", stub1, fallback=True)
2154
        stub2 = StubCredentialStore()
2155
        stub2.add_credentials("http", "example.com",
2156
                              "somebody", "stub2")
2157
        r.register("stub2", stub1, fallback=True)
2158
        creds = r.get_fallback_credentials("http", "example.com")
2159
        self.assertEquals("somebody", creds["user"])
2160
        self.assertEquals("stub1", creds["password"])
2161
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2162
2163
class TestPlainTextCredentialStore(tests.TestCase):
2164
2165
    def test_decode_password(self):
2166
        r = config.credential_store_registry
2167
        plain_text = r.get_credential_store()
2168
        decoded = plain_text.decode_password(dict(password='secret'))
2169
        self.assertEquals('secret', decoded)
2170
2171
2900.2.14 by Vincent Ladeuil
More tests.
2172
# 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.
2173
# can implement generic tests.
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
2174
# test_user_password_in_url
2175
# test_user_in_url_password_from_config
2176
# test_user_in_url_password_prompted
2177
# test_user_in_config
2178
# test_user_getpass.getuser
2179
# test_user_prompted ?
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
2180
class TestAuthenticationRing(tests.TestCaseWithTransport):
2181
    pass