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