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