/brz/remove-bazaar

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