/brz/remove-bazaar

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