~bzr-pqm/bzr/bzr.dev

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