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