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