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