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