/brz/remove-bazaar

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