/brz/remove-bazaar

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