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