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