/brz/remove-bazaar

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