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