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