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