/brz/remove-bazaar

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