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