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