/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
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,
5321.1.89 by Gordon Tyler
Moved mergetools config tests to bzrlib.tests.test_config.
36
    mergetools,
2900.2.14 by Vincent Ladeuil
More tests.
37
    ui,
1878.1.3 by John Arbash Meinel
some test cleanups
38
    urlutils,
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
39
    registry,
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
40
    tests,
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
41
    trace,
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
42
    transport,
1878.1.3 by John Arbash Meinel
some test cleanups
43
    )
5743.13.1 by Vincent Ladeuil
Deprecate _get_editor to identify its usages.
44
from bzrlib.symbol_versioning import (
45
    deprecated_in,
46
    deprecated_method,
47
    )
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
48
from bzrlib.transport import remote
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
49
from bzrlib.tests import (
50
    features,
51
    TestSkipped,
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
52
    scenarios,
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
53
    )
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
54
from bzrlib.util.configobj import configobj
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
55
56
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
57
def lockable_config_scenarios():
58
    return [
59
        ('global',
60
         {'config_class': config.GlobalConfig,
61
          'config_args': [],
62
          'config_section': 'DEFAULT'}),
63
        ('locations',
64
         {'config_class': config.LocationConfig,
65
          'config_args': ['.'],
66
          'config_section': '.'}),]
67
68
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
69
load_tests = scenarios.load_tests_apply_scenarios
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
70
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
71
# Register helpers to build stores
72
config.test_store_builder_registry.register(
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
73
    'configobj', lambda test: config.IniFileStore(test.get_transport(),
74
                                                  'configobj.conf'))
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
75
config.test_store_builder_registry.register(
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
76
    'bazaar', lambda test: config.GlobalStore())
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
77
config.test_store_builder_registry.register(
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
78
    'location', lambda test: config.LocationStore())
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
79
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
80
81
def build_backing_branch(test, relpath,
82
                         transport_class=None, server_class=None):
83
    """Test helper to create a backing branch only once.
84
85
    Some tests needs multiple stores/stacks to check concurrent update
86
    behaviours. As such, they need to build different branch *objects* even if
87
    they share the branch on disk.
88
89
    :param relpath: The relative path to the branch. (Note that the helper
90
        should always specify the same relpath).
91
92
    :param transport_class: The Transport class the test needs to use.
93
94
    :param server_class: The server associated with the ``transport_class``
95
        above.
96
5743.10.9 by Vincent Ladeuil
Fix use of none where neither is required.
97
    Either both or neither of ``transport_class`` and ``server_class`` should
98
    be specified.
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
99
    """
100
    if transport_class is not None and server_class is not None:
101
        test.transport_class = transport_class
102
        test.transport_server = server_class
103
    elif not (transport_class is None and server_class is None):
104
        raise AssertionError('Specify both ``transport_class`` and '
5743.10.9 by Vincent Ladeuil
Fix use of none where neither is required.
105
                             '``server_class`` or neither of them')
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
106
    if getattr(test, 'backing_branch', None) is None:
107
        # First call, let's build the branch on disk
108
        test.backing_branch = test.make_branch(relpath)
109
110
5743.10.11 by Vincent Ladeuil
Remove the duplicated comment so we can make the comment bigger :)
111
def keep_branch_alive(test, b):
112
    """Keep a branch alive for the duration of a test.
113
114
    :param tests: the test that should hold the branch alive.
115
116
    :param b: the branch that should be kept alive.
117
118
    Several tests need to keep a reference to a branch object as they are
119
    testing a Store which uses a weak reference. This is achieved by embedding
120
    a reference to the branch object in a lambda passed to a cleanup. When the
121
    test finish the cleanup method is deleted and so does the reference to the
122
    branch.
123
    """
124
    test.addCleanup(lambda : b)
125
5743.10.12 by Vincent Ladeuil
PEP8
126
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
127
def build_branch_store(test):
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
128
    build_backing_branch(test, 'branch')
129
    b = branch.Branch.open('branch')
5743.10.11 by Vincent Ladeuil
Remove the duplicated comment so we can make the comment bigger :)
130
    keep_branch_alive(test, b)
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
131
    return config.BranchStore(b)
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
132
config.test_store_builder_registry.register('branch', build_branch_store)
133
134
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
135
def build_remote_branch_store(test):
136
    # There is only one permutation (but we won't be able to handle more with
137
    # this design anyway)
138
    (transport_class, server_class) = remote.get_test_permutations()[0]
139
    build_backing_branch(test, 'branch', transport_class, server_class)
140
    b = branch.Branch.open(test.get_url('branch'))
5743.10.11 by Vincent Ladeuil
Remove the duplicated comment so we can make the comment bigger :)
141
    keep_branch_alive(test, b)
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
142
    return config.BranchStore(b)
143
config.test_store_builder_registry.register('remote_branch',
144
                                            build_remote_branch_store)
145
146
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
147
config.test_stack_builder_registry.register(
148
    'bazaar', lambda test: config.GlobalStack())
149
config.test_stack_builder_registry.register(
150
    'location', lambda test: config.LocationStack('.'))
151
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
152
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
153
def build_branch_stack(test):
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
154
    build_backing_branch(test, 'branch')
155
    b = branch.Branch.open('branch')
5743.10.11 by Vincent Ladeuil
Remove the duplicated comment so we can make the comment bigger :)
156
    keep_branch_alive(test, b)
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
157
    return config.BranchStack(b)
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
158
config.test_stack_builder_registry.register('branch', build_branch_stack)
159
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
160
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
161
def build_remote_branch_stack(test):
162
    # There is only one permutation (but we won't be able to handle more with
163
    # this design anyway)
164
    (transport_class, server_class) = remote.get_test_permutations()[0]
165
    build_backing_branch(test, 'branch', transport_class, server_class)
166
    b = branch.Branch.open(test.get_url('branch'))
5743.10.11 by Vincent Ladeuil
Remove the duplicated comment so we can make the comment bigger :)
167
    keep_branch_alive(test, b)
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
168
    return config.BranchStack(b)
169
config.test_stack_builder_registry.register('remote_branch',
170
                                            build_remote_branch_stack)
171
172
1553.6.12 by Erik BÃ¥gfors
remove AliasConfig, based on input from abentley
173
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
174
sample_config_text = u"""
175
[DEFAULT]
176
email=Erik B\u00e5gfors <erik@bagfors.nu>
177
editor=vim
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
178
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
179
gpg_signing_command=gnome-gpg
180
log_format=short
181
user_global_option=something
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
182
bzr.mergetool.sometool=sometool {base} {this} {other} -o {result}
5321.2.3 by Vincent Ladeuil
Prefix mergetools option names with 'bzr.'.
183
bzr.mergetool.funkytool=funkytool "arg with spaces" {this_temp}
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
184
bzr.default_mergetool=sometool
2120.6.2 by James Henstridge
remove get_matching_sections() norecurse tests, since that feature is handled in the config policy code now
185
[ALIASES]
186
h=help
187
ll=""" + sample_long_alias + "\n"
188
189
190
sample_always_signatures = """
191
[DEFAULT]
192
check_signatures=ignore
193
create_signatures=always
194
"""
195
196
sample_ignore_signatures = """
197
[DEFAULT]
198
check_signatures=require
199
create_signatures=never
200
"""
201
202
sample_maybe_signatures = """
203
[DEFAULT]
204
check_signatures=ignore
205
create_signatures=when-required
206
"""
207
208
sample_branches_text = """
209
[http://www.example.com]
210
# Top level policy
211
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
212
normal_option = normal
213
appendpath_option = append
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
214
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
215
norecurse_option = norecurse
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
216
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
217
[http://www.example.com/ignoreparent]
218
# different project: ignore parent dir config
219
ignore_parents=true
220
[http://www.example.com/norecurse]
221
# configuration items that only apply to this dir
222
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
223
normal_option = norecurse
224
[http://www.example.com/dir]
225
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
226
[/b/]
227
check_signatures=require
228
# test trailing / matching with no children
229
[/a/]
230
check_signatures=check-available
231
gpg_signing_command=false
232
user_local_option=local
233
# test trailing / matching
234
[/a/*]
235
#subdirs will match but not the parent
236
[/a/c]
237
check_signatures=ignore
238
post_commit=bzrlib.tests.test_config.post_commit
239
#testing explicit beats globs
240
"""
1553.6.3 by Erik BÃ¥gfors
tests for AliasesConfig
241
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
242
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
243
def create_configs(test):
244
    """Create configuration files for a given test.
245
246
    This requires creating a tree (and populate the ``test.tree`` attribute)
247
    and its associated branch and will populate the following attributes:
248
249
    - branch_config: A BranchConfig for the associated branch.
250
251
    - locations_config : A LocationConfig for the associated branch
252
253
    - bazaar_config: A GlobalConfig.
254
255
    The tree and branch are created in a 'tree' subdirectory so the tests can
256
    still use the test directory to stay outside of the branch.
257
    """
258
    tree = test.make_branch_and_tree('tree')
259
    test.tree = tree
260
    test.branch_config = config.BranchConfig(tree.branch)
261
    test.locations_config = config.LocationConfig(tree.basedir)
262
    test.bazaar_config = config.GlobalConfig()
263
5533.2.4 by Vincent Ladeuil
Fix whitespace issue.
264
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
265
def create_configs_with_file_option(test):
266
    """Create configuration files with a ``file`` option set in each.
267
268
    This builds on ``create_configs`` and add one ``file`` option in each
269
    configuration with a value which allows identifying the configuration file.
270
    """
271
    create_configs(test)
272
    test.bazaar_config.set_user_option('file', 'bazaar')
273
    test.locations_config.set_user_option('file', 'locations')
274
    test.branch_config.set_user_option('file', 'branch')
275
276
277
class TestOptionsMixin:
278
279
    def assertOptions(self, expected, conf):
280
        # We don't care about the parser (as it will make tests hard to write
281
        # and error-prone anyway)
282
        self.assertThat([opt[:4] for opt in conf._get_options()],
283
                        matchers.Equals(expected))
284
285
1474 by Robert Collins
Merge from Aaron Bentley.
286
class InstrumentedConfigObj(object):
287
    """A config obj look-enough-alike to record calls made to it."""
288
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
289
    def __contains__(self, thing):
290
        self._calls.append(('__contains__', thing))
291
        return False
292
293
    def __getitem__(self, key):
294
        self._calls.append(('__getitem__', key))
295
        return self
296
1551.2.20 by Aaron Bentley
Treated config files as utf-8
297
    def __init__(self, input, encoding=None):
298
        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.
299
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
300
    def __setitem__(self, key, value):
301
        self._calls.append(('__setitem__', key, value))
302
2120.6.4 by James Henstridge
add support for specifying policy when storing options
303
    def __delitem__(self, key):
304
        self._calls.append(('__delitem__', key))
305
306
    def keys(self):
307
        self._calls.append(('keys',))
308
        return []
309
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
310
    def reload(self):
311
        self._calls.append(('reload',))
312
1551.2.49 by abentley
Made ConfigObj output binary-identical files on win32 and *nix
313
    def write(self, arg):
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
314
        self._calls.append(('write',))
315
2120.6.4 by James Henstridge
add support for specifying policy when storing options
316
    def as_bool(self, value):
317
        self._calls.append(('as_bool', value))
318
        return False
319
320
    def get_value(self, section, name):
321
        self._calls.append(('get_value', section, name))
322
        return None
323
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
324
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
325
class FakeBranch(object):
326
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
327
    def __init__(self, base=None, user_id=None):
328
        if base is None:
329
            self.base = "http://example.com/branches/demo"
330
        else:
331
            self.base = base
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
332
        self._transport = self.control_files = \
333
            FakeControlFilesAndTransport(user_id=user_id)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
334
4226.1.7 by Robert Collins
Alter test_config.FakeBranch in accordance with the Branch change to have a _get_config.
335
    def _get_config(self):
336
        return config.TransportConfig(self._transport, 'branch.conf')
337
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
338
    def lock_write(self):
339
        pass
340
341
    def unlock(self):
342
        pass
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
343
344
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
345
class FakeControlFilesAndTransport(object):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
346
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
347
    def __init__(self, user_id=None):
348
        self.files = {}
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
349
        if user_id:
350
            self.files['email'] = user_id
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
351
        self._transport = self
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
352
1185.65.29 by Robert Collins
Implement final review suggestions.
353
    def get_utf8(self, filename):
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
354
        # from LockableFiles
355
        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
356
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
357
    def get(self, filename):
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
358
        # from Transport
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
359
        try:
360
            return StringIO(self.files[filename])
361
        except KeyError:
362
            raise errors.NoSuchFile(filename)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
363
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
364
    def get_bytes(self, filename):
365
        # from Transport
366
        try:
367
            return self.files[filename]
368
        except KeyError:
369
            raise errors.NoSuchFile(filename)
370
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
371
    def put(self, filename, fileobj):
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
372
        self.files[filename] = fileobj.read()
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
373
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
374
    def put_file(self, filename, fileobj):
375
        return self.put(filename, fileobj)
376
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
377
378
class InstrumentedConfig(config.Config):
379
    """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.
380
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
381
    def __init__(self):
382
        super(InstrumentedConfig, self).__init__()
383
        self._calls = []
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
384
        self._signatures = config.CHECK_NEVER
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
385
386
    def _get_user_id(self):
387
        self._calls.append('_get_user_id')
388
        return "Robert Collins <robert.collins@example.org>"
389
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
390
    def _get_signature_checking(self):
391
        self._calls.append('_get_signature_checking')
392
        return self._signatures
393
4603.1.10 by Aaron Bentley
Provide change editor via config.
394
    def _get_change_editor(self):
395
        self._calls.append('_get_change_editor')
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
396
        return 'vimdiff -fo @new_path @old_path'
4603.1.10 by Aaron Bentley
Provide change editor via config.
397
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
398
1556.2.2 by Aaron Bentley
Fixed get_bool
399
bool_config = """[DEFAULT]
400
active = true
401
inactive = false
402
[UPPERCASE]
403
active = True
404
nonactive = False
405
"""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
406
407
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
408
class TestConfigObj(tests.TestCase):
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
409
1556.2.2 by Aaron Bentley
Fixed get_bool
410
    def test_get_bool(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
411
        co = config.ConfigObj(StringIO(bool_config))
1556.2.2 by Aaron Bentley
Fixed get_bool
412
        self.assertIs(co.get_bool('DEFAULT', 'active'), True)
413
        self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
414
        self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
415
        self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
416
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
417
    def test_hash_sign_in_value(self):
418
        """
419
        Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
420
        treated as comments when read in again. (#86838)
421
        """
422
        co = config.ConfigObj()
423
        co['test'] = 'foo#bar'
5050.62.14 by Alexander Belchenko
don't use lines in the tests, and better comment about the corresponding bug in configobj; avoid using write() method without outfile parameter.
424
        outfile = StringIO()
425
        co.write(outfile=outfile)
426
        lines = outfile.getvalue().splitlines()
3221.7.4 by Matt Nordhoff
Add test for bug #86838.
427
        self.assertEqual(lines, ['test = "foo#bar"'])
428
        co2 = config.ConfigObj(lines)
429
        self.assertEqual(co2['test'], 'foo#bar')
430
5050.62.10 by Alexander Belchenko
test to illustrate the problem
431
    def test_triple_quotes(self):
432
        # Bug #710410: if the value string has triple quotes
433
        # then ConfigObj versions up to 4.7.2 will quote them wrong
5050.62.12 by Alexander Belchenko
added NEWS entry
434
        # and won't able to read them back
5050.62.10 by Alexander Belchenko
test to illustrate the problem
435
        triple_quotes_value = '''spam
436
""" that's my spam """
437
eggs'''
438
        co = config.ConfigObj()
439
        co['test'] = triple_quotes_value
5050.62.14 by Alexander Belchenko
don't use lines in the tests, and better comment about the corresponding bug in configobj; avoid using write() method without outfile parameter.
440
        # While writing this test another bug in ConfigObj has been found:
5050.62.10 by Alexander Belchenko
test to illustrate the problem
441
        # method co.write() without arguments produces list of lines
442
        # one option per line, and multiline values are not split
443
        # across multiple lines,
5050.62.14 by Alexander Belchenko
don't use lines in the tests, and better comment about the corresponding bug in configobj; avoid using write() method without outfile parameter.
444
        # and that breaks the parsing these lines back by ConfigObj.
445
        # This issue only affects test, but it's better to avoid
446
        # `co.write()` construct at all.
447
        # [bialix 20110222] bug report sent to ConfigObj's author
5050.62.10 by Alexander Belchenko
test to illustrate the problem
448
        outfile = StringIO()
449
        co.write(outfile=outfile)
5050.62.14 by Alexander Belchenko
don't use lines in the tests, and better comment about the corresponding bug in configobj; avoid using write() method without outfile parameter.
450
        output = outfile.getvalue()
5050.62.10 by Alexander Belchenko
test to illustrate the problem
451
        # now we're trying to read it back
5050.62.14 by Alexander Belchenko
don't use lines in the tests, and better comment about the corresponding bug in configobj; avoid using write() method without outfile parameter.
452
        co2 = config.ConfigObj(StringIO(output))
5050.62.10 by Alexander Belchenko
test to illustrate the problem
453
        self.assertEquals(triple_quotes_value, co2['test'])
454
1556.2.2 by Aaron Bentley
Fixed get_bool
455
2900.1.1 by Vincent Ladeuil
456
erroneous_config = """[section] # line 1
457
good=good # line 2
458
[section] # line 3
459
whocares=notme # line 4
460
"""
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
461
462
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
463
class TestConfigObjErrors(tests.TestCase):
2900.1.1 by Vincent Ladeuil
464
465
    def test_duplicate_section_name_error_line(self):
466
        try:
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
467
            co = configobj.ConfigObj(StringIO(erroneous_config),
468
                                     raise_errors=True)
2900.1.1 by Vincent Ladeuil
469
        except config.configobj.DuplicateError, e:
470
            self.assertEqual(3, e.line_number)
471
        else:
472
            self.fail('Error in config file not detected')
473
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
474
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
475
class TestConfig(tests.TestCase):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
476
477
    def test_constructs(self):
478
        config.Config()
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
479
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
480
    def test_no_default_editor(self):
5743.13.1 by Vincent Ladeuil
Deprecate _get_editor to identify its usages.
481
        self.assertRaises(
482
            NotImplementedError,
483
            self.applyDeprecated, deprecated_in((2, 4, 0)),
484
            config.Config().get_editor)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
485
486
    def test_user_email(self):
487
        my_config = InstrumentedConfig()
488
        self.assertEqual('robert.collins@example.org', my_config.user_email())
489
        self.assertEqual(['_get_user_id'], my_config._calls)
490
491
    def test_username(self):
492
        my_config = InstrumentedConfig()
493
        self.assertEqual('Robert Collins <robert.collins@example.org>',
494
                         my_config.username())
495
        self.assertEqual(['_get_user_id'], my_config._calls)
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
496
497
    def test_signatures_default(self):
498
        my_config = config.Config()
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
499
        self.assertFalse(my_config.signature_needed())
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
500
        self.assertEqual(config.CHECK_IF_POSSIBLE,
501
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
502
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
503
                         my_config.signing_policy())
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
504
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
505
    def test_signatures_template_method(self):
506
        my_config = InstrumentedConfig()
507
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
508
        self.assertEqual(['_get_signature_checking'], my_config._calls)
509
510
    def test_signatures_template_method_none(self):
511
        my_config = InstrumentedConfig()
512
        my_config._signatures = None
513
        self.assertEqual(config.CHECK_IF_POSSIBLE,
514
                         my_config.signature_checking())
515
        self.assertEqual(['_get_signature_checking'], my_config._calls)
516
1442.1.56 by Robert Collins
gpg_signing_command configuration item
517
    def test_gpg_signing_command_default(self):
518
        my_config = config.Config()
519
        self.assertEqual('gpg', my_config.gpg_signing_command())
520
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
521
    def test_get_user_option_default(self):
522
        my_config = config.Config()
523
        self.assertEqual(None, my_config.get_user_option('no_option'))
524
1472 by Robert Collins
post commit hook, first pass implementation
525
    def test_post_commit_default(self):
526
        my_config = config.Config()
527
        self.assertEqual(None, my_config.post_commit())
528
1553.2.9 by Erik BÃ¥gfors
log_formatter => log_format for "named" formatters
529
    def test_log_format_default(self):
1553.2.8 by Erik BÃ¥gfors
tests for config log_formatter
530
        my_config = config.Config()
1553.2.9 by Erik BÃ¥gfors
log_formatter => log_format for "named" formatters
531
        self.assertEqual('long', my_config.log_format())
1553.2.8 by Erik BÃ¥gfors
tests for config log_formatter
532
4603.1.10 by Aaron Bentley
Provide change editor via config.
533
    def test_get_change_editor(self):
534
        my_config = InstrumentedConfig()
535
        change_editor = my_config.get_change_editor('old_tree', 'new_tree')
536
        self.assertEqual(['_get_change_editor'], my_config._calls)
537
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
538
        self.assertEqual(['vimdiff', '-fo', '@new_path', '@old_path'],
4603.1.10 by Aaron Bentley
Provide change editor via config.
539
                         change_editor.command_template)
540
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
541
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
542
class TestConfigPath(tests.TestCase):
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
543
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
544
    def setUp(self):
545
        super(TestConfigPath, self).setUp()
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
546
        self.overrideEnv('HOME', '/home/bogus')
547
        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
548
        if sys.platform == 'win32':
5570.3.8 by Vincent Ladeuil
More use cases for overrideEnv.
549
            self.overrideEnv(
550
                '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.
551
            self.bzr_home = \
552
                '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
553
        else:
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
554
            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.
555
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
556
    def test_config_dir(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
557
        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.
558
559
    def test_config_filename(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
560
        self.assertEqual(config.config_filename(),
561
                         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.
562
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
563
    def test_locations_config_filename(self):
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
564
        self.assertEqual(config.locations_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
565
                         self.bzr_home + '/locations.conf')
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
566
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
567
    def test_authentication_config_filename(self):
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
568
        self.assertEqual(config.authentication_config_filename(),
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
569
                         self.bzr_home + '/authentication.conf')
570
4584.3.23 by Martin Pool
Correction to xdg_cache_dir and add a simple test
571
    def test_xdg_cache_dir(self):
572
        self.assertEqual(config.xdg_cache_dir(),
573
            '/home/bogus/.cache')
574
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
575
5519.4.8 by Neil Martinsen-Burrell
some tests and mention in Whats New
576
class TestXDGConfigDir(tests.TestCaseInTempDir):
577
    # must be in temp dir because config tests for the existence of the bazaar
578
    # subdirectory of $XDG_CONFIG_HOME
579
5519.4.9 by Neil Martinsen-Burrell
working tests
580
    def setUp(self):
5519.4.10 by Andrew Bennetts
Cosmetic tweaks to TestXDGConfigDir.
581
        if sys.platform in ('darwin', 'win32'):
582
            raise tests.TestNotApplicable(
583
                'XDG config dir not used on this platform')
5519.4.9 by Neil Martinsen-Burrell
working tests
584
        super(TestXDGConfigDir, self).setUp()
5570.3.8 by Vincent Ladeuil
More use cases for overrideEnv.
585
        self.overrideEnv('HOME', self.test_home_dir)
5519.4.10 by Andrew Bennetts
Cosmetic tweaks to TestXDGConfigDir.
586
        # BZR_HOME overrides everything we want to test so unset it.
5570.3.8 by Vincent Ladeuil
More use cases for overrideEnv.
587
        self.overrideEnv('BZR_HOME', None)
5519.4.9 by Neil Martinsen-Burrell
working tests
588
5519.4.8 by Neil Martinsen-Burrell
some tests and mention in Whats New
589
    def test_xdg_config_dir_exists(self):
5519.4.10 by Andrew Bennetts
Cosmetic tweaks to TestXDGConfigDir.
590
        """When ~/.config/bazaar exists, use it as the config dir."""
5519.4.8 by Neil Martinsen-Burrell
some tests and mention in Whats New
591
        newdir = osutils.pathjoin(self.test_home_dir, '.config', 'bazaar')
592
        os.makedirs(newdir)
593
        self.assertEqual(config.config_dir(), newdir)
594
595
    def test_xdg_config_home(self):
5519.4.10 by Andrew Bennetts
Cosmetic tweaks to TestXDGConfigDir.
596
        """When XDG_CONFIG_HOME is set, use it."""
5519.4.8 by Neil Martinsen-Burrell
some tests and mention in Whats New
597
        xdgconfigdir = osutils.pathjoin(self.test_home_dir, 'xdgconfig')
5570.3.8 by Vincent Ladeuil
More use cases for overrideEnv.
598
        self.overrideEnv('XDG_CONFIG_HOME', xdgconfigdir)
5519.4.8 by Neil Martinsen-Burrell
some tests and mention in Whats New
599
        newdir = osutils.pathjoin(xdgconfigdir, 'bazaar')
600
        os.makedirs(newdir)
601
        self.assertEqual(config.config_dir(), newdir)
602
603
5050.13.2 by Parth Malwankar
copy config file ownership only if a new file is created
604
class TestIniConfig(tests.TestCaseInTempDir):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
605
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
606
    def make_config_parser(self, s):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
607
        conf = config.IniBasedConfig.from_string(s)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
608
        return conf, conf._get_parser()
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
609
5050.13.2 by Parth Malwankar
copy config file ownership only if a new file is created
610
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
611
class TestIniConfigBuilding(TestIniConfig):
612
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
613
    def test_contructs(self):
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
614
        my_config = config.IniBasedConfig()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
615
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
616
    def test_from_fp(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
617
        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.
618
        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.
619
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
620
    def test_cached(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
621
        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.
622
        parser = my_config._get_parser()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
623
        self.assertTrue(my_config._get_parser() is parser)
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
624
5050.13.1 by Parth Malwankar
fixed .bazaar ownership regression
625
    def _dummy_chown(self, path, uid, gid):
626
        self.path, self.uid, self.gid = path, uid, gid
627
628
    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.
629
        """Ensure that chown is happening during _write_config_file"""
5050.13.1 by Parth Malwankar
fixed .bazaar ownership regression
630
        self.requireFeature(features.chown_feature)
631
        self.overrideAttr(os, 'chown', self._dummy_chown)
632
        self.path = self.uid = self.gid = None
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
633
        conf = config.IniBasedConfig(file_name='./foo.conf')
5050.13.1 by Parth Malwankar
fixed .bazaar ownership regression
634
        conf._write_config_file()
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
635
        self.assertEquals(self.path, './foo.conf')
5050.13.1 by Parth Malwankar
fixed .bazaar ownership regression
636
        self.assertTrue(isinstance(self.uid, int))
637
        self.assertTrue(isinstance(self.gid, int))
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
638
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
639
    def test_get_filename_parameter_is_deprecated_(self):
640
        conf = self.callDeprecated([
641
            'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
642
            ' Use file_name instead.'],
643
            config.IniBasedConfig, lambda: 'ini.conf')
5345.3.1 by Vincent Ladeuil
Check that _get_filename() is called and produces the desired side effect.
644
        self.assertEqual('ini.conf', conf.file_name)
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
645
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
646
    def test_get_parser_file_parameter_is_deprecated_(self):
647
        config_file = StringIO(sample_config_text.encode('utf-8'))
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
648
        conf = config.IniBasedConfig.from_string(sample_config_text)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
649
        conf = self.callDeprecated([
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
650
            'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
651
            ' Use IniBasedConfig(_content=xxx) instead.'],
652
            conf._get_parser, file=config_file)
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
653
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
654
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
655
class TestIniConfigSaving(tests.TestCaseInTempDir):
656
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
657
    def test_cant_save_without_a_file_name(self):
658
        conf = config.IniBasedConfig()
659
        self.assertRaises(AssertionError, conf._write_config_file)
660
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
661
    def test_saved_with_content(self):
662
        content = 'foo = bar\n'
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
663
        conf = config.IniBasedConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
664
            content, file_name='./test.conf', save=True)
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
665
        self.assertFileEqual(content, 'test.conf')
666
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
667
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
668
class TestIniConfigOptionExpansionDefaultValue(tests.TestCaseInTempDir):
669
    """What is the default value of expand for config options.
670
671
    This is an opt-in beta feature used to evaluate whether or not option
672
    references can appear in dangerous place raising exceptions, disapearing
673
    (and as such corrupting data) or if it's safe to activate the option by
674
    default.
675
676
    Note that these tests relies on config._expand_default_value being already
677
    overwritten in the parent class setUp.
678
    """
679
680
    def setUp(self):
681
        super(TestIniConfigOptionExpansionDefaultValue, self).setUp()
682
        self.config = None
683
        self.warnings = []
684
        def warning(*args):
685
            self.warnings.append(args[0] % args[1:])
686
        self.overrideAttr(trace, 'warning', warning)
687
688
    def get_config(self, expand):
689
        c = config.GlobalConfig.from_string('bzr.config.expand=%s' % (expand,),
690
                                            save=True)
691
        return c
692
693
    def assertExpandIs(self, expected):
694
        actual = config._get_expand_default_value()
695
        #self.config.get_user_option_as_bool('bzr.config.expand')
696
        self.assertEquals(expected, actual)
697
698
    def test_default_is_None(self):
699
        self.assertEquals(None, config._expand_default_value)
700
701
    def test_default_is_False_even_if_None(self):
702
        self.config = self.get_config(None)
703
        self.assertExpandIs(False)
704
705
    def test_default_is_False_even_if_invalid(self):
706
        self.config = self.get_config('<your choice>')
707
        self.assertExpandIs(False)
708
        # ...
709
        # Huh ? My choice is False ? Thanks, always happy to hear that :D
710
        # Wait, you've been warned !
711
        self.assertLength(1, self.warnings)
712
        self.assertEquals(
713
            'Value "<your choice>" is not a boolean for "bzr.config.expand"',
714
            self.warnings[0])
715
716
    def test_default_is_True(self):
717
        self.config = self.get_config(True)
718
        self.assertExpandIs(True)
5743.10.10 by Vincent Ladeuil
Remove spurious space
719
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
720
    def test_default_is_False(self):
721
        self.config = self.get_config(False)
722
        self.assertExpandIs(False)
5743.10.10 by Vincent Ladeuil
Remove spurious space
723
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
724
725
class TestIniConfigOptionExpansion(tests.TestCase):
726
    """Test option expansion from the IniConfig level.
727
728
    What we really want here is to test the Config level, but the class being
729
    abstract as far as storing values is concerned, this can't be done
730
    properly (yet).
731
    """
732
    # FIXME: This should be rewritten when all configs share a storage
733
    # implementation -- vila 2011-02-18
734
735
    def get_config(self, string=None):
736
        if string is None:
737
            string = ''
738
        c = config.IniBasedConfig.from_string(string)
739
        return c
740
741
    def assertExpansion(self, expected, conf, string, env=None):
742
        self.assertEquals(expected, conf.expand_options(string, env))
743
744
    def test_no_expansion(self):
745
        c = self.get_config('')
746
        self.assertExpansion('foo', c, 'foo')
747
748
    def test_env_adding_options(self):
749
        c = self.get_config('')
750
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
751
752
    def test_env_overriding_options(self):
753
        c = self.get_config('foo=baz')
754
        self.assertExpansion('bar', c, '{foo}', {'foo': 'bar'})
755
756
    def test_simple_ref(self):
757
        c = self.get_config('foo=xxx')
758
        self.assertExpansion('xxx', c, '{foo}')
759
760
    def test_unknown_ref(self):
761
        c = self.get_config('')
762
        self.assertRaises(errors.ExpandingUnknownOption,
763
                          c.expand_options, '{foo}')
764
765
    def test_indirect_ref(self):
766
        c = self.get_config('''
767
foo=xxx
768
bar={foo}
769
''')
770
        self.assertExpansion('xxx', c, '{bar}')
771
772
    def test_embedded_ref(self):
773
        c = self.get_config('''
774
foo=xxx
775
bar=foo
776
''')
777
        self.assertExpansion('xxx', c, '{{bar}}')
778
779
    def test_simple_loop(self):
780
        c = self.get_config('foo={foo}')
781
        self.assertRaises(errors.OptionExpansionLoop, c.expand_options, '{foo}')
782
783
    def test_indirect_loop(self):
784
        c = self.get_config('''
785
foo={bar}
786
bar={baz}
787
baz={foo}''')
788
        e = self.assertRaises(errors.OptionExpansionLoop,
789
                              c.expand_options, '{foo}')
790
        self.assertEquals('foo->bar->baz', e.refs)
791
        self.assertEquals('{foo}', e.string)
792
793
    def test_list(self):
794
        conf = self.get_config('''
795
foo=start
796
bar=middle
797
baz=end
798
list={foo},{bar},{baz}
799
''')
800
        self.assertEquals(['start', 'middle', 'end'],
801
                           conf.get_user_option('list', expand=True))
802
803
    def test_cascading_list(self):
804
        conf = self.get_config('''
805
foo=start,{bar}
806
bar=middle,{baz}
807
baz=end
808
list={foo}
809
''')
810
        self.assertEquals(['start', 'middle', 'end'],
811
                           conf.get_user_option('list', expand=True))
812
813
    def test_pathological_hidden_list(self):
814
        conf = self.get_config('''
815
foo=bin
816
bar=go
817
start={foo
818
middle=},{
819
end=bar}
820
hidden={start}{middle}{end}
821
''')
822
        # Nope, it's either a string or a list, and the list wins as soon as a
823
        # ',' appears, so the string concatenation never occur.
824
        self.assertEquals(['{foo', '}', '{', 'bar}'],
825
                          conf.get_user_option('hidden', expand=True))
826
827
class TestLocationConfigOptionExpansion(tests.TestCaseInTempDir):
828
829
    def get_config(self, location, string=None):
830
        if string is None:
831
            string = ''
832
        # Since we don't save the config we won't strictly require to inherit
833
        # from TestCaseInTempDir, but an error occurs so quickly...
834
        c = config.LocationConfig.from_string(string, location)
835
        return c
836
837
    def test_dont_cross_unrelated_section(self):
838
        c = self.get_config('/another/branch/path','''
839
[/one/branch/path]
840
foo = hello
841
bar = {foo}/2
842
843
[/another/branch/path]
844
bar = {foo}/2
845
''')
846
        self.assertRaises(errors.ExpandingUnknownOption,
847
                          c.get_user_option, 'bar', expand=True)
848
849
    def test_cross_related_sections(self):
850
        c = self.get_config('/project/branch/path','''
851
[/project]
852
foo = qu
853
854
[/project/branch/path]
855
bar = {foo}ux
856
''')
857
        self.assertEquals('quux', c.get_user_option('bar', expand=True))
858
859
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
860
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
861
862
    def test_cannot_reload_without_name(self):
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
863
        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.
864
        self.assertRaises(AssertionError, conf.reload)
865
866
    def test_reload_see_new_value(self):
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
867
        c1 = config.IniBasedConfig.from_string('editor=vim\n',
868
                                               file_name='./test/conf')
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
869
        c1._write_config_file()
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
870
        c2 = config.IniBasedConfig.from_string('editor=emacs\n',
871
                                               file_name='./test/conf')
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
872
        c2._write_config_file()
873
        self.assertEqual('vim', c1.get_user_option('editor'))
874
        self.assertEqual('emacs', c2.get_user_option('editor'))
875
        # Make sure we get the Right value
876
        c1.reload()
877
        self.assertEqual('emacs', c1.get_user_option('editor'))
878
879
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
880
class TestLockableConfig(tests.TestCaseInTempDir):
881
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
882
    scenarios = lockable_config_scenarios()
883
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
884
    # Set by load_tests
885
    config_class = None
886
    config_args = None
887
    config_section = None
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
888
889
    def setUp(self):
890
        super(TestLockableConfig, self).setUp()
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
891
        self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
892
        self.config = self.create_config(self._content)
893
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
894
    def get_existing_config(self):
895
        return self.config_class(*self.config_args)
896
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
897
    def create_config(self, content):
5396.1.1 by Vincent Ladeuil
Fix python-2.6-ism.
898
        kwargs = dict(save=True)
899
        c = self.config_class.from_string(content, *self.config_args, **kwargs)
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
900
        return c
901
902
    def test_simple_read_access(self):
903
        self.assertEquals('1', self.config.get_user_option('one'))
904
905
    def test_simple_write_access(self):
906
        self.config.set_user_option('one', 'one')
907
        self.assertEquals('one', self.config.get_user_option('one'))
908
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
909
    def test_listen_to_the_last_speaker(self):
910
        c1 = self.config
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
911
        c2 = self.get_existing_config()
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
912
        c1.set_user_option('one', 'ONE')
913
        c2.set_user_option('two', 'TWO')
914
        self.assertEquals('ONE', c1.get_user_option('one'))
915
        self.assertEquals('TWO', c2.get_user_option('two'))
916
        # The second update respect the first one
917
        self.assertEquals('ONE', c2.get_user_option('one'))
918
5345.5.3 by Vincent Ladeuil
Add a test for concurrent writers ensuring the values propagate.
919
    def test_last_speaker_wins(self):
920
        # If the same config is not shared, the same variable modified twice
921
        # can only see a single result.
922
        c1 = self.config
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
923
        c2 = self.get_existing_config()
5345.5.3 by Vincent Ladeuil
Add a test for concurrent writers ensuring the values propagate.
924
        c1.set_user_option('one', 'c1')
925
        c2.set_user_option('one', 'c2')
926
        self.assertEquals('c2', c2._get_user_option('one'))
927
        # The first modification is still available until another refresh
928
        # occur
929
        self.assertEquals('c1', c1._get_user_option('one'))
930
        c1.set_user_option('two', 'done')
931
        self.assertEquals('c2', c1._get_user_option('one'))
932
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
933
    def test_writes_are_serialized(self):
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
934
        c1 = self.config
935
        c2 = self.get_existing_config()
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
936
937
        # We spawn a thread that will pause *during* the write
938
        before_writing = threading.Event()
939
        after_writing = threading.Event()
940
        writing_done = threading.Event()
941
        c1_orig = c1._write_config_file
942
        def c1_write_config_file():
943
            before_writing.set()
944
            c1_orig()
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
945
            # The lock is held. We wait for the main thread to decide when to
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
946
            # continue
947
            after_writing.wait()
948
        c1._write_config_file = c1_write_config_file
949
        def c1_set_option():
950
            c1.set_user_option('one', 'c1')
951
            writing_done.set()
952
        t1 = threading.Thread(target=c1_set_option)
953
        # Collect the thread after the test
954
        self.addCleanup(t1.join)
955
        # Be ready to unblock the thread if the test goes wrong
956
        self.addCleanup(after_writing.set)
957
        t1.start()
958
        before_writing.wait()
959
        self.assertTrue(c1._lock.is_held)
960
        self.assertRaises(errors.LockContention,
961
                          c2.set_user_option, 'one', 'c2')
962
        self.assertEquals('c1', c1.get_user_option('one'))
963
        # Let the lock be released
964
        after_writing.set()
965
        writing_done.wait()
966
        c2.set_user_option('one', 'c2')
967
        self.assertEquals('c2', c2.get_user_option('one'))
968
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
969
    def test_read_while_writing(self):
970
       c1 = self.config
971
       # We spawn a thread that will pause *during* the write
972
       ready_to_write = threading.Event()
973
       do_writing = threading.Event()
974
       writing_done = threading.Event()
975
       c1_orig = c1._write_config_file
976
       def c1_write_config_file():
977
           ready_to_write.set()
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
978
           # The lock is held. We wait for the main thread to decide when to
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
979
           # continue
980
           do_writing.wait()
981
           c1_orig()
982
           writing_done.set()
983
       c1._write_config_file = c1_write_config_file
984
       def c1_set_option():
985
           c1.set_user_option('one', 'c1')
986
       t1 = threading.Thread(target=c1_set_option)
987
       # Collect the thread after the test
988
       self.addCleanup(t1.join)
989
       # Be ready to unblock the thread if the test goes wrong
990
       self.addCleanup(do_writing.set)
991
       t1.start()
992
       # Ensure the thread is ready to write
993
       ready_to_write.wait()
994
       self.assertTrue(c1._lock.is_held)
995
       self.assertEquals('c1', c1.get_user_option('one'))
996
       # If we read during the write, we get the old value
997
       c2 = self.get_existing_config()
998
       self.assertEquals('1', c2.get_user_option('one'))
999
       # Let the writing occur and ensure it occurred
1000
       do_writing.set()
1001
       writing_done.wait()
1002
       # Now we get the updated value
1003
       c3 = self.get_existing_config()
1004
       self.assertEquals('c1', c3.get_user_option('one'))
1005
5345.1.7 by Vincent Ladeuil
Start LockableConfig tests.
1006
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
1007
class TestGetUserOptionAs(TestIniConfig):
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
1008
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
1009
    def test_get_user_option_as_bool(self):
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
1010
        conf, parser = self.make_config_parser("""
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
1011
a_true_bool = true
1012
a_false_bool = 0
1013
an_invalid_bool = maybe
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
1014
a_list = hmm, who knows ? # This is interpreted as a list !
4840.2.5 by Vincent Ladeuil
Refactor get_user_option_as_* tests.
1015
""")
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
1016
        get_bool = conf.get_user_option_as_bool
1017
        self.assertEqual(True, get_bool('a_true_bool'))
1018
        self.assertEqual(False, get_bool('a_false_bool'))
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
1019
        warnings = []
1020
        def warning(*args):
1021
            warnings.append(args[0] % args[1:])
1022
        self.overrideAttr(trace, 'warning', warning)
1023
        msg = 'Value "%s" is not a boolean for "%s"'
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
1024
        self.assertIs(None, get_bool('an_invalid_bool'))
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
1025
        self.assertEquals(msg % ('maybe', 'an_invalid_bool'), warnings[0])
1026
        warnings = []
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
1027
        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.
1028
        self.assertEquals([], warnings)
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
1029
1030
    def test_get_user_option_as_list(self):
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
1031
        conf, parser = self.make_config_parser("""
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
1032
a_list = a,b,c
1033
length_1 = 1,
1034
one_item = x
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
1035
""")
1036
        get_list = conf.get_user_option_as_list
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
1037
        self.assertEqual(['a', 'b', 'c'], get_list('a_list'))
1038
        self.assertEqual(['1'], get_list('length_1'))
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
1039
        self.assertEqual('x', conf.get_user_option('one_item'))
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
1040
        # automatically cast to list
1041
        self.assertEqual(['x'], get_list('one_item'))
1042
1043
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
1044
class TestSupressWarning(TestIniConfig):
1045
1046
    def make_warnings_config(self, s):
1047
        conf, parser = self.make_config_parser(s)
1048
        return conf.suppress_warning
1049
1050
    def test_suppress_warning_unknown(self):
1051
        suppress_warning = self.make_warnings_config('')
1052
        self.assertEqual(False, suppress_warning('unknown_warning'))
1053
1054
    def test_suppress_warning_known(self):
1055
        suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
1056
        self.assertEqual(False, suppress_warning('c'))
1057
        self.assertEqual(True, suppress_warning('a'))
1058
        self.assertEqual(True, suppress_warning('b'))
1059
1060
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1061
class TestGetConfig(tests.TestCase):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1062
1063
    def test_constructs(self):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1064
        my_config = config.GlobalConfig()
1065
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
1066
    def test_calls_read_filenames(self):
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1067
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
1068
        oldparserclass = config.ConfigObj
1069
        config.ConfigObj = InstrumentedConfigObj
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1070
        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.
1071
        try:
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1072
            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.
1073
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
1074
            config.ConfigObj = oldparserclass
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1075
        self.assertIsInstance(parser, InstrumentedConfigObj)
1551.2.20 by Aaron Bentley
Treated config files as utf-8
1076
        self.assertEqual(parser._calls, [('__init__', config.config_filename(),
1077
                                          '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.
1078
1079
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1080
class TestBranchConfig(tests.TestCaseWithTransport):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1081
1082
    def test_constructs(self):
1083
        branch = FakeBranch()
1084
        my_config = config.BranchConfig(branch)
1085
        self.assertRaises(TypeError, config.BranchConfig)
1086
1087
    def test_get_location_config(self):
1088
        branch = FakeBranch()
1089
        my_config = config.BranchConfig(branch)
1090
        location_config = my_config._get_location_config()
1091
        self.assertEqual(branch.base, location_config.location)
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1092
        self.assertIs(location_config, my_config._get_location_config())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1093
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
1094
    def test_get_config(self):
1095
        """The Branch.get_config method works properly"""
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1096
        b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
1097
        my_config = b.get_config()
1098
        self.assertIs(my_config.get_user_option('wacky'), None)
1099
        my_config.set_user_option('wacky', 'unlikely')
1100
        self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
1101
1102
        # Ensure we get the same thing if we start again
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1103
        b2 = branch.Branch.open('.')
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
1104
        my_config2 = b2.get_config()
1105
        self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
1106
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
1107
    def test_has_explicit_nickname(self):
1108
        b = self.make_branch('.')
1109
        self.assertFalse(b.get_config().has_explicit_nickname())
1110
        b.nick = 'foo'
1111
        self.assertTrue(b.get_config().has_explicit_nickname())
1112
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
1113
    def test_config_url(self):
1114
        """The Branch.get_config will use section that uses a local url"""
1115
        branch = self.make_branch('branch')
1116
        self.assertEqual('branch', branch.nick)
1117
1118
        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
1119
        conf = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1120
            '[%s]\nnickname = foobar' % (local_url,),
1121
            local_url, save=True)
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
1122
        self.assertEqual('foobar', branch.nick)
1123
1124
    def test_config_local_path(self):
1125
        """The Branch.get_config will use a local system path"""
1126
        branch = self.make_branch('branch')
1127
        self.assertEqual('branch', branch.nick)
1128
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
1129
        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
1130
        conf = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1131
            '[%s/branch]\nnickname = barry' % (local_path,),
1132
            'branch',  save=True)
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
1133
        self.assertEqual('barry', branch.nick)
1134
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
1135
    def test_config_creates_local(self):
1136
        """Creating a new entry in config uses a local path."""
2230.3.6 by Aaron Bentley
work in progress bind stuff
1137
        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
1138
        branch.set_push_location('http://foobar')
1139
        local_path = osutils.getcwd().encode('utf8')
1140
        # Surprisingly ConfigObj doesn't create a trailing newline
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
1141
        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.
1142
                                 '[%s/branch]\n'
1143
                                 'push_location = http://foobar\n'
3221.7.1 by Matt Nordhoff
Upgrade ConfigObj to version 4.5.1.
1144
                                 'push_location:policy = norecurse\n'
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1145
                                 % (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
1146
2120.5.4 by Alexander Belchenko
Whitebox test for Config.get_nickname (req. by Aaron Bentley)
1147
    def test_autonick_urlencoded(self):
1148
        b = self.make_branch('!repo')
1149
        self.assertEqual('!repo', b.get_config().get_nickname())
1150
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1151
    def test_warn_if_masked(self):
1152
        warnings = []
1153
        def warning(*args):
1154
            warnings.append(args[0] % args[1:])
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
1155
        self.overrideAttr(trace, 'warning', warning)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1156
1157
        def set_option(store, warn_masked=True):
1158
            warnings[:] = []
1159
            conf.set_user_option('example_option', repr(store), store=store,
1160
                                 warn_masked=warn_masked)
1161
        def assertWarning(warning):
1162
            if warning is None:
1163
                self.assertEqual(0, len(warnings))
1164
            else:
1165
                self.assertEqual(1, len(warnings))
1166
                self.assertEqual(warning, warnings[0])
5345.1.12 by Vincent Ladeuil
Cleanup test_config some more.
1167
        branch = self.make_branch('.')
1168
        conf = branch.get_config()
1169
        set_option(config.STORE_GLOBAL)
1170
        assertWarning(None)
1171
        set_option(config.STORE_BRANCH)
1172
        assertWarning(None)
1173
        set_option(config.STORE_GLOBAL)
1174
        assertWarning('Value "4" is masked by "3" from branch.conf')
1175
        set_option(config.STORE_GLOBAL, warn_masked=False)
1176
        assertWarning(None)
1177
        set_option(config.STORE_LOCATION)
1178
        assertWarning(None)
1179
        set_option(config.STORE_BRANCH)
1180
        assertWarning('Value "3" is masked by "0" from locations.conf')
1181
        set_option(config.STORE_BRANCH, warn_masked=False)
1182
        assertWarning(None)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1183
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1184
5448.1.1 by Vincent Ladeuil
Use TestCaseInTempDir for tests requiring disk resources
1185
class TestGlobalConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1186
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
1187
    def test_user_id(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1188
        my_config = config.GlobalConfig.from_string(sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
1189
        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
1190
                         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.
1191
1192
    def test_absent_user_id(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1193
        my_config = config.GlobalConfig()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1194
        self.assertEqual(None, my_config._get_user_id())
1195
1196
    def test_configured_editor(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1197
        my_config = config.GlobalConfig.from_string(sample_config_text)
5743.13.1 by Vincent Ladeuil
Deprecate _get_editor to identify its usages.
1198
        editor = self.applyDeprecated(
1199
            deprecated_in((2, 4, 0)), my_config.get_editor)
1200
        self.assertEqual('vim', editor)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1201
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
1202
    def test_signatures_always(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1203
        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
1204
        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
1205
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1206
        self.assertEqual(config.SIGN_ALWAYS,
1207
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
1208
        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
1209
1210
    def test_signatures_if_possible(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1211
        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
1212
        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
1213
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1214
        self.assertEqual(config.SIGN_WHEN_REQUIRED,
1215
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
1216
        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
1217
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1218
    def test_signatures_ignore(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1219
        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
1220
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1221
                         my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1222
        self.assertEqual(config.SIGN_NEVER,
1223
                         my_config.signing_policy())
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
1224
        self.assertEqual(False, my_config.signature_needed())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1225
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1226
    def _get_sample_config(self):
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1227
        my_config = config.GlobalConfig.from_string(sample_config_text)
1534.7.154 by Aaron Bentley
Removed changes from bzr.ab 1529..1536
1228
        return my_config
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1229
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1230
    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.
1231
        my_config = self._get_sample_config()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1232
        self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
1233
        self.assertEqual(False, my_config.signature_needed())
1234
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1235
    def _get_empty_config(self):
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1236
        my_config = config.GlobalConfig()
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1237
        return my_config
1238
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
1239
    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.
1240
        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.
1241
        self.assertEqual("gpg", my_config.gpg_signing_command())
1242
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1243
    def test_get_user_option_default(self):
1244
        my_config = self._get_empty_config()
1245
        self.assertEqual(None, my_config.get_user_option('no_option'))
1246
1247
    def test_get_user_option_global(self):
1248
        my_config = self._get_sample_config()
1249
        self.assertEqual("something",
1250
                         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.
1251
1472 by Robert Collins
post commit hook, first pass implementation
1252
    def test_post_commit_default(self):
1253
        my_config = self._get_sample_config()
1254
        self.assertEqual(None, my_config.post_commit())
1255
1553.2.9 by Erik BÃ¥gfors
log_formatter => log_format for "named" formatters
1256
    def test_configured_logformat(self):
1553.2.8 by Erik BÃ¥gfors
tests for config log_formatter
1257
        my_config = self._get_sample_config()
1553.2.9 by Erik BÃ¥gfors
log_formatter => log_format for "named" formatters
1258
        self.assertEqual("short", my_config.log_format())
1553.2.8 by Erik BÃ¥gfors
tests for config log_formatter
1259
1553.6.12 by Erik BÃ¥gfors
remove AliasConfig, based on input from abentley
1260
    def test_get_alias(self):
1261
        my_config = self._get_sample_config()
1262
        self.assertEqual('help', my_config.get_alias('h'))
1263
2900.3.6 by Tim Penhey
Added tests.
1264
    def test_get_aliases(self):
1265
        my_config = self._get_sample_config()
1266
        aliases = my_config.get_aliases()
1267
        self.assertEqual(2, len(aliases))
1268
        sorted_keys = sorted(aliases)
1269
        self.assertEqual('help', aliases[sorted_keys[0]])
1270
        self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
1271
1553.6.12 by Erik BÃ¥gfors
remove AliasConfig, based on input from abentley
1272
    def test_get_no_alias(self):
1273
        my_config = self._get_sample_config()
1274
        self.assertEqual(None, my_config.get_alias('foo'))
1275
1276
    def test_get_long_alias(self):
1277
        my_config = self._get_sample_config()
1278
        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.
1279
4603.1.10 by Aaron Bentley
Provide change editor via config.
1280
    def test_get_change_editor(self):
1281
        my_config = self._get_sample_config()
1282
        change_editor = my_config.get_change_editor('old', 'new')
1283
        self.assertIs(diff.DiffFromTool, change_editor.__class__)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
1284
        self.assertEqual('vimdiff -of @new_path @old_path',
4603.1.10 by Aaron Bentley
Provide change editor via config.
1285
                         ' '.join(change_editor.command_template))
1286
1287
    def test_get_no_change_editor(self):
1288
        my_config = self._get_empty_config()
1289
        change_editor = my_config.get_change_editor('old', 'new')
1290
        self.assertIs(None, change_editor)
1291
5321.1.89 by Gordon Tyler
Moved mergetools config tests to bzrlib.tests.test_config.
1292
    def test_get_merge_tools(self):
1293
        conf = self._get_sample_config()
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1294
        tools = conf.get_merge_tools()
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
1295
        self.log(repr(tools))
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1296
        self.assertEqual(
1297
            {u'funkytool' : u'funkytool "arg with spaces" {this_temp}',
1298
            u'sometool' : u'sometool {base} {this} {other} -o {result}'},
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
1299
            tools)
5321.1.89 by Gordon Tyler
Moved mergetools config tests to bzrlib.tests.test_config.
1300
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1301
    def test_get_merge_tools_empty(self):
5321.1.93 by Gordon Tyler
Added tests for get_default_merge_tool.
1302
        conf = self._get_empty_config()
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1303
        tools = conf.get_merge_tools()
1304
        self.assertEqual({}, tools)
5321.1.103 by Gordon Tyler
Renamed _find_merge_tool back to find_merge_tool since it must be public for UI code to lookup merge tools by name, and added tests for it.
1305
1306
    def test_find_merge_tool(self):
1307
        conf = self._get_sample_config()
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1308
        cmdline = conf.find_merge_tool('sometool')
1309
        self.assertEqual('sometool {base} {this} {other} -o {result}', cmdline)
5321.1.103 by Gordon Tyler
Renamed _find_merge_tool back to find_merge_tool since it must be public for UI code to lookup merge tools by name, and added tests for it.
1310
1311
    def test_find_merge_tool_not_found(self):
1312
        conf = self._get_sample_config()
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1313
        cmdline = conf.find_merge_tool('DOES NOT EXIST')
1314
        self.assertIs(cmdline, None)
5321.1.93 by Gordon Tyler
Added tests for get_default_merge_tool.
1315
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
1316
    def test_find_merge_tool_known(self):
1317
        conf = self._get_empty_config()
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1318
        cmdline = conf.find_merge_tool('kdiff3')
1319
        self.assertEquals('kdiff3 {base} {this} {other} -o {result}', cmdline)
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
1320
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
1321
    def test_find_merge_tool_override_known(self):
1322
        conf = self._get_empty_config()
5321.1.112 by Gordon Tyler
Removed set_merge_tool, remove_merge_tool and set_default_merge_tool from Config.
1323
        conf.set_user_option('bzr.mergetool.kdiff3', 'kdiff3 blah')
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
1324
        cmdline = conf.find_merge_tool('kdiff3')
1325
        self.assertEqual('kdiff3 blah', cmdline)
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
1326
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1327
2900.3.6 by Tim Penhey
Added tests.
1328
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
1329
1330
    def test_empty(self):
1331
        my_config = config.GlobalConfig()
1332
        self.assertEqual(0, len(my_config.get_aliases()))
1333
1334
    def test_set_alias(self):
1335
        my_config = config.GlobalConfig()
1336
        alias_value = 'commit --strict'
1337
        my_config.set_alias('commit', alias_value)
1338
        new_config = config.GlobalConfig()
1339
        self.assertEqual(alias_value, new_config.get_alias('commit'))
1340
1341
    def test_remove_alias(self):
1342
        my_config = config.GlobalConfig()
1343
        my_config.set_alias('commit', 'commit --strict')
1344
        # Now remove the alias again.
1345
        my_config.unset_alias('commit')
1346
        new_config = config.GlobalConfig()
1347
        self.assertIs(None, new_config.get_alias('commit'))
1348
1349
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1350
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1351
1352
    def test_constructs(self):
1353
        my_config = config.LocationConfig('http://example.com')
1354
        self.assertRaises(TypeError, config.LocationConfig)
1355
1356
    def test_branch_calls_read_filenames(self):
1474 by Robert Collins
Merge from Aaron Bentley.
1357
        # This is testing the correct file names are provided.
1358
        # TODO: consolidate with the test for GlobalConfigs filename checks.
1359
        #
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1360
        # replace the class that is constructed, to check its parameters
1474 by Robert Collins
Merge from Aaron Bentley.
1361
        oldparserclass = config.ConfigObj
1362
        config.ConfigObj = InstrumentedConfigObj
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1363
        try:
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1364
            my_config = config.LocationConfig('http://www.example.com')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1365
            parser = my_config._get_parser()
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1366
        finally:
1474 by Robert Collins
Merge from Aaron Bentley.
1367
            config.ConfigObj = oldparserclass
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1368
        self.assertIsInstance(parser, InstrumentedConfigObj)
1474 by Robert Collins
Merge from Aaron Bentley.
1369
        self.assertEqual(parser._calls,
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1370
                         [('__init__', config.locations_config_filename(),
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1371
                           'utf-8')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1372
1373
    def test_get_global_config(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1374
        my_config = config.BranchConfig(FakeBranch('http://example.com'))
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1375
        global_config = my_config._get_global_config()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1376
        self.assertIsInstance(global_config, config.GlobalConfig)
1377
        self.assertIs(global_config, my_config._get_global_config())
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1378
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1379
    def assertLocationMatching(self, expected):
1380
        self.assertEqual(expected,
1381
                         list(self.my_location_config._get_matching_sections()))
1382
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1383
    def test__get_matching_sections_no_match(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1384
        self.get_branch_config('/')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1385
        self.assertLocationMatching([])
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1386
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1387
    def test__get_matching_sections_exact(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1388
        self.get_branch_config('http://www.example.com')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1389
        self.assertLocationMatching([('http://www.example.com', '')])
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1390
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1391
    def test__get_matching_sections_suffix_does_not(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1392
        self.get_branch_config('http://www.example.com-com')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1393
        self.assertLocationMatching([])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1394
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1395
    def test__get_matching_sections_subdir_recursive(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1396
        self.get_branch_config('http://www.example.com/com')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1397
        self.assertLocationMatching([('http://www.example.com', 'com')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1398
1993.3.5 by James Henstridge
add back recurse=False option to config file
1399
    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
1400
        self.get_branch_config('http://www.example.com/ignoreparent')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1401
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1402
                                      '')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1403
1993.3.5 by James Henstridge
add back recurse=False option to config file
1404
    def test__get_matching_sections_ignoreparent_subdir(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1405
        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
1406
            'http://www.example.com/ignoreparent/childbranch')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1407
        self.assertLocationMatching([('http://www.example.com/ignoreparent',
1408
                                      'childbranch')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1409
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1410
    def test__get_matching_sections_subdir_trailing_slash(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1411
        self.get_branch_config('/b')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1412
        self.assertLocationMatching([('/b/', '')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1413
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1414
    def test__get_matching_sections_subdir_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1415
        self.get_branch_config('/a/foo')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1416
        self.assertLocationMatching([('/a/*', ''), ('/a/', 'foo')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1417
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1418
    def test__get_matching_sections_subdir_child_child(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1419
        self.get_branch_config('/a/foo/bar')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1420
        self.assertLocationMatching([('/a/*', 'bar'), ('/a/', 'foo/bar')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1421
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1422
    def test__get_matching_sections_trailing_slash_with_children(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1423
        self.get_branch_config('/a/')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1424
        self.assertLocationMatching([('/a/', '')])
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1425
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1426
    def test__get_matching_sections_explicit_over_glob(self):
1427
        # XXX: 2006-09-08 jamesh
1428
        # This test only passes because ord('c') > ord('*').  If there
1429
        # was a config section for '/a/?', it would get precedence
1430
        # over '/a/c'.
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1431
        self.get_branch_config('/a/c')
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1432
        self.assertLocationMatching([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')])
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1433
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
1434
    def test__get_option_policy_normal(self):
1435
        self.get_branch_config('http://www.example.com')
1436
        self.assertEqual(
1437
            self.my_location_config._get_config_policy(
1438
            'http://www.example.com', 'normal_option'),
1439
            config.POLICY_NONE)
1440
1441
    def test__get_option_policy_norecurse(self):
1442
        self.get_branch_config('http://www.example.com')
1443
        self.assertEqual(
1444
            self.my_location_config._get_option_policy(
1445
            'http://www.example.com', 'norecurse_option'),
1446
            config.POLICY_NORECURSE)
1447
        # Test old recurse=False setting:
1448
        self.assertEqual(
1449
            self.my_location_config._get_option_policy(
1450
            'http://www.example.com/norecurse', 'normal_option'),
1451
            config.POLICY_NORECURSE)
1452
1453
    def test__get_option_policy_normal(self):
1454
        self.get_branch_config('http://www.example.com')
1455
        self.assertEqual(
1456
            self.my_location_config._get_option_policy(
1457
            'http://www.example.com', 'appendpath_option'),
1458
            config.POLICY_APPENDPATH)
1459
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1460
    def test__get_options_with_policy(self):
1461
        self.get_branch_config('/dir/subdir',
1462
                               location_config="""\
1463
[/dir]
1464
other_url = /other-dir
1465
other_url:policy = appendpath
1466
[/dir/subdir]
1467
other_url = /other-subdir
1468
""")
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1469
        self.assertOptions(
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1470
            [(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
1471
             (u'other_url', u'/other-dir', u'/dir', 'locations'),
1472
             (u'other_url:policy', u'appendpath', u'/dir', 'locations')],
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1473
            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.
1474
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1475
    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
1476
        self.get_branch_config('http://www.example.com/ignoreparent')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1477
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1478
                         self.my_config.username())
1479
1480
    def test_location_not_listed(self):
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1481
        """Test that the global username is used when no location matches"""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1482
        self.get_branch_config('/home/robertc/sources')
1704.2.18 by Martin Pool
Remove duplicated TestLocationConfig and update previously hidden tests. (#32587)
1483
        self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
1442.1.8 by Robert Collins
preparing some tests for LocationConfig
1484
                         self.my_config.username())
1485
1442.1.13 by Robert Collins
branches.conf is now able to override the users email
1486
    def test_overriding_location(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1487
        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
1488
        self.assertEqual('Robert Collins <robertc@example.org>',
1489
                         self.my_config.username())
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1490
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1491
    def test_signatures_not_set(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1492
        self.get_branch_config('http://www.example.com',
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1493
                                 global_config=sample_ignore_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1494
        self.assertEqual(config.CHECK_ALWAYS,
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1495
                         self.my_config.signature_checking())
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1496
        self.assertEqual(config.SIGN_NEVER,
1497
                         self.my_config.signing_policy())
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1498
1499
    def test_signatures_never(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1500
        self.get_branch_config('/a/c')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1501
        self.assertEqual(config.CHECK_NEVER,
1502
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1503
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
1504
    def test_signatures_when_available(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1505
        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
1506
        self.assertEqual(config.CHECK_IF_POSSIBLE,
1507
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1508
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1509
    def test_signatures_always(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1510
        self.get_branch_config('/b')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1511
        self.assertEqual(config.CHECK_ALWAYS,
1512
                         self.my_config.signature_checking())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1513
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1514
    def test_gpg_signing_command(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1515
        self.get_branch_config('/b')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1516
        self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
1517
1518
    def test_gpg_signing_command_missing(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1519
        self.get_branch_config('/a')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1520
        self.assertEqual("false", self.my_config.gpg_signing_command())
1521
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1522
    def test_get_user_option_global(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1523
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1524
        self.assertEqual('something',
1525
                         self.my_config.get_user_option('user_global_option'))
1526
1527
    def test_get_user_option_local(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1528
        self.get_branch_config('/a')
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1529
        self.assertEqual('local',
1530
                         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
1531
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
1532
    def test_get_user_option_appendpath(self):
1533
        # returned as is for the base path:
1534
        self.get_branch_config('http://www.example.com')
1535
        self.assertEqual('append',
1536
                         self.my_config.get_user_option('appendpath_option'))
1537
        # Extra path components get appended:
1538
        self.get_branch_config('http://www.example.com/a/b/c')
1539
        self.assertEqual('append/a/b/c',
1540
                         self.my_config.get_user_option('appendpath_option'))
1541
        # Overriden for http://www.example.com/dir, where it is a
1542
        # normal option:
1543
        self.get_branch_config('http://www.example.com/dir/a/b/c')
1544
        self.assertEqual('normal',
1545
                         self.my_config.get_user_option('appendpath_option'))
1546
1547
    def test_get_user_option_norecurse(self):
1548
        self.get_branch_config('http://www.example.com')
1549
        self.assertEqual('norecurse',
1550
                         self.my_config.get_user_option('norecurse_option'))
1551
        self.get_branch_config('http://www.example.com/dir')
1552
        self.assertEqual(None,
1553
                         self.my_config.get_user_option('norecurse_option'))
1554
        # http://www.example.com/norecurse is a recurse=False section
1555
        # that redefines normal_option.  Subdirectories do not pick up
1556
        # this redefinition.
1557
        self.get_branch_config('http://www.example.com/norecurse')
1558
        self.assertEqual('norecurse',
1559
                         self.my_config.get_user_option('normal_option'))
1560
        self.get_branch_config('http://www.example.com/norecurse/subdir')
1561
        self.assertEqual('normal',
1562
                         self.my_config.get_user_option('normal_option'))
1563
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1564
    def test_set_user_option_norecurse(self):
1565
        self.get_branch_config('http://www.example.com')
1566
        self.my_config.set_user_option('foo', 'bar',
1567
                                       store=config.STORE_LOCATION_NORECURSE)
1568
        self.assertEqual(
1569
            self.my_location_config._get_option_policy(
1570
            'http://www.example.com', 'foo'),
1571
            config.POLICY_NORECURSE)
1572
1573
    def test_set_user_option_appendpath(self):
1574
        self.get_branch_config('http://www.example.com')
1575
        self.my_config.set_user_option('foo', 'bar',
1576
                                       store=config.STORE_LOCATION_APPENDPATH)
1577
        self.assertEqual(
1578
            self.my_location_config._get_option_policy(
1579
            'http://www.example.com', 'foo'),
1580
            config.POLICY_APPENDPATH)
1581
1582
    def test_set_user_option_change_policy(self):
1583
        self.get_branch_config('http://www.example.com')
1584
        self.my_config.set_user_option('norecurse_option', 'normal',
1585
                                       store=config.STORE_LOCATION)
1586
        self.assertEqual(
1587
            self.my_location_config._get_option_policy(
1588
            'http://www.example.com', 'norecurse_option'),
1589
            config.POLICY_NONE)
1590
1591
    def test_set_user_option_recurse_false_section(self):
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1592
        # The following section has recurse=False set.  The test is to
1593
        # make sure that a normal option can be added to the section,
1594
        # converting recurse=False to the norecurse policy.
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1595
        self.get_branch_config('http://www.example.com/norecurse')
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
1596
        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
1597
                             'The section "http://www.example.com/norecurse" '
1598
                             'has been converted to use policies.'],
1599
                            self.my_config.set_user_option,
1600
                            'foo', 'bar', store=config.STORE_LOCATION)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1601
        self.assertEqual(
1602
            self.my_location_config._get_option_policy(
1603
            'http://www.example.com/norecurse', 'foo'),
1604
            config.POLICY_NONE)
1605
        # The previously existing option is still norecurse:
1606
        self.assertEqual(
1607
            self.my_location_config._get_option_policy(
1608
            'http://www.example.com/norecurse', 'normal_option'),
1609
            config.POLICY_NORECURSE)
1610
1472 by Robert Collins
post commit hook, first pass implementation
1611
    def test_post_commit_default(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1612
        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
1613
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1614
                         self.my_config.post_commit())
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1615
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
1616
    def get_branch_config(self, location, global_config=None,
1617
                          location_config=None):
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1618
        my_branch = FakeBranch(location)
1502 by Robert Collins
Bugfix the config test suite to not create .bazaar in the dir where it is run.
1619
        if global_config is None:
5345.2.2 by Vincent Ladeuil
Simplify test config building.
1620
            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.
1621
        if location_config is None:
1622
            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.
1623
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1624
        my_global_config = config.GlobalConfig.from_string(global_config,
1625
                                                           save=True)
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1626
        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.
1627
            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.
1628
        my_config = config.BranchConfig(my_branch)
1629
        self.my_config = my_config
1630
        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.
1631
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1632
    def test_set_user_setting_sets_and_saves(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1633
        self.get_branch_config('/a/c')
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1634
        record = InstrumentedConfigObj("foo")
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1635
        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
1636
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
1637
        self.callDeprecated(['The recurse option is deprecated as of '
1638
                             '0.14.  The section "/a/c" has been '
1639
                             'converted to use policies.'],
1640
                            self.my_config.set_user_option,
1641
                            'foo', 'bar', store=config.STORE_LOCATION)
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
1642
        self.assertEqual([('reload',),
1643
                          ('__contains__', '/a/c'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1644
                          ('__contains__', '/a/c/'),
1645
                          ('__setitem__', '/a/c', {}),
1646
                          ('__getitem__', '/a/c'),
1647
                          ('__setitem__', 'foo', 'bar'),
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1648
                          ('__getitem__', '/a/c'),
1649
                          ('as_bool', 'recurse'),
1650
                          ('__getitem__', '/a/c'),
1651
                          ('__delitem__', 'recurse'),
1652
                          ('__getitem__', '/a/c'),
1653
                          ('keys',),
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1654
                          ('__getitem__', '/a/c'),
1655
                          ('__contains__', 'foo:policy'),
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1656
                          ('write',)],
1657
                         record._calls[1:])
1658
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1659
    def test_set_user_setting_sets_and_saves2(self):
1660
        self.get_branch_config('/a/c')
1661
        self.assertIs(self.my_config.get_user_option('foo'), None)
1662
        self.my_config.set_user_option('foo', 'bar')
1663
        self.assertEqual(
3616.2.6 by Mark Hammond
Fix test_set_user_setting_sets_and_saves2 on windows by stripping EOL
1664
            self.my_config.branch.control_files.files['branch.conf'].strip(),
1665
            'foo = bar')
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1666
        self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1667
        self.my_config.set_user_option('foo', 'baz',
1668
                                       store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1669
        self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
1670
        self.my_config.set_user_option('foo', 'qux')
1671
        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.
1672
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1673
    def test_get_bzr_remote_path(self):
1674
        my_config = config.LocationConfig('/a/c')
1675
        self.assertEqual('bzr', my_config.get_bzr_remote_path())
1676
        my_config.set_user_option('bzr_remote_path', '/path-bzr')
1677
        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.
1678
        self.overrideEnv('BZR_REMOTE_PATH', '/environ-bzr')
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1679
        self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
1680
1185.62.7 by John Arbash Meinel
Whitespace cleanup.
1681
1770.2.8 by Aaron Bentley
Add precedence test
1682
precedence_global = 'option = global'
1683
precedence_branch = 'option = branch'
1684
precedence_location = """
1685
[http://]
1686
recurse = true
1687
option = recurse
1688
[http://example.com/specific]
1689
option = exact
1690
"""
1691
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1692
class TestBranchConfigItems(tests.TestCaseInTempDir):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1693
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1694
    def get_branch_config(self, global_config=None, location=None,
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1695
                          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.
1696
        my_branch = FakeBranch(location)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1697
        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
1698
            my_global_config = config.GlobalConfig.from_string(global_config,
1699
                                                               save=True)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1700
        if location_config is not None:
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1701
            my_location_config = config.LocationConfig.from_string(
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1702
                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.
1703
        my_config = config.BranchConfig(my_branch)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1704
        if branch_data_config is not None:
1705
            my_config.branch.control_files.files['branch.conf'] = \
1706
                branch_data_config
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1707
        return my_config
1708
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1709
    def test_user_id(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1710
        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
1711
        my_config = config.BranchConfig(branch)
1712
        self.assertEqual("Robert Collins <robertc@example.net>",
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1713
                         my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1714
        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.
1715
        my_config.set_user_option('email',
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1716
                                  "Robert Collins <robertc@example.org>")
1717
        self.assertEqual("John", my_config.username())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1718
        del my_config.branch.control_files.files['email']
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1719
        self.assertEqual("Robert Collins <robertc@example.org>",
1720
                         my_config.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1721
1722
    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.
1723
        my_config = self.get_branch_config(global_config=sample_config_text)
1551.2.21 by Aaron Bentley
Formatted unicode config tests as ASCII
1724
        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
1725
                         my_config._get_user_id())
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
1726
        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
1727
        self.assertEqual("John", my_config._get_user_id())
1728
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
1729
    def test_BZR_EMAIL_OVERRIDES(self):
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
1730
        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
1731
        branch = FakeBranch()
1732
        my_config = config.BranchConfig(branch)
1733
        self.assertEqual("Robert Collins <robertc@example.org>",
1734
                         my_config.username())
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1735
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1736
    def test_signatures_forced(self):
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1737
        my_config = self.get_branch_config(
1738
            global_config=sample_always_signatures)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1739
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1740
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1741
        self.assertTrue(my_config.signature_needed())
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1742
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1743
    def test_signatures_forced_branch(self):
1744
        my_config = self.get_branch_config(
1745
            global_config=sample_ignore_signatures,
1746
            branch_data_config=sample_always_signatures)
1747
        self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
1748
        self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
1749
        self.assertTrue(my_config.signature_needed())
1750
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1751
    def test_gpg_signing_command(self):
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1752
        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.
1753
            global_config=sample_config_text,
1770.2.10 by Aaron Bentley
Added test that branch_config can't influence gpg_signing_command
1754
            # branch data cannot set gpg_signing_command
1755
            branch_data_config="gpg_signing_command=pgp")
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1756
        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.
1757
1758
    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.
1759
        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.
1760
        self.assertEqual('something',
1761
                         my_config.get_user_option('user_global_option'))
1472 by Robert Collins
post commit hook, first pass implementation
1762
1763
    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.
1764
        my_config = self.get_branch_config(global_config=sample_config_text,
1765
                                      location='/a/c',
1766
                                      location_config=sample_branches_text)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1767
        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
1768
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1472 by Robert Collins
post commit hook, first pass implementation
1769
                         my_config.post_commit())
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1770
        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.
1771
        # post-commit is ignored when present in branch data
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1772
        self.assertEqual('bzrlib.tests.test_config.post_commit',
1773
                         my_config.post_commit())
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1774
        my_config.set_user_option('post_commit', 'rmtree_root',
1775
                                  store=config.STORE_LOCATION)
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1776
        self.assertEqual('rmtree_root', my_config.post_commit())
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1777
1770.2.8 by Aaron Bentley
Add precedence test
1778
    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.
1779
        # FIXME: eager test, luckily no persitent config file makes it fail
1780
        # -- vila 20100716
1770.2.8 by Aaron Bentley
Add precedence test
1781
        my_config = self.get_branch_config(global_config=precedence_global)
1782
        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.
1783
        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.
1784
                                           branch_data_config=precedence_branch)
1770.2.8 by Aaron Bentley
Add precedence test
1785
        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.
1786
        my_config = self.get_branch_config(
1787
            global_config=precedence_global,
1788
            branch_data_config=precedence_branch,
1789
            location_config=precedence_location)
1770.2.8 by Aaron Bentley
Add precedence test
1790
        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.
1791
        my_config = self.get_branch_config(
1792
            global_config=precedence_global,
1793
            branch_data_config=precedence_branch,
1794
            location_config=precedence_location,
1795
            location='http://example.com/specific')
1770.2.8 by Aaron Bentley
Add precedence test
1796
        self.assertEqual(my_config.get_user_option('option'), 'exact')
1797
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
1798
    def test_get_mail_client(self):
1799
        config = self.get_branch_config()
1800
        client = config.get_mail_client()
2681.1.24 by Aaron Bentley
Handle default mail client by trying xdg-email, falling back to editor
1801
        self.assertIsInstance(client, mail_client.DefaultMail)
1802
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1803
        # Specific clients
2681.1.21 by Aaron Bentley
Refactor prompt generation to make it testable, test it with unicode
1804
        config.set_user_option('mail_client', 'evolution')
1805
        client = config.get_mail_client()
1806
        self.assertIsInstance(client, mail_client.Evolution)
1807
2681.5.1 by ghigo
Add KMail support to bzr send
1808
        config.set_user_option('mail_client', 'kmail')
1809
        client = config.get_mail_client()
1810
        self.assertIsInstance(client, mail_client.KMail)
1811
2790.2.1 by Keir Mierle
Add Mutt as a supported client email program. Also rearranges various listings
1812
        config.set_user_option('mail_client', 'mutt')
1813
        client = config.get_mail_client()
1814
        self.assertIsInstance(client, mail_client.Mutt)
1815
1816
        config.set_user_option('mail_client', 'thunderbird')
1817
        client = config.get_mail_client()
1818
        self.assertIsInstance(client, mail_client.Thunderbird)
1819
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
1820
        # Generic options
1821
        config.set_user_option('mail_client', 'default')
1822
        client = config.get_mail_client()
1823
        self.assertIsInstance(client, mail_client.DefaultMail)
1824
1825
        config.set_user_option('mail_client', 'editor')
1826
        client = config.get_mail_client()
1827
        self.assertIsInstance(client, mail_client.Editor)
1828
1829
        config.set_user_option('mail_client', 'mapi')
1830
        client = config.get_mail_client()
1831
        self.assertIsInstance(client, mail_client.MAPIClient)
1832
2681.1.23 by Aaron Bentley
Add support for xdg-email
1833
        config.set_user_option('mail_client', 'xdg-email')
1834
        client = config.get_mail_client()
1835
        self.assertIsInstance(client, mail_client.XDGEmail)
1836
2681.1.10 by Aaron Bentley
Clean up handling of unknown mail clients
1837
        config.set_user_option('mail_client', 'firebird')
1838
        self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
1839
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1840
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1841
class TestMailAddressExtraction(tests.TestCase):
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1842
1843
    def test_extract_email_address(self):
1844
        self.assertEqual('jane@test.com',
1845
                         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
1846
        self.assertRaises(errors.NoEmailInUsername,
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
1847
                          config.extract_email_address, 'Jane Tester')
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1848
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1849
    def test_parse_username(self):
1850
        self.assertEqual(('', 'jdoe@example.com'),
1851
                         config.parse_username('jdoe@example.com'))
1852
        self.assertEqual(('', 'jdoe@example.com'),
1853
                         config.parse_username('<jdoe@example.com>'))
1854
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1855
                         config.parse_username('John Doe <jdoe@example.com>'))
1856
        self.assertEqual(('John Doe', ''),
1857
                         config.parse_username('John Doe'))
3063.3.3 by Lukáš Lalinský
Add one more test for config.parse_username().
1858
        self.assertEqual(('John Doe', 'jdoe@example.com'),
1859
                         config.parse_username('John Doe jdoe@example.com'))
2562.1.2 by John Arbash Meinel
Clean up whitespace
1860
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1861
class TestTreeConfig(tests.TestCaseWithTransport):
2533.1.1 by James Westby
Fix TreeConfig to return values from sections.
1862
1863
    def test_get_value(self):
1864
        """Test that retreiving a value from a section is possible"""
1865
        branch = self.make_branch('.')
1866
        tree_config = config.TreeConfig(branch)
1867
        tree_config.set_option('value', 'key', 'SECTION')
1868
        tree_config.set_option('value2', 'key2')
1869
        tree_config.set_option('value3-top', 'key3')
1870
        tree_config.set_option('value3-section', 'key3', 'SECTION')
1871
        value = tree_config.get_option('key', 'SECTION')
1872
        self.assertEqual(value, 'value')
1873
        value = tree_config.get_option('key2')
1874
        self.assertEqual(value, 'value2')
1875
        self.assertEqual(tree_config.get_option('non-existant'), None)
1876
        value = tree_config.get_option('non-existant', 'SECTION')
1877
        self.assertEqual(value, None)
1878
        value = tree_config.get_option('non-existant', default='default')
1879
        self.assertEqual(value, 'default')
1880
        self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
1881
        value = tree_config.get_option('key2', 'NOSECTION', default='default')
1882
        self.assertEqual(value, 'default')
1883
        value = tree_config.get_option('key3')
1884
        self.assertEqual(value, 'value3-top')
1885
        value = tree_config.get_option('key3', 'SECTION')
1886
        self.assertEqual(value, 'value3-section')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1887
1888
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1889
class TestTransportConfig(tests.TestCaseWithTransport):
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1890
1891
    def test_get_value(self):
1892
        """Test that retreiving a value from a section is possible"""
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1893
        bzrdir_config = config.TransportConfig(transport.get_transport('.'),
1894
                                               'control.conf')
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1895
        bzrdir_config.set_option('value', 'key', 'SECTION')
1896
        bzrdir_config.set_option('value2', 'key2')
1897
        bzrdir_config.set_option('value3-top', 'key3')
1898
        bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
1899
        value = bzrdir_config.get_option('key', 'SECTION')
1900
        self.assertEqual(value, 'value')
1901
        value = bzrdir_config.get_option('key2')
1902
        self.assertEqual(value, 'value2')
1903
        self.assertEqual(bzrdir_config.get_option('non-existant'), None)
1904
        value = bzrdir_config.get_option('non-existant', 'SECTION')
1905
        self.assertEqual(value, None)
1906
        value = bzrdir_config.get_option('non-existant', default='default')
1907
        self.assertEqual(value, 'default')
1908
        self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
1909
        value = bzrdir_config.get_option('key2', 'NOSECTION',
1910
                                         default='default')
1911
        self.assertEqual(value, 'default')
1912
        value = bzrdir_config.get_option('key3')
1913
        self.assertEqual(value, 'value3-top')
1914
        value = bzrdir_config.get_option('key3', 'SECTION')
1915
        self.assertEqual(value, 'value3-section')
1916
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1917
    def test_set_unset_default_stack_on(self):
1918
        my_dir = self.make_bzrdir('.')
4288.1.3 by Robert Collins
Fix BzrDirConfig tests.
1919
        bzrdir_config = config.BzrDirConfig(my_dir)
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1920
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1921
        bzrdir_config.set_default_stack_on('Foo')
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1922
        self.assertEqual('Foo', bzrdir_config._config.get_option(
1923
                         'default_stack_on'))
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1924
        self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
1925
        bzrdir_config.set_default_stack_on(None)
1926
        self.assertIs(None, bzrdir_config.get_default_stack_on())
1927
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1928
5743.12.4 by Vincent Ladeuil
An option can provide a default value.
1929
class TestOption(tests.TestCase):
1930
1931
    def test_default_value(self):
1932
        opt = config.Option('foo', default='bar')
1933
        self.assertEquals('bar', opt.get_default())
5743.12.5 by Vincent Ladeuil
Remove spurious spaces.
1934
5743.12.4 by Vincent Ladeuil
An option can provide a default value.
1935
5743.12.2 by Vincent Ladeuil
Basic registry for options.
1936
class TestOptionRegistry(tests.TestCase):
5743.12.5 by Vincent Ladeuil
Remove spurious spaces.
1937
5743.12.2 by Vincent Ladeuil
Basic registry for options.
1938
    def setUp(self):
1939
        super(TestOptionRegistry, self).setUp()
1940
        # Always start with an empty registry
1941
        self.overrideAttr(config, 'option_registry', registry.Registry())
1942
        self.registry = config.option_registry
1943
1944
    def test_register(self):
1945
        opt = config.Option('foo')
1946
        self.registry.register('foo', opt)
1947
        self.assertIs(opt, self.registry.get('foo'))
1948
1949
    lazy_option = config.Option('lazy_foo')
1950
1951
    def test_register_lazy(self):
1952
        self.registry.register_lazy('foo', self.__module__,
1953
                                    'TestOptionRegistry.lazy_option')
1954
        self.assertIs(self.lazy_option, self.registry.get('foo'))
1955
5743.12.3 by Vincent Ladeuil
More basic tests for options. Start tests for all registered options.
1956
    def test_registered_help(self):
1957
        opt = config.Option('foo')
1958
        self.registry.register('foo', opt, help='A simple option')
1959
        self.assertEquals('A simple option', self.registry.get_help('foo'))
1960
1961
1962
class TestRegisteredOptions(tests.TestCase):
1963
    """All registered options should verify some constraints."""
1964
1965
    scenarios = [(key, {'option_name': key, 'option': option}) for key, option
1966
                 in config.option_registry.iteritems()]
1967
1968
    def setUp(self):
1969
        super(TestRegisteredOptions, self).setUp()
1970
        self.registry = config.option_registry
1971
1972
    def test_proper_name(self):
1973
        # An option should be registered under its own name, this can't be
1974
        # checked at registration time for the lazy ones.
1975
        self.assertEquals(self.option_name, self.option.name)
1976
1977
    def test_help_is_set(self):
1978
        option_help = self.registry.get_help(self.option_name)
1979
        self.assertNotEquals(None, option_help)
1980
        # Come on, think about the user, he really wants to know whst the
1981
        # option is about
1982
        self.assertNotEquals('', option_help)
1983
5743.12.2 by Vincent Ladeuil
Basic registry for options.
1984
5743.3.12 by Vincent Ladeuil
Add an ad-hoc __repr__.
1985
class TestSection(tests.TestCase):
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
1986
1987
    # FIXME: Parametrize so that all sections produced by Stores run these
5743.3.1 by Vincent Ladeuil
Add a docstring and dates to FIXMEs.
1988
    # tests -- vila 2011-04-01
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
1989
1990
    def test_get_a_value(self):
1991
        a_dict = dict(foo='bar')
5743.3.11 by Vincent Ladeuil
Config sections only implement read access.
1992
        section = config.Section('myID', a_dict)
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
1993
        self.assertEquals('bar', section.get('foo'))
1994
5743.3.10 by Vincent Ladeuil
Fix typos mentioned in reviews.
1995
    def test_get_unknown_option(self):
5743.2.2 by Vincent Ladeuil
Add tests for remove.
1996
        a_dict = dict()
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
1997
        section = config.Section(None, a_dict)
5743.2.2 by Vincent Ladeuil
Add tests for remove.
1998
        self.assertEquals('out of thin air',
1999
                          section.get('foo', 'out of thin air'))
2000
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2001
    def test_options_is_shared(self):
2002
        a_dict = dict()
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
2003
        section = config.Section(None, a_dict)
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2004
        self.assertIs(a_dict, section.options)
2005
2006
5743.3.12 by Vincent Ladeuil
Add an ad-hoc __repr__.
2007
class TestMutableSection(tests.TestCase):
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2008
5743.4.20 by Vincent Ladeuil
Fix typo.
2009
    # FIXME: Parametrize so that all sections (including os.environ and the
5743.3.1 by Vincent Ladeuil
Add a docstring and dates to FIXMEs.
2010
    # ones produced by Stores) run these tests -- vila 2011-04-01
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2011
2012
    def test_set(self):
2013
        a_dict = dict(foo='bar')
2014
        section = config.MutableSection('myID', a_dict)
2015
        section.set('foo', 'new_value')
2016
        self.assertEquals('new_value', section.get('foo'))
2017
        # The change appears in the shared section
2018
        self.assertEquals('new_value', a_dict.get('foo'))
2019
        # We keep track of the change
2020
        self.assertTrue('foo' in section.orig)
2021
        self.assertEquals('bar', section.orig.get('foo'))
2022
2023
    def test_set_preserve_original_once(self):
2024
        a_dict = dict(foo='bar')
2025
        section = config.MutableSection('myID', a_dict)
2026
        section.set('foo', 'first_value')
2027
        section.set('foo', 'second_value')
2028
        # We keep track of the original value
2029
        self.assertTrue('foo' in section.orig)
2030
        self.assertEquals('bar', section.orig.get('foo'))
2031
5743.2.2 by Vincent Ladeuil
Add tests for remove.
2032
    def test_remove(self):
2033
        a_dict = dict(foo='bar')
2034
        section = config.MutableSection('myID', a_dict)
2035
        section.remove('foo')
2036
        # We get None for unknown options via the default value
2037
        self.assertEquals(None, section.get('foo'))
2038
        # Or we just get the default value
2039
        self.assertEquals('unknown', section.get('foo', 'unknown'))
2040
        self.assertFalse('foo' in section.options)
2041
        # We keep track of the deletion
2042
        self.assertTrue('foo' in section.orig)
2043
        self.assertEquals('bar', section.orig.get('foo'))
2044
2045
    def test_remove_new_option(self):
2046
        a_dict = dict()
2047
        section = config.MutableSection('myID', a_dict)
2048
        section.set('foo', 'bar')
2049
        section.remove('foo')
2050
        self.assertFalse('foo' in section.options)
2051
        # The option didn't exist initially so it we need to keep track of it
2052
        # with a special value
2053
        self.assertTrue('foo' in section.orig)
5743.3.6 by Vincent Ladeuil
Use a name less likely to be reused.
2054
        self.assertEquals(config._NewlyCreatedOption, section.orig['foo'])
5743.2.2 by Vincent Ladeuil
Add tests for remove.
2055
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2056
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2057
class TestStore(tests.TestCaseWithTransport):
2058
2059
    def assertSectionContent(self, expected, section):
2060
        """Assert that some options have the proper values in a section."""
2061
        expected_name, expected_options = expected
2062
        self.assertEquals(expected_name, section.id)
2063
        self.assertEquals(
2064
            expected_options,
2065
            dict([(k, section.get(k)) for k in expected_options.keys()]))
2066
2067
2068
class TestReadonlyStore(TestStore):
2069
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2070
    scenarios = [(key, {'get_store': builder}) for key, builder
2071
                 in config.test_store_builder_registry.iteritems()]
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2072
2073
    def setUp(self):
2074
        super(TestReadonlyStore, self).setUp()
2075
2076
    def test_building_delays_load(self):
2077
        store = self.get_store(self)
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2078
        self.assertEquals(False, store.is_loaded())
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2079
        store._load_from_string('')
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2080
        self.assertEquals(True, store.is_loaded())
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2081
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2082
    def test_get_no_sections_for_empty(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2083
        store = self.get_store(self)
2084
        store._load_from_string('')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2085
        self.assertEquals([], list(store.get_sections()))
2086
2087
    def test_get_default_section(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2088
        store = self.get_store(self)
2089
        store._load_from_string('foo=bar')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2090
        sections = list(store.get_sections())
2091
        self.assertLength(1, sections)
2092
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2093
2094
    def test_get_named_section(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2095
        store = self.get_store(self)
2096
        store._load_from_string('[baz]\nfoo=bar')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2097
        sections = list(store.get_sections())
2098
        self.assertLength(1, sections)
2099
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2100
5743.4.21 by Vincent Ladeuil
All stores should provide _load_from_string to reuse the existing tests.
2101
    def test_load_from_string_fails_for_non_empty_store(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2102
        store = self.get_store(self)
2103
        store._load_from_string('foo=bar')
5743.4.21 by Vincent Ladeuil
All stores should provide _load_from_string to reuse the existing tests.
2104
        self.assertRaises(AssertionError, store._load_from_string, 'bar=baz')
2105
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2106
2107
class TestMutableStore(TestStore):
2108
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2109
    scenarios = [(key, {'store_id': key, 'get_store': builder}) for key, builder
2110
                 in config.test_store_builder_registry.iteritems()]
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2111
2112
    def setUp(self):
2113
        super(TestMutableStore, self).setUp()
2114
        self.transport = self.get_transport()
2115
2116
    def has_store(self, store):
2117
        store_basename = urlutils.relative_url(self.transport.external_url(),
2118
                                               store.external_url())
2119
        return self.transport.has(store_basename)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2120
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2121
    def test_save_empty_creates_no_file(self):
5743.10.4 by Vincent Ladeuil
Add FIXME.
2122
        # FIXME: There should be a better way than relying on the test
2123
        # parametrization to identify branch.conf -- vila 2011-0526
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
2124
        if self.store_id in ('branch', 'remote_branch'):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2125
            raise tests.TestNotApplicable(
2126
                'branch.conf is *always* created when a branch is initialized')
2127
        store = self.get_store(self)
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2128
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2129
        self.assertEquals(False, self.has_store(store))
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2130
2131
    def test_save_emptied_succeeds(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2132
        store = self.get_store(self)
2133
        store._load_from_string('foo=bar\n')
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2134
        section = store.get_mutable_section(None)
2135
        section.remove('foo')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2136
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2137
        self.assertEquals(True, self.has_store(store))
2138
        modified_store = self.get_store(self)
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2139
        sections = list(modified_store.get_sections())
2140
        self.assertLength(0, sections)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2141
2142
    def test_save_with_content_succeeds(self):
5743.10.4 by Vincent Ladeuil
Add FIXME.
2143
        # FIXME: There should be a better way than relying on the test
2144
        # parametrization to identify branch.conf -- vila 2011-0526
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
2145
        if self.store_id in ('branch', 'remote_branch'):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2146
            raise tests.TestNotApplicable(
2147
                'branch.conf is *always* created when a branch is initialized')
2148
        store = self.get_store(self)
2149
        store._load_from_string('foo=bar\n')
2150
        self.assertEquals(False, self.has_store(store))
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2151
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2152
        self.assertEquals(True, self.has_store(store))
2153
        modified_store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2154
        sections = list(modified_store.get_sections())
2155
        self.assertLength(1, sections)
2156
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2157
2158
    def test_set_option_in_empty_store(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2159
        store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2160
        section = store.get_mutable_section(None)
2161
        section.set('foo', 'bar')
2162
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2163
        modified_store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2164
        sections = list(modified_store.get_sections())
2165
        self.assertLength(1, sections)
2166
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2167
2168
    def test_set_option_in_default_section(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2169
        store = self.get_store(self)
2170
        store._load_from_string('')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2171
        section = store.get_mutable_section(None)
2172
        section.set('foo', 'bar')
2173
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2174
        modified_store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2175
        sections = list(modified_store.get_sections())
2176
        self.assertLength(1, sections)
2177
        self.assertSectionContent((None, {'foo': 'bar'}), sections[0])
2178
2179
    def test_set_option_in_named_section(self):
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2180
        store = self.get_store(self)
2181
        store._load_from_string('')
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2182
        section = store.get_mutable_section('baz')
2183
        section.set('foo', 'bar')
2184
        store.save()
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2185
        modified_store = self.get_store(self)
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2186
        sections = list(modified_store.get_sections())
2187
        self.assertLength(1, sections)
2188
        self.assertSectionContent(('baz', {'foo': 'bar'}), sections[0])
2189
2190
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2191
class TestIniFileStore(TestStore):
5743.4.6 by Vincent Ladeuil
Parametrize Store tests and isolate the ConfigObjStore specific ones.
2192
5743.4.3 by Vincent Ladeuil
Implement get_mutable_section.
2193
    def test_loading_unknown_file_fails(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2194
        store = config.IniFileStore(self.get_transport(), 'I-do-not-exist')
5743.4.3 by Vincent Ladeuil
Implement get_mutable_section.
2195
        self.assertRaises(errors.NoSuchFile, store.load)
2196
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2197
    def test_invalid_content(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2198
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
2199
        self.assertEquals(False, store.is_loaded())
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
2200
        exc = self.assertRaises(
2201
            errors.ParseConfigError, store._load_from_string,
2202
            'this is invalid !')
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2203
        self.assertEndsWith(exc.filename, 'foo.conf')
2204
        # And the load failed
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2205
        self.assertEquals(False, store.is_loaded())
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2206
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2207
    def test_get_embedded_sections(self):
5743.2.11 by Vincent Ladeuil
Basic store.set implementation.
2208
        # A more complicated example (which also shows that section names and
2209
        # option names share the same name space...)
5743.4.7 by Vincent Ladeuil
The test is now specific to ConfigObjStore and highlight a pending problem there.
2210
        # FIXME: This should be fixed by forbidding dicts as values ?
2211
        # -- vila 2011-04-05
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2212
        store = config.IniFileStore(self.get_transport(), 'foo.conf', )
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
2213
        store._load_from_string('''
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2214
foo=bar
2215
l=1,2
2216
[DEFAULT]
2217
foo_in_DEFAULT=foo_DEFAULT
2218
[bar]
2219
foo_in_bar=barbar
2220
[baz]
2221
foo_in_baz=barbaz
2222
[[qux]]
2223
foo_in_qux=quux
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
2224
''')
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2225
        sections = list(store.get_sections())
2226
        self.assertLength(4, sections)
2227
        # The default section has no name.
2228
        # List values are provided as lists
5743.4.1 by Vincent Ladeuil
Use proper ReadOnly sections in ConfigObjStore.get_sections().
2229
        self.assertSectionContent((None, {'foo': 'bar', 'l': ['1', '2']}),
2230
                                  sections[0])
2231
        self.assertSectionContent(
2232
            ('DEFAULT', {'foo_in_DEFAULT': 'foo_DEFAULT'}), sections[1])
2233
        self.assertSectionContent(
2234
            ('bar', {'foo_in_bar': 'barbar'}), sections[2])
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2235
        # sub sections are provided as embedded dicts.
5743.4.1 by Vincent Ladeuil
Use proper ReadOnly sections in ConfigObjStore.get_sections().
2236
        self.assertSectionContent(
2237
            ('baz', {'foo_in_baz': 'barbaz', 'qux': {'foo_in_qux': 'quux'}}),
2238
            sections[3])
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2239
5743.4.5 by Vincent Ladeuil
Split store tests between readonly and mutable ones.
2240
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2241
class TestLockableIniFileStore(TestStore):
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2242
2243
    def test_create_store_in_created_dir(self):
5743.6.21 by Vincent Ladeuil
Tighten the test.
2244
        self.assertPathDoesNotExist('dir')
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2245
        t = self.get_transport('dir/subdir')
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2246
        store = config.LockableIniFileStore(t, 'foo.conf')
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2247
        store.get_mutable_section(None).set('foo', 'bar')
2248
        store.save()
5743.6.21 by Vincent Ladeuil
Tighten the test.
2249
        self.assertPathExists('dir/subdir')
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2250
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2251
5743.10.5 by Vincent Ladeuil
Give up.
2252
class TestBranchStore(TestStore):
2253
2254
    def test_dead_branch(self):
2255
        build_backing_branch(self, 'branch')
2256
        b = branch.Branch.open('branch')
2257
        store = config.BranchStore(b)
2258
        del b
2259
        # The only reliable way to trigger the error is to explicitly call the
2260
        # garbage collector.
2261
        import gc
2262
        gc.collect()
2263
        store.get_mutable_section(None).set('foo', 'bar')
2264
        self.assertRaises(AssertionError, store.save)
2265
2266
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2267
class TestConcurrentStoreUpdates(TestStore):
5743.10.13 by Vincent Ladeuil
Mention that the the concurrent update tests are not targeted at *all* Store implementations.
2268
    """Test that Stores properly handle conccurent updates.
2269
2270
    New Store implementation may fail some of these tests but until such
2271
    implementations exist it's hard to properly filter them from the scenarios
2272
    applied here. If you encounter such a case, contact the bzr devs.
2273
    """
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2274
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2275
    scenarios = [(key, {'get_stack': builder}) for key, builder
2276
                 in config.test_stack_builder_registry.iteritems()]
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2277
2278
    def setUp(self):
2279
        super(TestConcurrentStoreUpdates, self).setUp()
2280
        self._content = 'one=1\ntwo=2\n'
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2281
        self.stack = self.get_stack(self)
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2282
        if not isinstance(self.stack, config._CompatibleStack):
2283
            raise tests.TestNotApplicable(
2284
                '%s is not meant to be compatible with the old config design'
2285
                % (self.stack,))
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2286
        self.stack.store._load_from_string(self._content)
2287
        # Flush the store
2288
        self.stack.store.save()
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2289
2290
    def test_simple_read_access(self):
2291
        self.assertEquals('1', self.stack.get('one'))
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2292
5743.6.22 by Vincent Ladeuil
Start writing tests for lockable stores.
2293
    def test_simple_write_access(self):
2294
        self.stack.set('one', 'one')
2295
        self.assertEquals('one', self.stack.get('one'))
2296
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2297
    def test_listen_to_the_last_speaker(self):
2298
        c1 = self.stack
2299
        c2 = self.get_stack(self)
2300
        c1.set('one', 'ONE')
2301
        c2.set('two', 'TWO')
2302
        self.assertEquals('ONE', c1.get('one'))
2303
        self.assertEquals('TWO', c2.get('two'))
2304
        # The second update respect the first one
2305
        self.assertEquals('ONE', c2.get('one'))
2306
2307
    def test_last_speaker_wins(self):
2308
        # If the same config is not shared, the same variable modified twice
2309
        # can only see a single result.
2310
        c1 = self.stack
2311
        c2 = self.get_stack(self)
2312
        c1.set('one', 'c1')
2313
        c2.set('one', 'c2')
2314
        self.assertEquals('c2', c2.get('one'))
2315
        # The first modification is still available until another refresh
2316
        # occur
2317
        self.assertEquals('c1', c1.get('one'))
2318
        c1.set('two', 'done')
2319
        self.assertEquals('c2', c1.get('one'))
2320
5743.6.24 by Vincent Ladeuil
One more test with a ugly hack to allow the test to stop in the right place.
2321
    def test_writes_are_serialized(self):
2322
        c1 = self.stack
2323
        c2 = self.get_stack(self)
2324
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2325
        # We spawn a thread that will pause *during* the config saving.
5743.6.24 by Vincent Ladeuil
One more test with a ugly hack to allow the test to stop in the right place.
2326
        before_writing = threading.Event()
2327
        after_writing = threading.Event()
2328
        writing_done = threading.Event()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2329
        c1_save_without_locking_orig = c1.store.save_without_locking
2330
        def c1_save_without_locking():
5743.6.24 by Vincent Ladeuil
One more test with a ugly hack to allow the test to stop in the right place.
2331
            before_writing.set()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2332
            c1_save_without_locking_orig()
5743.6.24 by Vincent Ladeuil
One more test with a ugly hack to allow the test to stop in the right place.
2333
            # The lock is held. We wait for the main thread to decide when to
2334
            # continue
2335
            after_writing.wait()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2336
        c1.store.save_without_locking = c1_save_without_locking
5743.6.24 by Vincent Ladeuil
One more test with a ugly hack to allow the test to stop in the right place.
2337
        def c1_set():
2338
            c1.set('one', 'c1')
2339
            writing_done.set()
2340
        t1 = threading.Thread(target=c1_set)
2341
        # Collect the thread after the test
2342
        self.addCleanup(t1.join)
2343
        # Be ready to unblock the thread if the test goes wrong
2344
        self.addCleanup(after_writing.set)
2345
        t1.start()
2346
        before_writing.wait()
2347
        self.assertRaises(errors.LockContention,
2348
                          c2.set, 'one', 'c2')
2349
        self.assertEquals('c1', c1.get('one'))
2350
        # Let the lock be released
2351
        after_writing.set()
2352
        writing_done.wait()
2353
        c2.set('one', 'c2')
2354
        self.assertEquals('c2', c2.get('one'))
2355
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2356
    def test_read_while_writing(self):
2357
       c1 = self.stack
2358
       # We spawn a thread that will pause *during* the write
2359
       ready_to_write = threading.Event()
2360
       do_writing = threading.Event()
2361
       writing_done = threading.Event()
2362
       # We override the _save implementation so we know the store is locked
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2363
       c1_save_without_locking_orig = c1.store.save_without_locking
2364
       def c1_save_without_locking():
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2365
           ready_to_write.set()
2366
           # The lock is held. We wait for the main thread to decide when to
2367
           # continue
2368
           do_writing.wait()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2369
           c1_save_without_locking_orig()
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2370
           writing_done.set()
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2371
       c1.store.save_without_locking = c1_save_without_locking
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2372
       def c1_set():
2373
           c1.set('one', 'c1')
2374
       t1 = threading.Thread(target=c1_set)
2375
       # Collect the thread after the test
2376
       self.addCleanup(t1.join)
2377
       # Be ready to unblock the thread if the test goes wrong
2378
       self.addCleanup(do_writing.set)
2379
       t1.start()
2380
       # Ensure the thread is ready to write
2381
       ready_to_write.wait()
2382
       self.assertEquals('c1', c1.get('one'))
2383
       # If we read during the write, we get the old value
2384
       c2 = self.get_stack(self)
2385
       self.assertEquals('1', c2.get('one'))
2386
       # Let the writing occur and ensure it occurred
2387
       do_writing.set()
2388
       writing_done.wait()
2389
       # Now we get the updated value
2390
       c3 = self.get_stack(self)
2391
       self.assertEquals('c1', c3.get('one'))
2392
2393
    # FIXME: It may be worth looking into removing the lock dir when it's not
2394
    # needed anymore and look at possible fallouts for concurrent lockers. This
2395
    # will matter if/when we use config files outside of bazaar directories
2396
    # (.bazaar or .bzr) -- vila 20110-04-11
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2397
2398
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2399
class TestSectionMatcher(TestStore):
2400
2401
    scenarios = [('location', {'matcher': config.LocationMatcher})]
2402
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2403
    def get_store(self, file_name):
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2404
        return config.IniFileStore(self.get_readonly_transport(), file_name)
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2405
2406
    def test_no_matches_for_empty_stores(self):
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2407
        store = self.get_store('foo.conf')
2408
        store._load_from_string('')
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2409
        matcher = self.matcher(store, '/bar')
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2410
        self.assertEquals([], list(matcher.get_sections()))
2411
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2412
    def test_build_doesnt_load_store(self):
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2413
        store = self.get_store('foo.conf')
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2414
        matcher = self.matcher(store, '/bar')
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2415
        self.assertFalse(store.is_loaded())
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2416
2417
2418
class TestLocationSection(tests.TestCase):
2419
2420
    def get_section(self, options, extra_path):
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2421
        section = config.Section('foo', options)
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2422
        # We don't care about the length so we use '0'
2423
        return config.LocationSection(section, 0, extra_path)
2424
2425
    def test_simple_option(self):
2426
        section = self.get_section({'foo': 'bar'}, '')
2427
        self.assertEquals('bar', section.get('foo'))
2428
2429
    def test_option_with_extra_path(self):
2430
        section = self.get_section({'foo': 'bar', 'foo:policy': 'appendpath'},
2431
                                   'baz')
2432
        self.assertEquals('bar/baz', section.get('foo'))
2433
2434
    def test_invalid_policy(self):
2435
        section = self.get_section({'foo': 'bar', 'foo:policy': 'die'},
2436
                                   'baz')
2437
        # invalid policies are ignored
2438
        self.assertEquals('bar', section.get('foo'))
2439
2440
2441
class TestLocationMatcher(TestStore):
2442
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2443
    def get_store(self, file_name):
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2444
        return config.IniFileStore(self.get_readonly_transport(), file_name)
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2445
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2446
    def test_more_specific_sections_first(self):
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2447
        store = self.get_store('foo.conf')
2448
        store._load_from_string('''
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2449
[/foo]
2450
section=/foo
2451
[/foo/bar]
2452
section=/foo/bar
5743.2.33 by Vincent Ladeuil
Stop using get_ConfigObjStore.
2453
''')
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2454
        self.assertEquals(['/foo', '/foo/bar'],
2455
                          [section.id for section in store.get_sections()])
2456
        matcher = config.LocationMatcher(store, '/foo/bar/baz')
2457
        sections = list(matcher.get_sections())
2458
        self.assertEquals([3, 2],
2459
                          [section.length for section in sections])
2460
        self.assertEquals(['/foo/bar', '/foo'],
2461
                          [section.id for section in sections])
2462
        self.assertEquals(['baz', 'bar/baz'],
2463
                          [section.extra_path for section in sections])
2464
5743.6.18 by Vincent Ladeuil
Add a test for appendpath support in no-name section.
2465
    def test_appendpath_in_no_name_section(self):
2466
        # It's a bit weird to allow appendpath in a no-name section, but
2467
        # someone may found a use for it
2468
        store = self.get_store('foo.conf')
2469
        store._load_from_string('''
2470
foo=bar
2471
foo:policy = appendpath
2472
''')
2473
        matcher = config.LocationMatcher(store, 'dir/subdir')
2474
        sections = list(matcher.get_sections())
2475
        self.assertLength(1, sections)
2476
        self.assertEquals('bar/dir/subdir', sections[0].get('foo'))
2477
5743.6.19 by Vincent Ladeuil
Clarify comments about section names for Location-related objects (also fix LocationMatcher and add tests).
2478
    def test_file_urls_are_normalized(self):
2479
        store = self.get_store('foo.conf')
5912.3.1 by Vincent Ladeuil
Fix spurious windows-specific test failure
2480
        if sys.platform == 'win32':
2481
            expected_url = 'file:///C:/dir/subdir'
2482
            expected_location = 'C:/dir/subdir'
2483
        else:
2484
            expected_url = 'file:///dir/subdir'
2485
            expected_location = '/dir/subdir'
2486
        matcher = config.LocationMatcher(store, expected_url)
2487
        self.assertEquals(expected_location, matcher.location)
5743.6.19 by Vincent Ladeuil
Clarify comments about section names for Location-related objects (also fix LocationMatcher and add tests).
2488
5743.1.20 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
2489
5743.1.35 by Vincent Ladeuil
Address some review comments from jelmer and poolie.
2490
class TestStackGet(tests.TestCase):
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2491
5743.1.35 by Vincent Ladeuil
Address some review comments from jelmer and poolie.
2492
    # FIXME: This should be parametrized for all known Stack or dedicated
5743.1.3 by Vincent Ladeuil
Don't forget to parametrized for people *providing* new stacks.
2493
    # paramerized tests created to avoid bloating -- vila 2011-03-31
2494
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2495
    def test_single_config_get(self):
2496
        conf = dict(foo='bar')
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
2497
        conf_stack = config.Stack([conf])
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2498
        self.assertEquals('bar', conf_stack.get('foo'))
2499
5743.12.7 by Vincent Ladeuil
Test that providing a default value doesn't break for non-registered options.
2500
    def test_get_with_registered_default_value(self):
5743.12.6 by Vincent Ladeuil
Stack.get() provides the registered option default value.
2501
        conf_stack = config.Stack([dict()])
2502
        opt = config.Option('foo', default='bar')
2503
        self.overrideAttr(config, 'option_registry', registry.Registry())
2504
        config.option_registry.register('foo', opt)
2505
        self.assertEquals('bar', conf_stack.get('foo'))
2506
5743.12.7 by Vincent Ladeuil
Test that providing a default value doesn't break for non-registered options.
2507
    def test_get_without_registered_default_value(self):
2508
        conf_stack = config.Stack([dict()])
2509
        opt = config.Option('foo')
2510
        self.overrideAttr(config, 'option_registry', registry.Registry())
2511
        config.option_registry.register('foo', opt)
2512
        self.assertEquals(None, conf_stack.get('foo'))
2513
2514
    def test_get_without_default_value_for_not_registered(self):
2515
        conf_stack = config.Stack([dict()])
2516
        opt = config.Option('foo')
2517
        self.overrideAttr(config, 'option_registry', registry.Registry())
2518
        self.assertEquals(None, conf_stack.get('foo'))
2519
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2520
    def test_get_first_definition(self):
2521
        conf1 = dict(foo='bar')
2522
        conf2 = dict(foo='baz')
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
2523
        conf_stack = config.Stack([conf1, conf2])
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2524
        self.assertEquals('bar', conf_stack.get('foo'))
2525
5743.1.2 by Vincent Ladeuil
Stacks can be used as read-only sections.
2526
    def test_get_embedded_definition(self):
2527
        conf1 = dict(yy='12')
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
2528
        conf2 = config.Stack([dict(xx='42'), dict(foo='baz')])
2529
        conf_stack = config.Stack([conf1, conf2])
5743.1.2 by Vincent Ladeuil
Stacks can be used as read-only sections.
2530
        self.assertEquals('baz', conf_stack.get('foo'))
2531
5743.1.16 by Vincent Ladeuil
Allows empty sections and empty section callables.
2532
    def test_get_for_empty_stack(self):
5743.1.36 by Vincent Ladeuil
Clarify that constructor parameters are here to *define* the stack and as such can be re-used. Also make the sections_def parameter mandatory.
2533
        conf_stack = config.Stack([])
5743.1.16 by Vincent Ladeuil
Allows empty sections and empty section callables.
2534
        self.assertEquals(None, conf_stack.get('foo'))
2535
2536
    def test_get_for_empty_section_callable(self):
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
2537
        conf_stack = config.Stack([lambda : []])
5743.1.16 by Vincent Ladeuil
Allows empty sections and empty section callables.
2538
        self.assertEquals(None, conf_stack.get('foo'))
2539
5743.1.35 by Vincent Ladeuil
Address some review comments from jelmer and poolie.
2540
    def test_get_for_broken_callable(self):
2541
        # Trying to use and invalid callable raises an exception on first use
2542
        conf_stack = config.Stack([lambda : object()])
2543
        self.assertRaises(TypeError, conf_stack.get, 'foo')
2544
2545
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2546
class TestStackWithTransport(tests.TestCaseWithTransport):
2547
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2548
    scenarios = [(key, {'get_stack': builder}) for key, builder
2549
                 in config.test_stack_builder_registry.iteritems()]
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2550
2551
5743.11.1 by Vincent Ladeuil
Add a note about config store builders being called several times by some tests.
2552
class TestConcreteStacks(TestStackWithTransport):
2553
2554
    def test_build_stack(self):
2555
        # Just a smoke test to help debug builders
2556
        stack = self.get_stack(self)
2557
2558
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2559
class TestStackSet(TestStackWithTransport):
2560
5743.1.7 by Vincent Ladeuil
Simple set implementation.
2561
    def test_simple_set(self):
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2562
        conf = self.get_stack(self)
2563
        conf.store._load_from_string('foo=bar')
5743.1.7 by Vincent Ladeuil
Simple set implementation.
2564
        self.assertEquals('bar', conf.get('foo'))
2565
        conf.set('foo', 'baz')
2566
        # Did we get it back ?
2567
        self.assertEquals('baz', conf.get('foo'))
2568
5743.1.8 by Vincent Ladeuil
Damn, the sections can't be pre-loaded or need to be reloaded on modifications or even better lazily iterated instead.
2569
    def test_set_creates_a_new_section(self):
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2570
        conf = self.get_stack(self)
5743.1.8 by Vincent Ladeuil
Damn, the sections can't be pre-loaded or need to be reloaded on modifications or even better lazily iterated instead.
2571
        conf.set('foo', 'baz')
5743.1.9 by Vincent Ladeuil
Fix the issue by allowing delayed section acquisition.
2572
        self.assertEquals, 'baz', conf.get('foo')
5743.1.8 by Vincent Ladeuil
Damn, the sections can't be pre-loaded or need to be reloaded on modifications or even better lazily iterated instead.
2573
5743.1.7 by Vincent Ladeuil
Simple set implementation.
2574
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2575
class TestStackRemove(TestStackWithTransport):
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
2576
2577
    def test_remove_existing(self):
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2578
        conf = self.get_stack(self)
2579
        conf.store._load_from_string('foo=bar')
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
2580
        self.assertEquals('bar', conf.get('foo'))
2581
        conf.remove('foo')
2582
        # Did we get it back ?
2583
        self.assertEquals(None, conf.get('foo'))
2584
2585
    def test_remove_unknown(self):
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2586
        conf = self.get_stack(self)
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
2587
        self.assertRaises(KeyError, conf.remove, 'I_do_not_exist')
2588
2589
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
2590
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
2591
2592
    def setUp(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2593
        super(TestConfigGetOptions, self).setUp()
2594
        create_configs(self)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
2595
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
2596
    def test_no_variable(self):
2597
        # 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.
2598
        self.assertOptions([], self.branch_config)
2599
2600
    def test_option_in_bazaar(self):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2601
        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.
2602
        self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2603
                           self.bazaar_config)
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
2604
2605
    def test_option_in_locations(self):
2606
        self.locations_config.set_user_option('file', 'locations')
2607
        self.assertOptions(
2608
            [('file', 'locations', self.tree.basedir, 'locations')],
2609
            self.locations_config)
2610
2611
    def test_option_in_branch(self):
2612
        self.branch_config.set_user_option('file', 'branch')
2613
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
2614
                           self.branch_config)
2615
2616
    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.
2617
        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.
2618
        self.branch_config.set_user_option('file', 'branch')
2619
        self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
2620
                            ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
2621
                           self.branch_config)
2622
2623
    def test_option_in_branch_and_locations(self):
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
2624
        # Hmm, locations override branch :-/
2625
        self.locations_config.set_user_option('file', 'locations')
2626
        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.
2627
        self.assertOptions(
2628
            [('file', 'locations', self.tree.basedir, 'locations'),
2629
             ('file', 'branch', 'DEFAULT', 'branch'),],
2630
            self.branch_config)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
2631
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
2632
    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.
2633
        self.bazaar_config.set_user_option('file', 'bazaar')
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
2634
        self.locations_config.set_user_option('file', 'locations')
2635
        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.
2636
        self.assertOptions(
2637
            [('file', 'locations', self.tree.basedir, 'locations'),
2638
             ('file', 'branch', 'DEFAULT', 'branch'),
2639
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
2640
            self.branch_config)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
2641
2642
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
2643
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2644
2645
    def setUp(self):
2646
        super(TestConfigRemoveOption, self).setUp()
2647
        create_configs_with_file_option(self)
2648
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
2649
    def test_remove_in_locations(self):
2650
        self.locations_config.remove_user_option('file', self.tree.basedir)
2651
        self.assertOptions(
2652
            [('file', 'branch', 'DEFAULT', 'branch'),
2653
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
2654
            self.branch_config)
2655
2656
    def test_remove_in_branch(self):
2657
        self.branch_config.remove_user_option('file')
2658
        self.assertOptions(
2659
            [('file', 'locations', self.tree.basedir, 'locations'),
2660
             ('file', 'bazaar', 'DEFAULT', 'bazaar'),],
2661
            self.branch_config)
2662
2663
    def test_remove_in_bazaar(self):
2664
        self.bazaar_config.remove_user_option('file')
2665
        self.assertOptions(
2666
            [('file', 'locations', self.tree.basedir, 'locations'),
2667
             ('file', 'branch', 'DEFAULT', 'branch'),],
2668
            self.branch_config)
2669
5447.4.7 by Vincent Ladeuil
Check error message if the test is checking for errors or we have unexpected success for wrong errors.
2670
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2671
class TestConfigGetSections(tests.TestCaseWithTransport):
2672
2673
    def setUp(self):
2674
        super(TestConfigGetSections, self).setUp()
2675
        create_configs(self)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
2676
2677
    def assertSectionNames(self, expected, conf, name=None):
2678
        """Check which sections are returned for a given config.
2679
2680
        If fallback configurations exist their sections can be included.
2681
2682
        :param expected: A list of section names.
2683
2684
        :param conf: The configuration that will be queried.
2685
2686
        :param name: An optional section name that will be passed to
2687
            get_sections().
2688
        """
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.
2689
        sections = list(conf._get_sections(name))
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
2690
        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.
2691
        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.
2692
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2693
    def test_bazaar_default_section(self):
2694
        self.assertSectionNames(['DEFAULT'], self.bazaar_config)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
2695
2696
    def test_locations_default_section(self):
2697
        # No sections are defined in an empty file
2698
        self.assertSectionNames([], self.locations_config)
2699
2700
    def test_locations_named_section(self):
2701
        self.locations_config.set_user_option('file', 'locations')
2702
        self.assertSectionNames([self.tree.basedir], self.locations_config)
2703
2704
    def test_locations_matching_sections(self):
2705
        loc_config = self.locations_config
2706
        loc_config.set_user_option('file', 'locations')
2707
        # We need to cheat a bit here to create an option in sections above and
2708
        # below the 'location' one.
2709
        parser = loc_config._get_parser()
2710
        # locations.cong deals with '/' ignoring native os.sep
2711
        location_names = self.tree.basedir.split('/')
2712
        parent = '/'.join(location_names[:-1])
2713
        child = '/'.join(location_names + ['child'])
2714
        parser[parent] = {}
2715
        parser[parent]['file'] = 'parent'
2716
        parser[child] = {}
2717
        parser[child]['file'] = 'child'
2718
        self.assertSectionNames([self.tree.basedir, parent], loc_config)
2719
2720
    def test_branch_data_default_section(self):
2721
        self.assertSectionNames([None],
2722
                                self.branch_config._get_branch_data_config())
2723
2724
    def test_branch_default_sections(self):
2725
        # No sections are defined in an empty locations file
2726
        self.assertSectionNames([None, 'DEFAULT'],
2727
                                self.branch_config)
2728
        # Unless we define an option
2729
        self.branch_config._get_location_config().set_user_option(
2730
            'file', 'locations')
2731
        self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
2732
                                self.branch_config)
2733
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2734
    def test_bazaar_named_section(self):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
2735
        # We need to cheat as the API doesn't give direct access to sections
2736
        # other than DEFAULT.
5447.4.6 by Vincent Ladeuil
Start defining fixtures but we still have an unexpected sucessful test.
2737
        self.bazaar_config.set_alias('bazaar', 'bzr')
2738
        self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
2739
2740
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
2741
class TestAuthenticationConfigFile(tests.TestCase):
2900.2.14 by Vincent Ladeuil
More tests.
2742
    """Test the authentication.conf file matching"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2743
2744
    def _got_user_passwd(self, expected_user, expected_password,
2745
                         config, *args, **kwargs):
2746
        credentials = config.get_credentials(*args, **kwargs)
2747
        if credentials is None:
2748
            user = None
2749
            password = None
2750
        else:
2751
            user = credentials['user']
2752
            password = credentials['password']
2753
        self.assertEquals(expected_user, user)
2754
        self.assertEquals(expected_password, password)
2755
2978.5.1 by John Arbash Meinel
Fix bug #162494, 'bzr register-branch' needs proper auth handling.
2756
    def test_empty_config(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2757
        conf = config.AuthenticationConfig(_file=StringIO())
2758
        self.assertEquals({}, conf._get_config())
2759
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
2760
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
2761
    def test_missing_auth_section_header(self):
2762
        conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
2763
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
2764
2765
    def test_auth_section_header_not_closed(self):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2766
        conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
2767
        self.assertRaises(errors.ParseConfigError, conf._get_config)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
2768
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
2769
    def test_auth_value_not_boolean(self):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
2770
        conf = config.AuthenticationConfig(_file=StringIO(
2771
                """[broken]
2772
scheme=ftp
2773
user=joe
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
2774
verify_certificates=askme # Error: Not a boolean
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
2775
"""))
2776
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
2777
2778
    def test_auth_value_not_int(self):
2900.2.22 by Vincent Ladeuil
Polishing.
2779
        conf = config.AuthenticationConfig(_file=StringIO(
2780
                """[broken]
2781
scheme=ftp
2782
user=joe
2783
port=port # Error: Not an int
2784
"""))
2785
        self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2786
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2787
    def test_unknown_password_encoding(self):
2788
        conf = config.AuthenticationConfig(_file=StringIO(
2789
                """[broken]
2790
scheme=ftp
2791
user=joe
2792
password_encoding=unknown
2793
"""))
2794
        self.assertRaises(ValueError, conf.get_password,
2795
                          'ftp', 'foo.net', 'joe')
2796
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2797
    def test_credentials_for_scheme_host(self):
2798
        conf = config.AuthenticationConfig(_file=StringIO(
2799
                """# Identity on foo.net
2800
[ftp definition]
2801
scheme=ftp
2802
host=foo.net
2803
user=joe
2804
password=secret-pass
2805
"""))
2806
        # Basic matching
2807
        self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
2808
        # different scheme
2809
        self._got_user_passwd(None, None, conf, 'http', 'foo.net')
2810
        # different host
2811
        self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
2812
2813
    def test_credentials_for_host_port(self):
2814
        conf = config.AuthenticationConfig(_file=StringIO(
2815
                """# Identity on foo.net
2816
[ftp definition]
2817
scheme=ftp
2818
port=10021
2819
host=foo.net
2820
user=joe
2821
password=secret-pass
2822
"""))
2823
        # No port
2824
        self._got_user_passwd('joe', 'secret-pass',
2825
                              conf, 'ftp', 'foo.net', port=10021)
2826
        # different port
2827
        self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
2828
2829
    def test_for_matching_host(self):
2830
        conf = config.AuthenticationConfig(_file=StringIO(
2831
                """# Identity on foo.net
2832
[sourceforge]
2833
scheme=bzr
2834
host=bzr.sf.net
2835
user=joe
2836
password=joepass
2837
[sourceforge domain]
2838
scheme=bzr
2839
host=.bzr.sf.net
2840
user=georges
2841
password=bendover
2842
"""))
2843
        # matching domain
2844
        self._got_user_passwd('georges', 'bendover',
2845
                              conf, 'bzr', 'foo.bzr.sf.net')
2846
        # phishing attempt
2847
        self._got_user_passwd(None, None,
2848
                              conf, 'bzr', 'bbzr.sf.net')
2849
2850
    def test_for_matching_host_None(self):
2851
        conf = config.AuthenticationConfig(_file=StringIO(
2852
                """# Identity on foo.net
2853
[catchup bzr]
2854
scheme=bzr
2855
user=joe
2856
password=joepass
2857
[DEFAULT]
2858
user=georges
2859
password=bendover
2860
"""))
2861
        # match no host
2862
        self._got_user_passwd('joe', 'joepass',
2863
                              conf, 'bzr', 'quux.net')
2864
        # no host but different scheme
2865
        self._got_user_passwd('georges', 'bendover',
2866
                              conf, 'ftp', 'quux.net')
2867
2868
    def test_credentials_for_path(self):
2869
        conf = config.AuthenticationConfig(_file=StringIO(
2870
                """
2871
[http dir1]
2872
scheme=http
2873
host=bar.org
2874
path=/dir1
2875
user=jim
2876
password=jimpass
2877
[http dir2]
2878
scheme=http
2879
host=bar.org
2880
path=/dir2
2881
user=georges
2882
password=bendover
2883
"""))
2884
        # no path no dice
2885
        self._got_user_passwd(None, None,
2886
                              conf, 'http', host='bar.org', path='/dir3')
2887
        # matching path
2888
        self._got_user_passwd('georges', 'bendover',
2889
                              conf, 'http', host='bar.org', path='/dir2')
2890
        # matching subdir
2891
        self._got_user_passwd('jim', 'jimpass',
2892
                              conf, 'http', host='bar.org',path='/dir1/subdir')
2893
2894
    def test_credentials_for_user(self):
2895
        conf = config.AuthenticationConfig(_file=StringIO(
2896
                """
2897
[with user]
2898
scheme=http
2899
host=bar.org
2900
user=jim
2901
password=jimpass
2902
"""))
2903
        # Get user
2904
        self._got_user_passwd('jim', 'jimpass',
2905
                              conf, 'http', 'bar.org')
2906
        # Get same user
2907
        self._got_user_passwd('jim', 'jimpass',
2908
                              conf, 'http', 'bar.org', user='jim')
2909
        # Don't get a different user if one is specified
2910
        self._got_user_passwd(None, None,
2911
                              conf, 'http', 'bar.org', user='georges')
2912
3418.4.1 by Vincent Ladeuil
Reproduce bug 199440.
2913
    def test_credentials_for_user_without_password(self):
2914
        conf = config.AuthenticationConfig(_file=StringIO(
2915
                """
2916
[without password]
2917
scheme=http
2918
host=bar.org
2919
user=jim
2920
"""))
2921
        # Get user but no password
2922
        self._got_user_passwd('jim', None,
2923
                              conf, 'http', 'bar.org')
2924
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
2925
    def test_verify_certificates(self):
2926
        conf = config.AuthenticationConfig(_file=StringIO(
2927
                """
2928
[self-signed]
2929
scheme=https
2930
host=bar.org
2931
user=jim
2932
password=jimpass
2933
verify_certificates=False
2934
[normal]
2935
scheme=https
2936
host=foo.net
2937
user=georges
2938
password=bendover
2939
"""))
2940
        credentials = conf.get_credentials('https', 'bar.org')
2941
        self.assertEquals(False, credentials.get('verify_certificates'))
2942
        credentials = conf.get_credentials('https', 'foo.net')
2943
        self.assertEquals(True, credentials.get('verify_certificates'))
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
2944
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2945
2946
class TestAuthenticationStorage(tests.TestCaseInTempDir):
2947
3777.1.8 by Aaron Bentley
Commit work-in-progress
2948
    def test_set_credentials(self):
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2949
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
2950
        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
2951
        99, path='/foo', verify_certificates=False, realm='realm')
3777.1.8 by Aaron Bentley
Commit work-in-progress
2952
        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
2953
                                           port=99, path='/foo',
2954
                                           realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2955
        CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
2956
                       'verify_certificates': False, 'scheme': 'scheme', 
2957
                       'host': 'host', 'port': 99, 'path': '/foo', 
2958
                       'realm': 'realm'}
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2959
        self.assertEqual(CREDENTIALS, credentials)
2960
        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
2961
            host='host', scheme='scheme', port=99, path='/foo', realm='realm')
3777.1.10 by Aaron Bentley
Ensure credentials are stored
2962
        self.assertEqual(CREDENTIALS, credentials_from_disk)
3777.1.8 by Aaron Bentley
Commit work-in-progress
2963
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
2964
    def test_reset_credentials_different_name(self):
2965
        conf = config.AuthenticationConfig()
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
2966
        conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
2967
        conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
2968
        self.assertIs(None, conf._get_config().get('name'))
2969
        credentials = conf.get_credentials(host='host', scheme='scheme')
2970
        CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
4107.1.8 by Jean-Francois Roy
Updated test_config to account for the new credentials keys.
2971
                       'password', 'verify_certificates': True, 
2972
                       'scheme': 'scheme', 'host': 'host', 'port': None, 
2973
                       'path': None, 'realm': None}
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
2974
        self.assertEqual(CREDENTIALS, credentials)
2975
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
2976
2900.2.14 by Vincent Ladeuil
More tests.
2977
class TestAuthenticationConfig(tests.TestCase):
2978
    """Test AuthenticationConfig behaviour"""
2979
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
2980
    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.
2981
                                       host=None, port=None, realm=None,
2982
                                       path=None):
2900.2.14 by Vincent Ladeuil
More tests.
2983
        if host is None:
2984
            host = 'bar.org'
2985
        user, password = 'jim', 'precious'
2986
        expected_prompt = expected_prompt_format % {
2987
            'scheme': scheme, 'host': host, 'port': port,
2988
            'user': user, 'realm': realm}
2989
2990
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2991
        stderr = tests.StringIOWrapper()
2900.2.14 by Vincent Ladeuil
More tests.
2992
        ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2993
                                            stdout=stdout, stderr=stderr)
2900.2.14 by Vincent Ladeuil
More tests.
2994
        # We use an empty conf so that the user is always prompted
2995
        conf = config.AuthenticationConfig()
2996
        self.assertEquals(password,
2997
                          conf.get_password(scheme, host, user, port=port,
2998
                                            realm=realm, path=path))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
2999
        self.assertEquals(expected_prompt, stderr.getvalue())
3000
        self.assertEquals('', stdout.getvalue())
2900.2.14 by Vincent Ladeuil
More tests.
3001
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
3002
    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.
3003
                                       host=None, port=None, realm=None,
3004
                                       path=None):
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
3005
        if host is None:
3006
            host = 'bar.org'
3007
        username = 'jim'
3008
        expected_prompt = expected_prompt_format % {
3009
            'scheme': scheme, 'host': host, 'port': port,
3010
            'realm': realm}
3011
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
3012
        stderr = tests.StringIOWrapper()
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
3013
        ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
3014
                                            stdout=stdout, stderr=stderr)
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
3015
        # We use an empty conf so that the user is always prompted
3016
        conf = config.AuthenticationConfig()
4222.3.5 by Jelmer Vernooij
Fix test.
3017
        self.assertEquals(username, conf.get_user(scheme, host, port=port,
3018
                          realm=realm, path=path, ask=True))
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
3019
        self.assertEquals(expected_prompt, stderr.getvalue())
3020
        self.assertEquals('', stdout.getvalue())
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
3021
3022
    def test_username_defaults_prompts(self):
3023
        # HTTP prompts can't be tested here, see test_http.py
5923.1.3 by Vincent Ladeuil
Even more unicode prompts fixes revealed by pqm.
3024
        self._check_default_username_prompt(u'FTP %(host)s username: ', 'ftp')
3025
        self._check_default_username_prompt(
3026
            u'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
3027
        self._check_default_username_prompt(
3028
            u'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
3029
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
3030
    def test_username_default_no_prompt(self):
3031
        conf = config.AuthenticationConfig()
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
3032
        self.assertEquals(None,
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
3033
            conf.get_user('ftp', 'example.com'))
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
3034
        self.assertEquals("explicitdefault",
4222.3.11 by Jelmer Vernooij
Add test to make sure the default= parameter works.
3035
            conf.get_user('ftp', 'example.com', default="explicitdefault"))
3036
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
3037
    def test_password_default_prompts(self):
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
3038
        # HTTP prompts can't be tested here, see test_http.py
4222.3.1 by Jelmer Vernooij
Mention password when checking default prompt.
3039
        self._check_default_password_prompt(
5923.1.3 by Vincent Ladeuil
Even more unicode prompts fixes revealed by pqm.
3040
            u'FTP %(user)s@%(host)s password: ', 'ftp')
3041
        self._check_default_password_prompt(
3042
            u'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
3043
        self._check_default_password_prompt(
3044
            u'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
2900.2.14 by Vincent Ladeuil
More tests.
3045
        # SMTP port handling is a bit special (it's handled if embedded in the
3046
        # host too)
2900.2.22 by Vincent Ladeuil
Polishing.
3047
        # FIXME: should we: forbid that, extend it to other schemes, leave
3048
        # things as they are that's fine thank you ?
5923.1.3 by Vincent Ladeuil
Even more unicode prompts fixes revealed by pqm.
3049
        self._check_default_password_prompt(
3050
            u'SMTP %(user)s@%(host)s password: ', 'smtp')
3051
        self._check_default_password_prompt(
3052
            u'SMTP %(user)s@%(host)s password: ', 'smtp', host='bar.org:10025')
3053
        self._check_default_password_prompt(
3054
            u'SMTP %(user)s@%(host)s:%(port)d password: ', 'smtp', port=10025)
2900.2.14 by Vincent Ladeuil
More tests.
3055
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
3056
    def test_ssh_password_emits_warning(self):
3057
        conf = config.AuthenticationConfig(_file=StringIO(
3058
                """
3059
[ssh with password]
3060
scheme=ssh
3061
host=bar.org
3062
user=jim
3063
password=jimpass
3064
"""))
3065
        entered_password = 'typed-by-hand'
3066
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
3067
        stderr = tests.StringIOWrapper()
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
3068
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
3069
                                            stdout=stdout, stderr=stderr)
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
3070
3071
        # Since the password defined in the authentication config is ignored,
3072
        # the user is prompted
3073
        self.assertEquals(entered_password,
3074
                          conf.get_password('ssh', 'bar.org', user='jim'))
3075
        self.assertContainsRe(
4794.1.17 by Robert Collins
Fix from vila for type log_log.
3076
            self.get_log(),
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
3077
            'password ignored in section \[ssh with password\]')
3078
3420.1.3 by Vincent Ladeuil
John's review feedback.
3079
    def test_ssh_without_password_doesnt_emit_warning(self):
3080
        conf = config.AuthenticationConfig(_file=StringIO(
3081
                """
3082
[ssh with password]
3083
scheme=ssh
3084
host=bar.org
3085
user=jim
3086
"""))
3087
        entered_password = 'typed-by-hand'
3088
        stdout = tests.StringIOWrapper()
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
3089
        stderr = tests.StringIOWrapper()
3420.1.3 by Vincent Ladeuil
John's review feedback.
3090
        ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
4449.3.30 by Martin Pool
Tweaks to test_config ui factory use
3091
                                            stdout=stdout,
3092
                                            stderr=stderr)
3420.1.3 by Vincent Ladeuil
John's review feedback.
3093
3094
        # Since the password defined in the authentication config is ignored,
3095
        # the user is prompted
3096
        self.assertEquals(entered_password,
3097
                          conf.get_password('ssh', 'bar.org', user='jim'))
3420.1.4 by Vincent Ladeuil
Fix comment.
3098
        # No warning shoud be emitted since there is no password. We are only
3099
        # providing "user".
3420.1.3 by Vincent Ladeuil
John's review feedback.
3100
        self.assertNotContainsRe(
4794.1.15 by Robert Collins
Review feedback.
3101
            self.get_log(),
3420.1.3 by Vincent Ladeuil
John's review feedback.
3102
            'password ignored in section \[ssh with password\]')
3103
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
3104
    def test_uses_fallback_stores(self):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
3105
        self.overrideAttr(config, 'credential_store_registry',
3106
                          config.CredentialStoreRegistry())
4283.1.3 by Jelmer Vernooij
Add test to make sure AuthenticationConfig queries for fallback credentials.
3107
        store = StubCredentialStore()
3108
        store.add_credentials("http", "example.com", "joe", "secret")
3109
        config.credential_store_registry.register("stub", store, fallback=True)
3110
        conf = config.AuthenticationConfig(_file=StringIO())
3111
        creds = conf.get_credentials("http", "example.com")
3112
        self.assertEquals("joe", creds["user"])
3113
        self.assertEquals("secret", creds["password"])
3114
2900.2.14 by Vincent Ladeuil
More tests.
3115
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3116
class StubCredentialStore(config.CredentialStore):
3117
3118
    def __init__(self):
3119
        self._username = {}
3120
        self._password = {}
3121
3122
    def add_credentials(self, scheme, host, user, password=None):
3123
        self._username[(scheme, host)] = user
3124
        self._password[(scheme, host)] = password
3125
3126
    def get_credentials(self, scheme, host, port=None, user=None,
3127
        path=None, realm=None):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3128
        key = (scheme, host)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3129
        if not key in self._username:
3130
            return None
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3131
        return { "scheme": scheme, "host": host, "port": port,
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3132
                "user": self._username[key], "password": self._password[key]}
3133
3134
3135
class CountingCredentialStore(config.CredentialStore):
3136
3137
    def __init__(self):
3138
        self._calls = 0
3139
3140
    def get_credentials(self, scheme, host, port=None, user=None,
3141
        path=None, realm=None):
3142
        self._calls += 1
3143
        return None
3144
3145
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
3146
class TestCredentialStoreRegistry(tests.TestCase):
3147
3148
    def _get_cs_registry(self):
3149
        return config.credential_store_registry
3150
3151
    def test_default_credential_store(self):
3152
        r = self._get_cs_registry()
3153
        default = r.get_credential_store(None)
3154
        self.assertIsInstance(default, config.PlainTextCredentialStore)
3155
3156
    def test_unknown_credential_store(self):
3157
        r = self._get_cs_registry()
3158
        # It's hard to imagine someone creating a credential store named
3159
        # 'unknown' so we use that as an never registered key.
3160
        self.assertRaises(KeyError, r.get_credential_store, 'unknown')
3161
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3162
    def test_fallback_none_registered(self):
3163
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3164
        self.assertEquals(None,
3165
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3166
3167
    def test_register(self):
3168
        r = config.CredentialStoreRegistry()
3169
        r.register("stub", StubCredentialStore(), fallback=False)
3170
        r.register("another", StubCredentialStore(), fallback=True)
3171
        self.assertEquals(["another", "stub"], r.keys())
3172
3173
    def test_register_lazy(self):
3174
        r = config.CredentialStoreRegistry()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3175
        r.register_lazy("stub", "bzrlib.tests.test_config",
3176
                        "StubCredentialStore", fallback=False)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3177
        self.assertEquals(["stub"], r.keys())
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3178
        self.assertIsInstance(r.get_credential_store("stub"),
3179
                              StubCredentialStore)
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3180
3181
    def test_is_fallback(self):
3182
        r = config.CredentialStoreRegistry()
3183
        r.register("stub1", None, fallback=False)
3184
        r.register("stub2", None, fallback=True)
3185
        self.assertEquals(False, r.is_fallback("stub1"))
3186
        self.assertEquals(True, r.is_fallback("stub2"))
3187
3188
    def test_no_fallback(self):
3189
        r = config.CredentialStoreRegistry()
3190
        store = CountingCredentialStore()
3191
        r.register("count", store, fallback=False)
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3192
        self.assertEquals(None,
3193
                          r.get_fallback_credentials("http", "example.com"))
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3194
        self.assertEquals(0, store._calls)
3195
3196
    def test_fallback_credentials(self):
3197
        r = config.CredentialStoreRegistry()
3198
        store = StubCredentialStore()
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3199
        store.add_credentials("http", "example.com",
3200
                              "somebody", "geheim")
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
3201
        r.register("stub", store, fallback=True)
3202
        creds = r.get_fallback_credentials("http", "example.com")
3203
        self.assertEquals("somebody", creds["user"])
3204
        self.assertEquals("geheim", creds["password"])
3205
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
3206
    def test_fallback_first_wins(self):
3207
        r = config.CredentialStoreRegistry()
3208
        stub1 = StubCredentialStore()
3209
        stub1.add_credentials("http", "example.com",
3210
                              "somebody", "stub1")
3211
        r.register("stub1", stub1, fallback=True)
3212
        stub2 = StubCredentialStore()
3213
        stub2.add_credentials("http", "example.com",
3214
                              "somebody", "stub2")
3215
        r.register("stub2", stub1, fallback=True)
3216
        creds = r.get_fallback_credentials("http", "example.com")
3217
        self.assertEquals("somebody", creds["user"])
3218
        self.assertEquals("stub1", creds["password"])
3219
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
3220
3221
class TestPlainTextCredentialStore(tests.TestCase):
3222
3223
    def test_decode_password(self):
3224
        r = config.credential_store_registry
3225
        plain_text = r.get_credential_store()
3226
        decoded = plain_text.decode_password(dict(password='secret'))
3227
        self.assertEquals('secret', decoded)
3228
3229
2900.2.14 by Vincent Ladeuil
More tests.
3230
# 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.
3231
# can implement generic tests.
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
3232
# test_user_password_in_url
3233
# test_user_in_url_password_from_config
3234
# test_user_in_url_password_prompted
3235
# test_user_in_config
3236
# test_user_getpass.getuser
3237
# test_user_prompted ?
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
3238
class TestAuthenticationRing(tests.TestCaseWithTransport):
3239
    pass
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
3240
3241
3242
class TestAutoUserId(tests.TestCase):
3243
    """Test inferring an automatic user name."""
3244
3245
    def test_auto_user_id(self):
3246
        """Automatic inference of user name.
3247
        
3248
        This is a bit hard to test in an isolated way, because it depends on
3249
        system functions that go direct to /etc or perhaps somewhere else.
3250
        But it's reasonable to say that on Unix, with an /etc/mailname, we ought
3251
        to be able to choose a user name with no configuration.
3252
        """
3253
        if sys.platform == 'win32':
3254
            raise TestSkipped("User name inference not implemented on win32")
3255
        realname, address = config._auto_user_id()
3256
        if os.path.exists('/etc/mailname'):
5813.1.1 by Jelmer Vernooij
Allow realname to be empty in tests.
3257
            self.assertIsNot(None, realname)
3258
            self.assertIsNot(None, address)
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
3259
        else:
3260
            self.assertEquals((None, None), (realname, address))
3261