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