/brz/remove-bazaar

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